diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_compare_date_with_time_zone_untyped.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_compare_date_with_time_zone_untyped.dmn new file mode 100644 index 0000000000000000000000000000000000000000..c7ca247e199fe790234f8b059e1745e90c4b68b9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_compare_date_with_time_zone_untyped.dmn @@ -0,0 +1,29 @@ + + + + + + + date1 + + + + + + <= date and time("2019-09-12T13:00:00@Europe/Berlin") + + + "foo" + + + + + > date and time("2019-09-12T13:00:00@Europe/Berlin") + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_pojo_comparison.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_pojo_comparison.dmn new file mode 100644 index 0000000000000000000000000000000000000000..6124418691b3ddfa28b9b03acf73942b4a98e2e0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_pojo_comparison.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + pojoOne + + + + + + pojoOne + + + "foo" + + + + + pojoTwo + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_single_quotes.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_single_quotes.dmn new file mode 100644 index 0000000000000000000000000000000000000000..e23a6949a3d5e9d4821bbf1710331e151c7437d0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_single_quotes.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + input + + + + + + 'Hello World' + + + "foo" + + + + + 'Hello Dog' + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_spin.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_spin.dmn new file mode 100644 index 0000000000000000000000000000000000000000..213d23ed38b426e35a02bec3041dd93145a7eba6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_spin.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + ${foo.getClass().getSimpleName() == "bla"} + + + + + + foo.prop("foo").numberValue() > 7 + + + "foo" + + + + + foo.prop("foo").numberValue() <= 7 + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_spin_context.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_spin_context.dmn new file mode 100644 index 0000000000000000000000000000000000000000..f82b5585f9567f687ae9ef79b0a5a485881c17af --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_spin_context.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + true + + + + + + (foo.bar > 7) + + + "foo" + + + + + (foo.bar <= 7) + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_unary_test_boolean.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_unary_test_boolean.dmn new file mode 100644 index 0000000000000000000000000000000000000000..5b37868fc4724adf0857de10acd8317fc1ceb5d2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_unary_test_boolean.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + ${true} + + + + + + 8 > 7 + + + "foo" + + + + + 8 <= 7 + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_unary_test_compare_short_untyped.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_unary_test_compare_short_untyped.dmn new file mode 100644 index 0000000000000000000000000000000000000000..05d05110f7b3118d3c924866b4f953026e080514 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/breaking_unary_test_compare_short_untyped.dmn @@ -0,0 +1,32 @@ + + + + + + + numberInput + + + + + + >= 5.66 + + + false + + + + + < 5.66 + + + true + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/compare_dates_non_typed.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/compare_dates_non_typed.dmn new file mode 100644 index 0000000000000000000000000000000000000000..92d0e255dd8c111c560216a19721eb2b01298e18 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/compare_dates_non_typed.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + date1 + + + + + + <= date2 + + + "foo" + + + + + > date2 + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/context_function.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/context_function.dmn new file mode 100644 index 0000000000000000000000000000000000000000..2576496d691fdcba73b58b11d06831fb387ccb11 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/context_function.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + myDate + + + + + + not(dateTime()) + + + "foo" + + + + + dateTime() + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/custom_function.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/custom_function.dmn new file mode 100644 index 0000000000000000000000000000000000000000..6d0d2a82776246d9d7f10d12fca40265d40396ad --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/custom_function.dmn @@ -0,0 +1,13 @@ + + + + + + + myFunctionOne()+myFunctionTwo() + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/input_date_typed.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/input_date_typed.dmn new file mode 100644 index 0000000000000000000000000000000000000000..3efd4f1a62ca3a8e5d92ba42a8023ce542b2dce0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/input_date_typed.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + date1 + + + + + + <=date and time("2014-11-30T12:00:00") + + + "ok" + + + + + >date and time("2014-11-30T12:00:00") + + + "not ok" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/java_object.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/java_object.dmn new file mode 100644 index 0000000000000000000000000000000000000000..7e79d6efc1b64db46b00c4e658c9405d6d3eecdd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/java_object.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + date1 + + + + + + > person.getBirthday() + + + "foo" + + + + + <= person.getBirthday() + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/mixed_variable_types.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/mixed_variable_types.dmn new file mode 100644 index 0000000000000000000000000000000000000000..c4ae1954ad5becf47cd0e4b66aa519e6c5287a27 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/mixed_variable_types.dmn @@ -0,0 +1,40 @@ + + + + + + + stringInput + + + + + numberInput + + + + + booleanInput + + + + + + "camunda" + + + >= 12 + + + true + + + true + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/number_untyped.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/number_untyped.dmn new file mode 100644 index 0000000000000000000000000000000000000000..05d05110f7b3118d3c924866b4f953026e080514 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/number_untyped.dmn @@ -0,0 +1,32 @@ + + + + + + + numberInput + + + + + + >= 5.66 + + + false + + + + + < 5.66 + + + true + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_compare_date_untyped.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_compare_date_untyped.dmn new file mode 100644 index 0000000000000000000000000000000000000000..422cff894b15c37234dcf0d1f54c1e1de2a1e15e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_compare_date_untyped.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + date1 + + + + + + <=date and time("2014-11-30T12:00:00") + + + "ok" + + + + + >date and time("2014-11-30T12:00:00") + + + "not ok" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_compare_date_with_time_zone_non_typed.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_compare_date_with_time_zone_non_typed.dmn new file mode 100644 index 0000000000000000000000000000000000000000..33348f16f461a2d3e619705d6ca0ccf524f4a34e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_compare_date_with_time_zone_non_typed.dmn @@ -0,0 +1,29 @@ + + + + + + + date1 + + + + + + <= date and time("2019-09-12T13:00:00@Europe/Berlin") + + + "foo" + + + + + > date and time("2019-09-12T13:00:00@Europe/Berlin") + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_date_typed_output.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_date_typed_output.dmn new file mode 100644 index 0000000000000000000000000000000000000000..2ada5ca16c36b29912bb8096a79de39958735024 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_date_typed_output.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + "foo" + + + + + + "bar" + + + date and time("2019-08-08T22:22:22") + + + + + "foo" + + + date and time("2019-08-08T22:22:22") + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_input_expression.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_input_expression.dmn new file mode 100644 index 0000000000000000000000000000000000000000..794d1424050ce25ca4a3e428bcc944add17d08c8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_input_expression.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + date1 > date2 + + + + + + true + + + "foo" + + + + + false + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_input_expression_builtin_function.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_input_expression_builtin_function.dmn new file mode 100644 index 0000000000000000000000000000000000000000..309375753fb2c75e233f6b1f36d5018f10c218ac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_input_expression_builtin_function.dmn @@ -0,0 +1,32 @@ + + + + + + + + + + date1 > date and time("2015-11-30T12:00:00") + + + + + + true + + + "foo" + + + + + false + + + "bar" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_literal_expression_date_typed.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_literal_expression_date_typed.dmn new file mode 100644 index 0000000000000000000000000000000000000000..5976e2957cd3a8a5074df08d5079f3ad9a41ed73 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_literal_expression_date_typed.dmn @@ -0,0 +1,17 @@ + + + + + + + + + date1 + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_output_expression_double.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_output_expression_double.dmn new file mode 100644 index 0000000000000000000000000000000000000000..f527bca11db8babd9dc692e124d32503302067fe --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_output_expression_double.dmn @@ -0,0 +1,24 @@ + + + + + + + + + + true + + + + + + true + + + myVariable + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_unary_builtin_function.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_unary_builtin_function.dmn new file mode 100644 index 0000000000000000000000000000000000000000..f8689c5e029f4b7044eb0849ba426f01572e0960 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/scala_unary_builtin_function.dmn @@ -0,0 +1,21 @@ + + + + + + + integerString + + + + + + number(integerString) + + + integerString + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/string_untyped.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/string_untyped.dmn new file mode 100644 index 0000000000000000000000000000000000000000..f6fa635696444ea6838fd4f3bdf60b8f4c657d21 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/feel/string_untyped.dmn @@ -0,0 +1,32 @@ + + + + + + + stringInput + + + + + + "foo" + + + false + + + + + "bar" + + + true + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..9d6aaf18c640d7db33653f5bccc32bedf93a615f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..757e1aa802b9fab9cc5f7af7c5bc22d59895b485 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.any.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..f31149e5c4de93c203b527eb06879ce32395e955 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..a14b074c4cc72b8d3ea7f3b2123996e3020e143b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..795184530201907a012d008d01fdc06b7aba5bfb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.count.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..29976427503a0c70b04c69f6a8b8d83059476e9a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..5d68d0cd7a684c11fcdb6c05e498d316e36cce0c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.max.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..a45b9932099a333718f07ec2074071ad0aefb3e9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..27495f7848f30733b0213034e27a4160af357855 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.min.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..9adb8692aa6401009d7802e01c7a9a3cc8fd866f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..b68b7e4fc09e5a9cdd836532041b62b4f2446f0c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..e5a9f9c93907fc1af855c1788bae02e2e6dedc53 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.collect.sum.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..06381f09b2953eec076a17ce74f0a02471f76390 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..3f6df884a711f430c1d02d1feb50b3a9b499ecef --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.default.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..7dd6753e78c701cf7aa45597394f1c03ca26ab27 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..2deeae44c473b5f69eaffa01b40acd02e5db73c9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.first.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.outputOrder.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.outputOrder.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..d87344ca58712ec4cf272c29a98f0cde83a51176 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.outputOrder.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.priority.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.priority.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..d8e081c0a89b3b3e3aa08491a3776098bd80bc9c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.priority.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..19fdfd9b581043ae4908d11dfbd59030e7f8fa45 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..2519c4353d712cc448506f76d45b922338e61bb7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.ruleOrder.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.compound.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.compound.dmn new file mode 100644 index 0000000000000000000000000000000000000000..5c70ca155b8ff1775aa69ed83acb63996d189204 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.compound.dmn @@ -0,0 +1,59 @@ + + + + + + + + + + + + + ${input1} + + + ${output1} + + + ${output1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + ${output2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + ${output3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.single.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.single.dmn new file mode 100644 index 0000000000000000000000000000000000000000..416289be8cded648ab952fb1b5a88eda35a89c98 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/hitpolicy/HitPolicyTest.unique.single.dmn @@ -0,0 +1,39 @@ + + + + + + + + + + + ${input1} + + + ${output1} + + + + + ${input2} + + + ${output2} + + + + + ${input3} + + + ${output3} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DecisionWithLiteralExpression.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DecisionWithLiteralExpression.dmn new file mode 100644 index 0000000000000000000000000000000000000000..72dda428247f2c5397d222592942de73d88b06b1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DecisionWithLiteralExpression.dmn @@ -0,0 +1,13 @@ + + + + + + + a + b + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DmnDecisionTransform.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DmnDecisionTransform.dmn new file mode 100644 index 0000000000000000000000000000000000000000..acb6ef9309ed1e9eda4403d0b0e97aabc2702f79 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DmnDecisionTransform.dmn @@ -0,0 +1,26 @@ + + + + + + + + camunda + + + + + + camunda + + + camunda + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DmnTransformTest.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DmnTransformTest.dmn new file mode 100644 index 0000000000000000000000000000000000000000..f52e533c154d1e1f2d6acc83f3f40c0305c0ad40 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DmnTransformTest.dmn @@ -0,0 +1,45 @@ + + + + + + + + camunda + + + + + + + + + + + + camunda + + + + + + camunda + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgCollectTest.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgCollectTest.dmn new file mode 100644 index 0000000000000000000000000000000000000000..8c6f88c0082d0ecb2a0bf666838dc9d214310955 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgCollectTest.dmn @@ -0,0 +1,43 @@ + + + + + + + + + + guestCount.size() + + + + + + cellInput == 1 + + + + + + + + + + + + dayType + + + + + + + + + 4 + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgExample.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgExample.dmn new file mode 100644 index 0000000000000000000000000000000000000000..06e10449970550d3d435f33d4b88ee26edef45f2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgExample.dmn @@ -0,0 +1,71 @@ + + + + + + + + + + + + + season + + + + + guestCount + + + + + + + + + + + + + + + + + + + + + temperature + + + + + + 30]]> + + + + + + + + + + + + dayType + + + + + + + + + 4 + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgRuleOrderTest.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgRuleOrderTest.dmn new file mode 100644 index 0000000000000000000000000000000000000000..709f3f6582b57c4d5be1de126d85c88d5a902fc4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/transform/DrgRuleOrderTest.dmn @@ -0,0 +1,43 @@ + + + + + + + + + + guestCount.size() + + + + + + cellInput == 1 + + + + + + + + + + + + dayType + + + + + + + + + 4 + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/CustomInputDefinition.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/CustomInputDefinition.dmn new file mode 100644 index 0000000000000000000000000000000000000000..a71e2cbf43800d28fdfde71f945e7c5ba049e437 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/CustomInputDefinition.dmn @@ -0,0 +1,33 @@ + + + + + + + input + + + + + + + 42 + + + "isCustom" + + + + + + + + "isOriginal" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/CustomOutputDefinition.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/CustomOutputDefinition.dmn new file mode 100644 index 0000000000000000000000000000000000000000..5c2e6ae4463377a2b6dc0776b48ec305abdfcd15 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/CustomOutputDefinition.dmn @@ -0,0 +1,17 @@ + + + + + + + + + ${output} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-Input.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-Input.dmn new file mode 100644 index 0000000000000000000000000000000000000000..6335a12b72b34a64aae82162214b6d4b778817ba --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-Input.dmn @@ -0,0 +1,33 @@ + + + + + + + + input + + + + + + 42 + + + "is transformed" + + + + + + + + "is not transformed" + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-NoTypes.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-NoTypes.dmn new file mode 100644 index 0000000000000000000000000000000000000000..84020a4131cff4655e807697c8759811c61e616e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-NoTypes.dmn @@ -0,0 +1,25 @@ + + + + + + + + input + + + + + + + + + ${output} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-Output.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-Output.dmn new file mode 100644 index 0000000000000000000000000000000000000000..70f59f23d1f47c1aa63fc9194a8997178d907350 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/DataTypeTransformerTest-Output.dmn @@ -0,0 +1,17 @@ + + + + + + + + + ${output} + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/TypedValue.dmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/TypedValue.dmn new file mode 100644 index 0000000000000000000000000000000000000000..8afea259dad45c163c22777fa93dcf8df8469a90 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/engine/src/test/resources/org/camunda/bpm/dmn/engine/type/TypedValue.dmn @@ -0,0 +1,66 @@ + + + + + + + + type + + + + + integer + + + + + + "typed" + + + = 42}]]> + + + true + + + + + "untyped" + + + = 42}]]> + + + true + + + + + "typed" + + + + + + false + + + + + "untyped" + + + + + + false + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..dcf9ed233daa1a96c90def13b40921ae7d2c1176 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + org.camunda.bpm.dmn + camunda-engine-dmn-root + 7.24.0-SNAPSHOT + + + camunda-engine-feel-api + camunda DMN - engine FEEL - API + + org.camunda.bpm.dmn.feel.impl + + + + org.camunda.commons + camunda-commons-typed-values + + + + + + + org.apache.felix + maven-bundle-plugin + + + generate-sources + + cleanVersions + + + + bundle-manifest + process-classes + + manifest + + + + + + + + + + + check-api-compatibility + + true + + + + + org.codehaus.mojo + clirr-maven-plugin + + ${camunda.version.old} + true + + org/camunda/bpm/dmn/feel/impl/** + + + + + all + verify + + check-no-fork + + + ${project.build.directory}/clirr-all.txt + false + false + + + + restrictive + verify + + check-no-fork + + + ${project.build.directory}/clirr-restrictive.txt + true + ../.clirr-jenkins-ignore.xml + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelEngine.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelEngine.java new file mode 100644 index 0000000000000000000000000000000000000000..7654438ff1efa5a7609a4fc2db03dda145013103 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelEngine.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl; + +import org.camunda.bpm.engine.variable.context.VariableContext; + +/** + * Engine to evaluate FEEL expressions. + */ +public interface FeelEngine { + + /** + * Evaluate a FEEL simple expression + * + * @param simpleExpression the simple expression to evaluate + * @param variableContext the variable context which are available + * @param the expected return type + * @return the result of the simple expression + * + * @throws FeelException + * if the expression cannot be evaluated + */ + T evaluateSimpleExpression(String simpleExpression, VariableContext variableContext); + + /** + * Evaluate a FEEL simple unary tests expression + * + * @param simpleUnaryTests the simple unary tests expression to evaluate + * @param inputName the name of the variable which is tested + * @param variableContext the variable context are available + * @return the result of the simple unary tests expression + * + * @throws FeelException + * if the expression cannot be evaluated + */ + boolean evaluateSimpleUnaryTests(String simpleUnaryTests, String inputName, VariableContext variableContext); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelEngineFactory.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelEngineFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..b747b786d0b34443751a6c440f5b7b6859f4bace --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelEngineFactory.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl; + +/** + * Factory to create a instance of a {@link FeelEngine}. + */ +public interface FeelEngineFactory { + + /** + * Create an instance of a {@link FeelEngine}. + * + * @return the instance of a {@link FeelEngine} + */ + FeelEngine createInstance(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelException.java new file mode 100644 index 0000000000000000000000000000000000000000..fe881b66b41c4266a9dbb9f3fc5b314010ec61fc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-api/src/main/java/org/camunda/bpm/dmn/feel/impl/FeelException.java @@ -0,0 +1,33 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl; + +/** + * Exception which is thrown if a error occurs during the + * evaluation of a FEEL expression. + */ +public class FeelException extends RuntimeException { + + public FeelException(String message) { + super(message); + } + + public FeelException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..ce1311738da7719fafc19bc60231f626eb247b3e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/pom.xml @@ -0,0 +1,133 @@ + + + 4.0.0 + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + org.camunda.bpm.dmn + camunda-engine-dmn-root + 7.24.0-SNAPSHOT + + + camunda-engine-feel-juel + camunda DMN - engine FEEL - JUEL + + + org.camunda.bpm.dmn.feel.impl.juel + + + + org.camunda.bpm.dmn + camunda-engine-feel-api + + + + org.camunda.commons + camunda-commons-logging + + + + org.camunda.commons + camunda-commons-typed-values + + + + org.camunda.bpm.juel + camunda-juel + + + + junit + junit + test + + + + org.assertj + assertj-core + test + + + + + + + + org.apache.felix + maven-bundle-plugin + + + generate-sources + + cleanVersions + + + + bundle-manifest + process-classes + + manifest + + + + + + + + + + + check-api-compatibility + + true + + + + + org.codehaus.mojo + clirr-maven-plugin + + ${camunda.version.old} + true + + org/camunda/bpm/dmn/feel/impl/** + + camundafeel/** + + + + + all + verify + + check-no-fork + + + ${project.build.directory}/clirr-all.txt + false + false + + + + restrictive + verify + + check-no-fork + + + ${project.build.directory}/clirr-restrictive.txt + true + ../.clirr-jenkins-ignore.xml + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelConvertException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelConvertException.java new file mode 100644 index 0000000000000000000000000000000000000000..2d14911ab3a438cab4f91d60f9eb707f5ca5b955 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelConvertException.java @@ -0,0 +1,55 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.bpm.dmn.feel.impl.FeelException; + +/** + * Exception thrown if a invalid type conversion occurs in a FEEL expression. + */ +public class FeelConvertException extends FeelException { + + protected Object value; + protected Class type; + + public FeelConvertException(String message, Object value, Class type) { + super(message); + this.value = value; + this.type = type; + } + + public FeelConvertException(String message, Object value, Class type, Throwable cause) { + super(message, cause); + this.value = value; + this.type = type; + } + + public FeelConvertException(String message, FeelConvertException convertException) { + super(message, convertException.getCause()); + this.value = convertException.getValue(); + this.type = convertException.getType(); + } + + public Object getValue() { + return value; + } + + public Class getType() { + return type; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineFactoryImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineFactoryImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..d187e4b940a08a9ab127f9e541308c2d62c2812f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineFactoryImpl.java @@ -0,0 +1,121 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import org.camunda.bpm.impl.juel.jakarta.el.ELException; +import org.camunda.bpm.impl.juel.jakarta.el.ExpressionFactory; + +import org.camunda.bpm.dmn.feel.impl.FeelEngine; +import org.camunda.bpm.dmn.feel.impl.FeelEngineFactory; +import org.camunda.bpm.dmn.feel.impl.juel.el.ElContextFactory; +import org.camunda.bpm.dmn.feel.impl.juel.el.FeelElContextFactory; +import org.camunda.bpm.dmn.feel.impl.juel.el.FeelTypeConverter; +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelFunctionTransformer; +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransform; +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransformImpl; +import org.camunda.commons.utils.cache.Cache; +import org.camunda.commons.utils.cache.ConcurrentLruCache; + +import org.camunda.bpm.impl.juel.ExpressionFactoryImpl; + +public class FeelEngineFactoryImpl implements FeelEngineFactory { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + public static final int DEFAULT_EXPRESSION_CACHE_SIZE = 1000; + + protected final FeelEngine feelEngine; + + protected final int expressionCacheSize; + protected final List customFunctionTransformers; + + public FeelEngineFactoryImpl() { + this(DEFAULT_EXPRESSION_CACHE_SIZE); + } + + public FeelEngineFactoryImpl(int expressionCacheSize) { + this(expressionCacheSize, Collections. emptyList()); + } + + public FeelEngineFactoryImpl(List customFunctionTransformers) { + this(DEFAULT_EXPRESSION_CACHE_SIZE, customFunctionTransformers); + } + + public FeelEngineFactoryImpl(int expressionCacheSize, List customFunctionTransformers) { + this.expressionCacheSize = expressionCacheSize; + this.customFunctionTransformers = customFunctionTransformers; + + feelEngine = createFeelEngine(); + } + + public FeelEngine createInstance() { + return feelEngine; + } + + protected FeelEngine createFeelEngine() { + FeelToJuelTransform transform = createFeelToJuelTransform(); + ExpressionFactory expressionFactory = createExpressionFactory(); + ElContextFactory elContextFactory = createElContextFactory(); + Cache transformExpressionCache = createTransformExpressionCache(); + return new FeelEngineImpl(transform, expressionFactory, elContextFactory, transformExpressionCache); + } + + protected FeelToJuelTransform createFeelToJuelTransform() { + FeelToJuelTransformImpl transformer = new FeelToJuelTransformImpl(); + + for (FeelToJuelFunctionTransformer functionTransformer : customFunctionTransformers) { + transformer.addCustomFunctionTransformer(functionTransformer); + } + + return transformer; + } + + protected ExpressionFactory createExpressionFactory() { + Properties properties = new Properties(); + properties.put(ExpressionFactoryImpl.PROP_CACHE_SIZE, String.valueOf(expressionCacheSize)); + + try { + return new ExpressionFactoryImpl(properties, createTypeConverter()); + } + catch (ELException e) { + throw LOG.unableToInitializeFeelEngine(e); + } + } + + protected FeelTypeConverter createTypeConverter() { + return new FeelTypeConverter(); + } + + protected ElContextFactory createElContextFactory() { + FeelElContextFactory factory = new FeelElContextFactory(); + + for (FeelToJuelFunctionTransformer functionTransformer : customFunctionTransformers) { + factory.addCustomFunction(functionTransformer.getName(), functionTransformer.getMethod()); + } + + return factory; + } + + protected Cache createTransformExpressionCache() { + return new ConcurrentLruCache(expressionCacheSize); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..51831f3f777b8b9ad78b8682a281fba283c122d1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineImpl.java @@ -0,0 +1,109 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.bpm.impl.juel.jakarta.el.ELContext; +import org.camunda.bpm.impl.juel.jakarta.el.ELException; +import org.camunda.bpm.impl.juel.jakarta.el.ExpressionFactory; +import org.camunda.bpm.impl.juel.jakarta.el.ValueExpression; + +import org.camunda.bpm.dmn.feel.impl.FeelEngine; +import org.camunda.bpm.dmn.feel.impl.juel.el.ElContextFactory; +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransform; +import org.camunda.bpm.engine.variable.context.VariableContext; +import org.camunda.commons.utils.cache.Cache; + +public class FeelEngineImpl implements FeelEngine { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + protected FeelToJuelTransform transform; + protected ExpressionFactory expressionFactory; + protected ElContextFactory elContextFactory; + protected Cache transformExpressionCache; + + public FeelEngineImpl(FeelToJuelTransform transform, ExpressionFactory expressionFactory, ElContextFactory elContextFactory, + Cache transformExpressionCache) { + this.transform = transform; + this.expressionFactory = expressionFactory; + this.elContextFactory = elContextFactory; + this.transformExpressionCache = transformExpressionCache; + } + + public T evaluateSimpleExpression(String simpleExpression, VariableContext variableContext) { + throw LOG.simpleExpressionNotSupported(); + } + + public boolean evaluateSimpleUnaryTests(String simpleUnaryTests, String inputName, VariableContext variableContext) { + try { + ELContext elContext = createContext(variableContext); + ValueExpression valueExpression = transformSimpleUnaryTests(simpleUnaryTests, inputName, elContext); + return (Boolean) valueExpression.getValue(elContext); + } + catch (FeelMissingFunctionException e) { + throw LOG.unknownFunction(simpleUnaryTests, e); + } + catch (FeelMissingVariableException e) { + if (inputName.equals(e.getVariable())) { + throw LOG.unableToEvaluateExpressionAsNotInputIsSet(simpleUnaryTests, e); + } + else { + throw LOG.unknownVariable(simpleUnaryTests, e); + } + } + catch (FeelConvertException e) { + throw LOG.unableToConvertValue(simpleUnaryTests, e); + } + catch (ELException e) { + if (e.getCause() instanceof FeelMethodInvocationException) { + throw LOG.unableToInvokeMethod(simpleUnaryTests, (FeelMethodInvocationException) e.getCause()); + } + else { + throw LOG.unableToEvaluateExpression(simpleUnaryTests, e); + } + } + } + + protected ELContext createContext(VariableContext variableContext) { + return elContextFactory.createContext(expressionFactory, variableContext); + } + + protected ValueExpression transformSimpleUnaryTests(String simpleUnaryTests, String inputName, ELContext elContext) { + + String juelExpression = transformToJuelExpression(simpleUnaryTests, inputName); + + try { + return expressionFactory.createValueExpression(elContext, juelExpression, Object.class); + } + catch (ELException e) { + throw LOG.invalidExpression(simpleUnaryTests, e); + } + } + + protected String transformToJuelExpression(String simpleUnaryTests, String inputName) { + + TransformExpressionCacheKey cacheKey = new TransformExpressionCacheKey(simpleUnaryTests, inputName); + String juelExpression = transformExpressionCache.get(cacheKey); + + if (juelExpression == null) { + juelExpression = transform.transformSimpleUnaryTests(simpleUnaryTests, inputName); + transformExpressionCache.put(cacheKey, juelExpression); + } + return juelExpression; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineLogger.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineLogger.java new file mode 100644 index 0000000000000000000000000000000000000000..7900fddd1b96ef78514084afea50eebc89a62459 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelEngineLogger.java @@ -0,0 +1,197 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.bpm.dmn.feel.impl.FeelException; + +public class FeelEngineLogger extends FeelLogger { + + protected FeelSyntaxException syntaxException(String id, String feelExpression, String description) { + return new FeelSyntaxException(syntaxExceptionMessage(id, feelExpression, description), feelExpression, description); + } + + protected FeelSyntaxException syntaxException(String id, String feelExpression, String description, Throwable cause) { + return new FeelSyntaxException(syntaxExceptionMessage(id, feelExpression, description), feelExpression, description, cause); + } + + protected String syntaxExceptionMessage(String id, String feelExpression, String description) { + if (description != null) { + return exceptionMessage( + id, + "Syntax error in expression '{}': {}", feelExpression, description + ); + } + else { + return exceptionMessage( + id, "Syntax error in expression '{}'", feelExpression + ); + } + } + + public FeelSyntaxException invalidNotExpression(String feelExpression) { + String description = "Expression should have format 'not(...)'"; + return syntaxException("001", feelExpression, description); + } + + public FeelSyntaxException invalidIntervalExpression(String feelExpression) { + String description = "Expression should have format '[|(|] endpoint .. endpoint ]|)|['"; + return syntaxException("002", feelExpression, description); + } + + public FeelSyntaxException invalidComparisonExpression(String feelExpression) { + String description = "Expression should have format '<=|<|>=|> endpoint'"; + return syntaxException("003", feelExpression, description); + } + + public FeelException variableMapperIsReadOnly() { + return new FeelException(exceptionMessage( + "004", + "The variable mapper is read only.") + ); + } + + public FeelException unableToFindMethod(NoSuchMethodException cause, String name, Class... parameterTypes) { + return new FeelException(exceptionMessage( + "005", + "Unable to find method '{}' with parameter types '{}'", name, parameterTypes), + cause + ); + } + + public FeelMissingFunctionException unknownFunction(String prefix, String localName) { + String function = localName; + if (prefix != null && !prefix.isEmpty()) { + function = prefix + ":" + localName; + } + return new FeelMissingFunctionException(exceptionMessage( + "006", + "Unable to resolve function '{}'", function), + function + ); + } + + public FeelMissingFunctionException unknownFunction(String feelExpression, FeelMissingFunctionException cause) { + String function = cause.getFunction(); + return new FeelMissingFunctionException(exceptionMessage( + "007", + "Unable to resolve function '{}' in expression '{}'" , function, feelExpression), + function + ); + } + + public FeelMissingVariableException unknownVariable(String variable) { + return new FeelMissingVariableException(exceptionMessage( + "008", + "Unable to resolve variable '{}'", variable), + variable + ); + } + + public FeelMissingVariableException unknownVariable(String feelExpression, FeelMissingVariableException cause) { + String variable = cause.getVariable(); + return new FeelMissingVariableException(exceptionMessage( + "009", + "Unable to resolve variable '{}' in expression '{}'", variable, feelExpression), + variable + ); + } + + public FeelSyntaxException invalidExpression(String feelExpression, Throwable cause) { + return syntaxException("010", feelExpression, null, cause); + } + + public FeelException unableToInitializeFeelEngine(Throwable cause) { + return new FeelException(exceptionMessage( + "011", + "Unable to initialize FEEL engine"), + cause + ); + } + + public FeelException unableToEvaluateExpression(String simpleUnaryTests, Throwable cause) { + return new FeelException(exceptionMessage( + "012", + "Unable to evaluate expression '{}'", simpleUnaryTests), + cause + ); + } + + public FeelConvertException unableToConvertValue(Object value, Class type) { + return new FeelConvertException(exceptionMessage( + "013", + "Unable to convert value '{}' of type '{}' to type '{}'", value, value.getClass(), type), + value, type + ); + } + + public FeelConvertException unableToConvertValue(Object value, Class type, Throwable cause) { + return new FeelConvertException(exceptionMessage( + "014", + "Unable to convert value '{}' of type '{}' to type '{}'", value, value.getClass(), type), + value, type, cause + ); + } + + public FeelConvertException unableToConvertValue(String feelExpression, FeelConvertException cause) { + Object value = cause.getValue(); + Class type = cause.getType(); + return new FeelConvertException(exceptionMessage( + "015", + "Unable to convert value '{}' of type '{}' to type '{}' in expression '{}'", value, value.getClass(), type, feelExpression), + cause + ); + } + + public UnsupportedOperationException simpleExpressionNotSupported() { + return new UnsupportedOperationException(exceptionMessage( + "016", + "Simple Expression not supported by FEEL engine") + ); + } + + public FeelException unableToEvaluateExpressionAsNotInputIsSet(String simpleUnaryTests, FeelMissingVariableException e) { + return new FeelException(exceptionMessage( + "017", + "Unable to evaluate expression '{}' as no input is set. Maybe the inputExpression is missing or empty.", simpleUnaryTests), + e + ); + } + + public FeelMethodInvocationException invalidDateAndTimeFormat(String dateTimeString, Throwable cause) { + return new FeelMethodInvocationException(exceptionMessage( + "018", + "Invalid date and time format in '{}'", dateTimeString), + cause, "date and time", dateTimeString + ); + } + + public FeelMethodInvocationException unableToInvokeMethod(String simpleUnaryTests, FeelMethodInvocationException cause) { + String method = cause.getMethod(); + String[] parameters = cause.getParameters(); + return new FeelMethodInvocationException(exceptionMessage( + "019", + "Unable to invoke method '{}' with parameters '{}' in expression '{}'", method, parameters, simpleUnaryTests), + cause.getCause(), method, parameters + ); + } + + public FeelSyntaxException invalidListExpression(String feelExpression) { + String description = "List expression can not have empty elements"; + return syntaxException("020", feelExpression, description); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelLogger.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelLogger.java new file mode 100644 index 0000000000000000000000000000000000000000..cba8b957242fb326c0c068680b152db952c2831b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelLogger.java @@ -0,0 +1,28 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.commons.logging.BaseLogger; + +public class FeelLogger extends BaseLogger { + + public static final String PROJECT_CODE = "FEEL"; + public static final String PROJECT_LOGGER= "org.camunda.bpm.dmn.feel"; + + public static FeelEngineLogger ENGINE_LOGGER = createLogger(FeelEngineLogger.class, PROJECT_CODE, PROJECT_LOGGER, "01"); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMethodInvocationException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMethodInvocationException.java new file mode 100644 index 0000000000000000000000000000000000000000..8ec546f2c76ca343908ad307d9846f821226db8e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMethodInvocationException.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.bpm.dmn.feel.impl.FeelException; + +/** + * Exception thrown if an error occurs during a method invocation + * in a FEEL expression. + */ +public class FeelMethodInvocationException extends FeelException { + + protected String method; + protected String[] parameters; + + public FeelMethodInvocationException(String message, String method, String... parameters) { + super(message); + this.method = method; + this.parameters = parameters; + } + + public FeelMethodInvocationException(String message, Throwable cause, String method, String... parameters) { + super(message, cause); + this.method = method; + this.parameters = parameters; + } + + public String getMethod() { + return method; + } + + public String[] getParameters() { + return parameters; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMissingFunctionException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMissingFunctionException.java new file mode 100644 index 0000000000000000000000000000000000000000..a70c7c8892839a68280aec5c6961ddf9afc786b8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMissingFunctionException.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.bpm.dmn.feel.impl.FeelException; + +/** + * Exception thrown if a method used in a FEEL expression is not available. + */ +public class FeelMissingFunctionException extends FeelException { + + protected String function; + + public FeelMissingFunctionException(String message, String function) { + super(message); + this.function = function; + } + + public FeelMissingFunctionException(String message, Throwable cause, String function) { + super(message, cause); + this.function = function; + } + + public String getFunction() { + return function; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMissingVariableException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMissingVariableException.java new file mode 100644 index 0000000000000000000000000000000000000000..0ff0830b1489baa54d1cffbea8328d890a68ebce --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelMissingVariableException.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.bpm.dmn.feel.impl.FeelException; + +/** + * Exception thrown if a variable used in a FEEL expression is not available. + */ +public class FeelMissingVariableException extends FeelException { + + private final String variable; + + public FeelMissingVariableException(String message, String variable) { + super(message); + this.variable = variable; + } + + public FeelMissingVariableException(String message, Throwable cause, String variable) { + super(message, cause); + this.variable = variable; + } + + public String getVariable() { + return variable; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelSyntaxException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelSyntaxException.java new file mode 100644 index 0000000000000000000000000000000000000000..3d30c48649877e2b72a185c649abdd12137cbfed --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/FeelSyntaxException.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +import org.camunda.bpm.dmn.feel.impl.FeelException; + +/** + * Exception thrown if the syntax of a FEEL expression is invalid. + */ +public class FeelSyntaxException extends FeelException { + + protected String feelExpression; + protected String description; + + public FeelSyntaxException(String message, String feelExpression, String description) { + super(message); + this.feelExpression = feelExpression; + this.description = description; + } + + public FeelSyntaxException(String message, String feelExpression, String description, Throwable cause) { + super(message, cause); + this.feelExpression = feelExpression; + this.description = description; + } + + public String getFeelExpression() { + return feelExpression; + } + + public String getDescription() { + return description; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/TransformExpressionCacheKey.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/TransformExpressionCacheKey.java new file mode 100644 index 0000000000000000000000000000000000000000..fdce8fa1eff29cb515cdf7c699d0b7315788d55a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/TransformExpressionCacheKey.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel; + +public class TransformExpressionCacheKey { + + protected final String expression; + protected final String inputName; + + public TransformExpressionCacheKey(String expression, String inputName) { + this.expression = expression; + this.inputName = inputName; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((expression == null) ? 0 : expression.hashCode()); + result = prime * result + ((inputName == null) ? 0 : inputName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + TransformExpressionCacheKey other = (TransformExpressionCacheKey) obj; + if (expression == null) { + if (other.expression != null) + return false; + } else if (!expression.equals(other.expression)) + return false; + if (inputName == null) { + if (other.inputName != null) + return false; + } else if (!inputName.equals(other.inputName)) + return false; + return true; + } + + @Override + public String toString() { + return "TransformExpressionCacheKey [expression=" + expression + ", inputName=" + inputName + "]"; + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/CompositeFunctionMapper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/CompositeFunctionMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..282dea1d932ca0ff1f5b85eefcb4d4291ae2dd5f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/CompositeFunctionMapper.java @@ -0,0 +1,55 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.camunda.bpm.impl.juel.jakarta.el.FunctionMapper; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class CompositeFunctionMapper extends FunctionMapper { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + protected List functionMappers = new ArrayList(); + + public Method resolveFunction(String prefix, String localName) { + for (FunctionMapper functionMapper : functionMappers) { + Method method = functionMapper.resolveFunction(prefix, localName); + if (method != null) { + return method; + } + } + throw LOG.unknownFunction(prefix, localName); + } + + public void setFunctionMappers(List functionMappers) { + this.functionMappers = functionMappers; + } + + public void add(FunctionMapper functionMapper) { + functionMappers.add(functionMapper); + } + + public void remove(FunctionMapper functionMapper) { + functionMappers.remove(functionMapper); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/CustomFunctionMapper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/CustomFunctionMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..2bd149ccddd2be14e61881a58375524d8e4ad690 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/CustomFunctionMapper.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.impl.juel.jakarta.el.FunctionMapper; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class CustomFunctionMapper extends FunctionMapper { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + protected final Map methods = new HashMap(); + + @Override + public Method resolveFunction(String prefix, String localName) { + return methods.get(localName); + } + + public void addMethod(final String name, final Method method) { + methods.put(name, method); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/ElContextFactory.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/ElContextFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..6f51a5f675b5e2ce76fc15c037aeac1105b65442 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/ElContextFactory.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import java.lang.reflect.Method; + +import org.camunda.bpm.impl.juel.jakarta.el.ELContext; +import org.camunda.bpm.impl.juel.jakarta.el.ExpressionFactory; + +import org.camunda.bpm.engine.variable.context.VariableContext; + +public interface ElContextFactory { + + /** + * Create a {@link ELContext} for the given {@link ExpressionFactory} and {@link VariableContext}. + * + * @param expressionFactory the {@link ExpressionFactory} to use + * @param variableContext the {@link VariableContext} to use + * @return the {@link ELContext} instance + */ + ELContext createContext(ExpressionFactory expressionFactory, VariableContext variableContext); + + /** + * Add a custom function which can be used by the context. + * + * @param name the name of the function + * @param method the method reference of the function + */ + void addCustomFunction(String name, Method method); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelElContext.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelElContext.java new file mode 100644 index 0000000000000000000000000000000000000000..3f11099162027972330cc7a5196c9646e342fd84 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelElContext.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import org.camunda.bpm.impl.juel.jakarta.el.ELContext; +import org.camunda.bpm.impl.juel.jakarta.el.ELResolver; +import org.camunda.bpm.impl.juel.jakarta.el.FunctionMapper; +import org.camunda.bpm.impl.juel.jakarta.el.VariableMapper; + +public class FeelElContext extends ELContext { + + protected ELResolver elResolver; + protected FunctionMapper functionMapper; + protected VariableMapper variableMapper; + + public FeelElContext(ELResolver elResolver, FunctionMapper functionMapper, VariableMapper variableMapper) { + this.elResolver = elResolver; + this.functionMapper = functionMapper; + this.variableMapper = variableMapper; + } + + public ELResolver getELResolver() { + return elResolver; + } + + public FunctionMapper getFunctionMapper() { + return functionMapper; + } + + public VariableMapper getVariableMapper() { + return variableMapper; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelElContextFactory.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelElContextFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..8f1f0cb19854f496d0e334a3c9ebd9885a60f734 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelElContextFactory.java @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import java.lang.reflect.Method; + +import org.camunda.bpm.impl.juel.jakarta.el.ELContext; +import org.camunda.bpm.impl.juel.jakarta.el.ELResolver; +import org.camunda.bpm.impl.juel.jakarta.el.ExpressionFactory; +import org.camunda.bpm.impl.juel.jakarta.el.FunctionMapper; +import org.camunda.bpm.impl.juel.jakarta.el.VariableMapper; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; +import org.camunda.bpm.engine.variable.context.VariableContext; + +import org.camunda.bpm.impl.juel.SimpleResolver; + +public class FeelElContextFactory implements ElContextFactory { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + protected CustomFunctionMapper customFunctionMapper = new CustomFunctionMapper(); + + public ELContext createContext(ExpressionFactory expressionFactory, VariableContext variableContext) { + ELResolver elResolver = createElResolver(); + FunctionMapper functionMapper = createFunctionMapper(); + VariableMapper variableMapper = createVariableMapper(expressionFactory, variableContext); + + return new FeelElContext(elResolver, functionMapper, variableMapper); + } + + public ELResolver createElResolver() { + return new SimpleResolver(true); + } + + public FunctionMapper createFunctionMapper() { + CompositeFunctionMapper functionMapper = new CompositeFunctionMapper(); + functionMapper.add(new FeelFunctionMapper()); + functionMapper.add(customFunctionMapper); + return functionMapper; + } + + public VariableMapper createVariableMapper(ExpressionFactory expressionFactory, VariableContext variableContext) { + return new FeelTypedVariableMapper(expressionFactory, variableContext); + } + + public void addCustomFunction(String name, Method method) { + customFunctionMapper.addMethod(name, method); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelFunctionMapper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelFunctionMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..0c87bbd389e8a8f596251494227313762a1c9a7b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelFunctionMapper.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import java.lang.reflect.Method; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import org.camunda.bpm.impl.juel.jakarta.el.FunctionMapper; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class FeelFunctionMapper extends FunctionMapper { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + protected static final SimpleDateFormat FEEL_DATE_AND_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + public static final String JUEL_DATE_AND_TIME_METHOD = "dateAndTime"; + + protected static final Map methods = new HashMap(); + + static { + methods.put(JUEL_DATE_AND_TIME_METHOD, getMethod("parseDateAndTime", String.class)); + } + + public Method resolveFunction(String prefix, String localName) { + return methods.get(localName); + } + + protected static Method getMethod(String name, Class... parameterTypes) { + try { + return FeelFunctionMapper.class.getMethod(name, parameterTypes); + } catch (NoSuchMethodException e) { + throw LOG.unableToFindMethod(e, name, parameterTypes); + } + } + + public static Date parseDateAndTime(String dateAndTimeString) { + try { + SimpleDateFormat clonedDateFormat = (SimpleDateFormat) FEEL_DATE_AND_TIME_FORMAT.clone(); + return clonedDateFormat.parse(dateAndTimeString); + } catch (ParseException e) { + throw LOG.invalidDateAndTimeFormat(dateAndTimeString, e); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelTypeConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelTypeConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..86826c5a49c8db9470f2c78fb61bc87c533dacca --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelTypeConverter.java @@ -0,0 +1,128 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import java.math.BigDecimal; +import java.math.BigInteger; +import org.camunda.bpm.impl.juel.jakarta.el.ELException; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +import org.camunda.bpm.impl.juel.TypeConverterImpl; + +public class FeelTypeConverter extends TypeConverterImpl { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + @Override + protected Boolean coerceToBoolean(Object value) { + if (value instanceof Boolean) { + return (Boolean) value; + } + else { + throw LOG.unableToConvertValue(value, Boolean.class); + } + } + + @Override + protected BigDecimal coerceToBigDecimal(Object value) { + if (value instanceof BigDecimal) { + return (BigDecimal)value; + } + else if (value instanceof BigInteger) { + return new BigDecimal((BigInteger)value); + } + else if (value instanceof Number) { + return new BigDecimal(((Number)value).doubleValue()); + } + else { + throw LOG.unableToConvertValue(value, BigDecimal.class); + } + } + + @Override + protected BigInteger coerceToBigInteger(Object value) { + if (value instanceof BigInteger) { + return (BigInteger)value; + } + else if (value instanceof BigDecimal) { + return ((BigDecimal)value).toBigInteger(); + } + else if (value instanceof Number) { + return BigInteger.valueOf(((Number)value).longValue()); + } + else { + throw LOG.unableToConvertValue(value, BigInteger.class); + } + } + + @Override + protected Double coerceToDouble(Object value) { + if (value instanceof Double) { + return (Double)value; + } + else if (value instanceof Number) { + return ((Number) value).doubleValue(); + } + else { + throw LOG.unableToConvertValue(value, Double.class); + } + } + + @Override + protected Long coerceToLong(Object value) { + if (value instanceof Long) { + return (Long)value; + } + else if (value instanceof Number && isLong((Number) value)) { + return ((Number) value).longValue(); + } + else { + throw LOG.unableToConvertValue(value, Long.class); + } + } + + @Override + protected String coerceToString(Object value) { + if (value instanceof String) { + return (String)value; + } + else if (value instanceof Enum) { + return ((Enum)value).name(); + } + else { + throw LOG.unableToConvertValue(value, String.class); + } + } + + @Override + public T convert(Object value, Class type) throws ELException { + try { + return super.convert(value, type); + } + catch (ELException e) { + throw LOG.unableToConvertValue(value, type, e); + } + } + + protected boolean isLong(Number value) { + double doubleValue = value.doubleValue(); + return doubleValue == (long) doubleValue; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelTypedVariableMapper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelTypedVariableMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..0fa105d1e74ea1d35cef5f3af48c867b109cecc7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/el/FeelTypedVariableMapper.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.el; + +import org.camunda.bpm.impl.juel.jakarta.el.ExpressionFactory; +import org.camunda.bpm.impl.juel.jakarta.el.ValueExpression; +import org.camunda.bpm.impl.juel.jakarta.el.VariableMapper; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; +import org.camunda.bpm.engine.variable.context.VariableContext; +import org.camunda.bpm.engine.variable.value.TypedValue; + +public class FeelTypedVariableMapper extends VariableMapper { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + protected ExpressionFactory expressionFactory; + protected VariableContext variableContext; + + public FeelTypedVariableMapper(ExpressionFactory expressionFactory, VariableContext variableContext) { + this.expressionFactory = expressionFactory; + this.variableContext = variableContext; + } + + public ValueExpression resolveVariable(String variable) { + if (variableContext.containsVariable(variable)) { + Object value = unpackVariable(variable); + return expressionFactory.createValueExpression(value, Object.class); + } + else { + throw LOG.unknownVariable(variable); + } + } + + public ValueExpression setVariable(String variable, ValueExpression expression) { + throw LOG.variableMapperIsReadOnly(); + } + + public Object unpackVariable(String variable) { + TypedValue valueTyped = variableContext.resolve(variable); + if(valueTyped != null) { + return valueTyped.getValue(); + } + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/ComparisonTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/ComparisonTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..75d1cb46e1ac3d0fa0164afbe66e63e83e79733c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/ComparisonTransformer.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class ComparisonTransformer implements FeelToJuelTransformer { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + public static final Pattern COMPARISON_PATTERN = Pattern.compile("^(<=|>=|<|>)([^=].*)$"); + + public boolean canTransform(String feelExpression) { + return feelExpression.startsWith("<=") || feelExpression.startsWith("<") || feelExpression.startsWith(">=") || feelExpression.startsWith(">"); + } + + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + Matcher matcher = COMPARISON_PATTERN.matcher(feelExpression); + if (matcher.matches()) { + return transformComparison(transform, matcher.group(1), matcher.group(2), inputName); + } + else { + throw LOG.invalidComparisonExpression(feelExpression); + } + } + + protected String transformComparison(FeelToJuelTransform transform, String operator, String endpoint, String inputName) { + String juelEndpoint = transform.transformEndpoint(endpoint, inputName); + return String.format("%s %s %s", inputName, operator, juelEndpoint); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/EndpointTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/EndpointTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..1c44e27d551c512e43c9b4db3f16ab56d84d06d8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/EndpointTransformer.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +import static org.camunda.bpm.dmn.feel.impl.juel.el.FeelFunctionMapper.JUEL_DATE_AND_TIME_METHOD; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class EndpointTransformer implements FeelToJuelTransformer { + + public static final Pattern DATE_AND_TIME_PATTERN = Pattern.compile("^date and time\\((.+)\\)$"); + + public boolean canTransform(String feelExpression) { + return true; + } + + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + Matcher matcher = DATE_AND_TIME_PATTERN.matcher(feelExpression); + if (matcher.matches()) { + return JUEL_DATE_AND_TIME_METHOD + "(" + matcher.group(1) + ")"; + } + else { + return feelExpression; + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/EqualTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/EqualTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..1edf86427383f27cc291c4e0ea47033c47384565 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/EqualTransformer.java @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +public class EqualTransformer implements FeelToJuelTransformer { + + public boolean canTransform(String feelExpression) { + return true; + } + + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + String juelEndpoint = transform.transformEndpoint(feelExpression, inputName); + return String.format("%s == %s", inputName, juelEndpoint); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelFunctionTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelFunctionTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..f40b124310994b625be690b8ca4b4cbba5fdc9ac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelFunctionTransformer.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +import java.lang.reflect.Method; + +public interface FeelToJuelFunctionTransformer extends FeelToJuelTransformer { + + /** + * Get the name of the function. + * + * @return the name of function + */ + String getName(); + + /** + * Get the method reference which implements the function to transform to. + * Note: The implementation should resolve the method reference only once at creation + * and not within every call of these method. + * + * @return the method reference + */ + Method getMethod(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransform.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransform.java new file mode 100644 index 0000000000000000000000000000000000000000..7a490ea53c02020d09a128cf647337ba37179ff7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransform.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +public interface FeelToJuelTransform { + + /** + * Transform a FEEL simple unary tests expression to a JUEL expression. + * + * @param simpleUnaryTests the FEEL simple unary tests expression to transform + * @param inputName the variable name of the input variable to test against + * @return the resulting JUEL expression + */ + String transformSimpleUnaryTests(String simpleUnaryTests, String inputName); + + /** + * Transform a FEEL simple positive unary tests expression to a JUEL expression. + * + * @param simplePositiveUnaryTests the FEEL simple positive unary tests expression to transform + * @param inputName the variable name of the input variable to test against + * @return the resulting JUEL expression + */ + String transformSimplePositiveUnaryTests(String simplePositiveUnaryTests, String inputName); + + /** + * Transform a FEEL simple positive unary test expression to a JUEL expression. + * + * @param simplePositiveUnaryTest the FEEL simple positive unary test expression to transform + * @param inputName the variable name of the input variable to test against + * @return the resulting JUEL expression + */ + String transformSimplePositiveUnaryTest(String simplePositiveUnaryTest, String inputName); + + /** + * Transform a FEEL endpoint expression to a JUEL expression. + * + * @param endpoint the FEEL endpoint expression to transform + * @param inputName the variable name of the input variable to test against + * @return the resulting JUEL expression + */ + String transformEndpoint(String endpoint, String inputName); + + /** + * Add a transformer for a custom function. + * + * @param functionTransformer the transformer for the custom function + */ + void addCustomFunctionTransformer(FeelToJuelTransformer functionTransformer); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransformImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransformImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..32c3a00bfb9b3e29b7a14b81ba5caa733956b9b2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransformImpl.java @@ -0,0 +1,92 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class FeelToJuelTransformImpl implements FeelToJuelTransform { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + + public static final FeelToJuelTransformer NOT_TRANSFORMER = new NotTransformer(); + public static final FeelToJuelTransformer HYPHEN_TRANSFORMER = new HyphenTransformer(); + public static final FeelToJuelTransformer LIST_TRANSFORMER = new ListTransformer(); + public static final FeelToJuelTransformer INTERVAL_TRANSFORMER = new IntervalTransformer(); + public static final FeelToJuelTransformer COMPARISON_TRANSFORMER = new ComparisonTransformer(); + public static final FeelToJuelTransformer EQUAL_TRANSFORMER = new EqualTransformer(); + public static final FeelToJuelTransformer ENDPOINT_TRANSFORMER = new EndpointTransformer(); + public static final List CUSTOM_FUNCTION_TRANSFORMERS = new ArrayList(); + + public String transformSimpleUnaryTests(String simpleUnaryTests, String inputName) { + simpleUnaryTests = simpleUnaryTests.trim(); + String juelExpression; + if (HYPHEN_TRANSFORMER.canTransform(simpleUnaryTests)) { + juelExpression = HYPHEN_TRANSFORMER.transform(this, simpleUnaryTests, inputName); + } + else if (NOT_TRANSFORMER.canTransform(simpleUnaryTests)) { + juelExpression = NOT_TRANSFORMER.transform(this, simpleUnaryTests, inputName); + } + else { + juelExpression = transformSimplePositiveUnaryTests(simpleUnaryTests, inputName); + } + + return "${" + juelExpression + "}"; + } + + public String transformSimplePositiveUnaryTests(String simplePositiveUnaryTests, String inputName) { + simplePositiveUnaryTests = simplePositiveUnaryTests.trim(); + if (LIST_TRANSFORMER.canTransform(simplePositiveUnaryTests)) { + return LIST_TRANSFORMER.transform(this, simplePositiveUnaryTests, inputName); + } + else { + return transformSimplePositiveUnaryTest(simplePositiveUnaryTests, inputName); + } + } + + public String transformSimplePositiveUnaryTest(String simplePositiveUnaryTest, String inputName) { + simplePositiveUnaryTest = simplePositiveUnaryTest.trim(); + + for (FeelToJuelTransformer functionTransformer : CUSTOM_FUNCTION_TRANSFORMERS) { + if (functionTransformer.canTransform(simplePositiveUnaryTest)) { + return functionTransformer.transform(this, simplePositiveUnaryTest, inputName); + } + } + + if (INTERVAL_TRANSFORMER.canTransform(simplePositiveUnaryTest)) { + return INTERVAL_TRANSFORMER.transform(this, simplePositiveUnaryTest, inputName); + } + else if (COMPARISON_TRANSFORMER.canTransform(simplePositiveUnaryTest)) { + return COMPARISON_TRANSFORMER.transform(this, simplePositiveUnaryTest, inputName); + } + else { + return EQUAL_TRANSFORMER.transform(this, simplePositiveUnaryTest, inputName); + } + } + + public String transformEndpoint(String endpoint, String inputName) { + endpoint = endpoint.trim(); + return ENDPOINT_TRANSFORMER.transform(this, endpoint, inputName); + } + + public void addCustomFunctionTransformer(FeelToJuelTransformer functionTransformer) { + CUSTOM_FUNCTION_TRANSFORMERS.add(functionTransformer); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..6161781f5d540f904b3ad16b5b817a745edc9098 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/FeelToJuelTransformer.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +public interface FeelToJuelTransformer { + + /** + * Test if an expression can be transformed by this transformer. + * + * @param feelExpression the FEEL expression to transform + * @return true if the expression can be transformed by this transformer, false otherwise + */ + boolean canTransform(String feelExpression); + + /** + * Transform the FEEL expression to a JUEL expression. + * + * @param transform the {@link FeelToJuelTransform} to use for further transforms + * @param feelExpression the FEEL expression to transform + * @param inputName the variable name of the input variable to test against + * @return the resulting JUEL expression + */ + String transform(FeelToJuelTransform transform, String feelExpression, String inputName); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/HyphenTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/HyphenTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..39e8cd1c52a79107e6a86c332edb9b91bf8c7e16 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/HyphenTransformer.java @@ -0,0 +1,29 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +public class HyphenTransformer implements FeelToJuelTransformer { + + public boolean canTransform(String feelExpression) { + return feelExpression.equals("-"); + } + + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + return "true"; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/IntervalTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/IntervalTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..8534ff697c49981ee8a3119cec7048e922a610aa --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/IntervalTransformer.java @@ -0,0 +1,71 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class IntervalTransformer implements FeelToJuelTransformer { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + public static final Pattern INTERVAL_PATTERN = Pattern.compile("^(\\(|\\[|\\])(.*[^\\.])\\.\\.(.+)(\\)|\\]|\\[)$"); + + public boolean canTransform(String feelExpression) { + return feelExpression.startsWith("(") || feelExpression.startsWith("[") || feelExpression.startsWith("]"); + } + + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + Matcher matcher = INTERVAL_PATTERN.matcher(feelExpression); + if (matcher.matches()) { + return transformInterval(transform, matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), inputName); + } + else { + throw LOG.invalidIntervalExpression(feelExpression); + } + } + + public String transformInterval(FeelToJuelTransform transform, String startIntervalSymbol, String lowerEndpoint, String upperEndpoint, String stopIntervalSymbol, String inputName) { + String juelLowerEndpoint = transform.transformEndpoint(lowerEndpoint, inputName); + String juelUpperEndpoint = transform.transformEndpoint(upperEndpoint, inputName); + String lowerEndpointComparator = transformLowerEndpointComparator(startIntervalSymbol); + String upperEndpointComparator = transformUpperEndpointComparator(stopIntervalSymbol); + + return String.format("%s %s %s && %s %s %s", inputName, lowerEndpointComparator, juelLowerEndpoint, inputName, upperEndpointComparator, juelUpperEndpoint); + } + + protected String transformLowerEndpointComparator(String startIntervalSymbol) { + if (startIntervalSymbol.equals("[")) { + return ">="; + } + else { + return ">"; + } + } + + protected String transformUpperEndpointComparator(String stopIntervalSymbol) { + if (stopIntervalSymbol.equals("]")) { + return "<="; + } + else { + return "<"; + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/ListTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/ListTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..3d24c825e64c30e94af6695a0c7e864cb9c1c728 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/ListTransformer.java @@ -0,0 +1,73 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class ListTransformer implements FeelToJuelTransformer { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + // regex to split by comma which does a positive look ahead to ignore commas enclosed in quotes + public static final String COMMA_SEPARATOR_REGEX = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"; + + public boolean canTransform(String feelExpression) { + return splitExpression(feelExpression).size() > 1; + } + + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + List juelExpressions = transformExpressions(transform, feelExpression, inputName); + return joinExpressions(juelExpressions); + } + + protected List collectExpressions(String feelExpression) { + return splitExpression(feelExpression); + } + + private List splitExpression(String feelExpression) { + return Arrays.asList(feelExpression.split(COMMA_SEPARATOR_REGEX, -1)); + } + + protected List transformExpressions(FeelToJuelTransform transform, String feelExpression, String inputName) { + List expressions = collectExpressions(feelExpression); + List juelExpressions = new ArrayList(); + for (String expression : expressions) { + if (!expression.trim().isEmpty()) { + String juelExpression = transform.transformSimplePositiveUnaryTest(expression, inputName); + juelExpressions.add(juelExpression); + } + else { + throw LOG.invalidListExpression(feelExpression); + } + } + return juelExpressions; + } + + protected String joinExpressions(List juelExpressions) { + StringBuilder builder = new StringBuilder(); + builder.append("(").append(juelExpressions.get(0)).append(")"); + for (int i = 1; i < juelExpressions.size(); i++) { + builder.append(" || (").append(juelExpressions.get(i)).append(")"); + } + return builder.toString(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/NotTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/NotTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..f47173465ad35768d080f06533311d5c7626d7b1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/main/java/org/camunda/bpm/dmn/feel/impl/juel/transform/NotTransformer.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.juel.transform; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineLogger; +import org.camunda.bpm.dmn.feel.impl.juel.FeelLogger; + +public class NotTransformer implements FeelToJuelTransformer { + + public static final FeelEngineLogger LOG = FeelLogger.ENGINE_LOGGER; + public static final Pattern NOT_PATTERN = Pattern.compile("^not\\((.+)\\)$"); + + public boolean canTransform(String feelExpression) { + return feelExpression.startsWith("not("); + } + + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + String simplePositiveUnaryTests = extractInnerExpression(feelExpression); + String juelExpression = transform.transformSimplePositiveUnaryTests(simplePositiveUnaryTests, inputName); + return "not(" + juelExpression + ")"; + } + + public String extractInnerExpression(String feelExpression) { + Matcher matcher = NOT_PATTERN.matcher(feelExpression); + if (matcher.matches()) { + return matcher.group(1); + } + else { + throw LOG.invalidNotExpression(feelExpression); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelEngineTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelEngineTest.java new file mode 100644 index 0000000000000000000000000000000000000000..194b47e91729a4ef971d517654c05601bf087282 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelEngineTest.java @@ -0,0 +1,446 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineFactoryImpl; +import org.camunda.bpm.dmn.feel.impl.juel.el.FeelFunctionMapper; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.DateValue; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FeelEngineTest { + + public static final String INPUT_VARIABLE = "input"; + + public static FeelEngine feelEngine; + + public VariableMap variables; + + @BeforeClass + public static void initFeelEngine() { + feelEngine = new FeelEngineFactoryImpl().createInstance(); + } + + @Before + public void initVariables() { + variables = Variables.createVariables(); + } + + @Test + public void testLong() { + variables.putValue("integer", 12); + variables.putValue("primitive", 12L); + variables.putValue("typed", Variables.longValue(12L)); + + assertEvaluatesToTrue(Variables.longValue(12L), "<= typed"); + assertEvaluatesToTrue(Variables.longValue(12L), "<= primitive"); + assertEvaluatesToTrue(Variables.longValue(12L), "<= integer"); + } + + @Test + public void testEndpointString() { + assertEvaluatesToTrue("Hello World", "\"Hello World\""); + assertEvaluatesToFalse("Hello World", "\"Hello Camunda\""); + assertEvaluatesToFalse("Hello World", "\"\""); + assertEvaluatesToTrue("", "\"\""); + assertEvaluatesToTrue("123", "\"123\""); + assertEvaluatesToTrue("Why.not?", "\"Why.not?\""); + } + + @Test + public void testEndpointVariable() { + variables.put("y", "a"); + assertEvaluatesToTrue("a", "y"); + assertEvaluatesToFalse("b", "y"); + + variables.put("customer", Collections.singletonMap("name", "camunda")); + assertEvaluatesToTrue("camunda", "customer.name"); + assertEvaluatesToFalse("hello", "customer.name"); + } + + @Test + public void testEndpointVariableGreater() { + variables.put("y", 13.37); + assertEvaluatesToTrue(12, "y"); + assertEvaluatesToTrue(13.38, ">y"); + } + + @Test + public void testEndpointVariableLessEqual() { + variables.put("y", 13.37); + assertEvaluatesToFalse(12, ">=y"); + assertEvaluatesToTrue(13.37, ">=y"); + assertEvaluatesToTrue(13.38, ">=y"); + } + + @Test + public void testEndpointBoolean() { + assertEvaluatesToTrue(true, "true"); + assertEvaluatesToFalse(true, "false"); + assertEvaluatesToTrue(false, "false"); + assertEvaluatesToFalse(false, "true"); + } + + @Test + public void testEndpointNumber() { + assertEvaluatesToTrue(13, "13"); + assertEvaluatesToTrue(13.37, "13.37"); + assertEvaluatesToTrue(0.37, ".37"); + assertEvaluatesToFalse(13.37, "23.42"); + assertEvaluatesToFalse(0.42, ".37"); + } + + @Test + public void testEndpointNumberGreater() { + assertEvaluatesToTrue(12, "<13"); + assertEvaluatesToTrue(13.35, "<13.37"); + assertEvaluatesToTrue(0.337, "<.37"); + assertEvaluatesToFalse(13.37, "<13.37"); + assertEvaluatesToFalse(0.37, "<.37"); + } + + @Test + public void testEndpointNumberGreaterEqual() { + assertEvaluatesToTrue(13.37, "<=13.37"); + assertEvaluatesToTrue(13.337, "<=13.37"); + assertEvaluatesToTrue(0.37, "<=.37"); + assertEvaluatesToTrue(0.337, "<=.37"); + assertEvaluatesToFalse(13.42, "<=13.37"); + assertEvaluatesToFalse(0.42, "<=.37"); + } + + @Test + public void testEndpointNumberLess() { + assertEvaluatesToTrue(13.37, ">13"); + assertEvaluatesToTrue(13.42, ">13.37"); + assertEvaluatesToTrue(0.42, ">.37"); + assertEvaluatesToFalse(13.37, ">13.37"); + assertEvaluatesToFalse(0.37, ">.37"); + } + + @Test + public void testEndpointNumberLessEqual() { + assertEvaluatesToTrue(13.37, ">=13"); + assertEvaluatesToTrue(13.37, ">=13.37"); + assertEvaluatesToTrue(0.37, ">=.37"); + assertEvaluatesToTrue(0.42, ">=.37"); + assertEvaluatesToFalse(13.337, ">=13.37"); + assertEvaluatesToFalse(0.23, ">=.37"); + } + + @Test + public void testEndpointDateAndTime() { + DateValue dateTime = parseDateAndTime("2015-12-12T22:12:53"); + + assertEvaluatesToTrue(dateTime, "date and time(\"2015-12-12T22:12:53\")"); + + variables.put("y", "2015-12-12T22:12:53"); + assertEvaluatesToTrue(dateTime, "date and time(y)"); + } + + @Test + public void testThreadSafetyDateAndTimeParsing() throws ExecutionException, InterruptedException { + int threadCount = 2; + ExecutorService pool = Executors.newFixedThreadPool(threadCount); + + Set> futureSet = new HashSet>(); + Set expectedDates = new HashSet(); + + for(int i = 1; i <= 3 * threadCount; i++) { + final String dateAndTimeString = "2015-12-12T22:12:5" + i; + + expectedDates.add( + FeelFunctionMapper.parseDateAndTime(dateAndTimeString) + ); + + futureSet.add(pool.submit(new Callable() { + public Date call() throws Exception { + return FeelFunctionMapper.parseDateAndTime(dateAndTimeString); + } + })); + } + + pool.shutdown(); + + Set actualDates = new HashSet(); + for( Future dateFuture : futureSet ) { + actualDates.add(dateFuture.get()); + } + + + assertThat(actualDates).hasSameElementsAs(expectedDates); + } + + @Test + public void testIntervalNumber() { + assertEvaluatesToTrue(0.23, "[.12...37]"); + assertEvaluatesToTrue(0.23, "[.12...37)"); + assertEvaluatesToTrue(0.23, "[.12...37["); + + assertEvaluatesToTrue(0.23, "(.12...37]"); + assertEvaluatesToTrue(0.23, "(.12...37)"); + assertEvaluatesToTrue(0.23, "(.12...37["); + + assertEvaluatesToTrue(0.23, "].12...37]"); + assertEvaluatesToTrue(0.23, "].12...37)"); + assertEvaluatesToTrue(0.23, "].12...37["); + + assertEvaluatesToFalse(13.37, "[.12...37]"); + assertEvaluatesToFalse(13.37, "[.12...37)"); + assertEvaluatesToFalse(13.37, "[.12...37["); + + assertEvaluatesToFalse(13.37, "(.12...37]"); + assertEvaluatesToFalse(13.37, "(.12...37)"); + assertEvaluatesToFalse(13.37, "(.12...37["); + + assertEvaluatesToFalse(13.37, "].12...37]"); + assertEvaluatesToFalse(13.37, "].12...37)"); + assertEvaluatesToFalse(13.37, "].12...37["); + } + + @Test + public void testIntervalVariable() { + variables.put("a", 10); + variables.put("b", 15); + + assertEvaluatesToTrue(13.37, "[a..b]"); + assertEvaluatesToTrue(13.37, "[a..b)"); + assertEvaluatesToTrue(13.37, "[a..b["); + + assertEvaluatesToTrue(13.37, "(a..b]"); + assertEvaluatesToTrue(13.37, "(a..b)"); + assertEvaluatesToTrue(13.37, "(a..b["); + + assertEvaluatesToTrue(13.37, "]a..b]"); + assertEvaluatesToTrue(13.37, "]a..b)"); + assertEvaluatesToTrue(13.37, "]a..b["); + + assertEvaluatesToFalse(0.37, "[a..b]"); + assertEvaluatesToFalse(0.37, "[a..b)"); + assertEvaluatesToFalse(0.37, "[a..b["); + + assertEvaluatesToFalse(0.37, "(a..b]"); + assertEvaluatesToFalse(0.37, "(a..b)"); + assertEvaluatesToFalse(0.37, "(a..b["); + + assertEvaluatesToFalse(0.37, "]a..b]"); + assertEvaluatesToFalse(0.37, "]a..b)"); + assertEvaluatesToFalse(0.37, "]a..b["); + } + + @Test + public void testIntervalDateAndTime() { + DateValue dateAndTime = parseDateAndTime("2016-03-03T00:00:00"); + assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))"); + assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")["); + + assertEvaluatesToTrue(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToTrue(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))"); + assertEvaluatesToTrue(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")["); + + assertEvaluatesToTrue(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToTrue(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))"); + assertEvaluatesToTrue(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")["); + + assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:00\")]"); + assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:01\")["); + assertEvaluatesToTrue(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:01\"))"); + + assertEvaluatesToTrue(dateAndTime, "[date and time(\"2016-03-03T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToTrue(dateAndTime, "]date and time(\"2016-03-02T23:59:59\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToTrue(dateAndTime, "(date and time(\"2016-03-02T23:59:59\")..date and time(\"2016-06-06T00:00:00\")]"); + + + dateAndTime = parseDateAndTime("2013-03-03T00:00:00"); + assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))"); + assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")["); + + assertEvaluatesToFalse(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToFalse(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))"); + assertEvaluatesToFalse(dateAndTime, "(date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")["); + + assertEvaluatesToFalse(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToFalse(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\"))"); + assertEvaluatesToFalse(dateAndTime, "]date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-06-06T00:00:00\")["); + + assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-02T23:59:59\")]"); + assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:00\")["); + assertEvaluatesToFalse(dateAndTime, "[date and time(\"2015-12-12T00:00:00\")..date and time(\"2016-03-03T00:00:00\"))"); + + assertEvaluatesToFalse(dateAndTime, "[date and time(\"2016-03-03T00:00:01\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToFalse(dateAndTime, "]date and time(\"2016-03-03T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + assertEvaluatesToFalse(dateAndTime, "(date and time(\"2016-03-03T00:00:00\")..date and time(\"2016-06-06T00:00:00\")]"); + } + + @Test + public void testNot() { + variables.put("y", 13.37); + + assertEvaluatesToTrue("Hello camunda", "not(\"Hello World\")"); + assertEvaluatesToTrue(0.37, "not(y)"); + assertEvaluatesToFalse(0.37, "not(y)"); + assertEvaluatesToTrue(0.37, "not(>=y)"); + assertEvaluatesToTrue(0.37, "not(13.37)"); + assertEvaluatesToFalse(0.37, "not(<13.37)"); + assertEvaluatesToFalse(0.37, "not(<=13.37)"); + assertEvaluatesToTrue(0.37, "not(>13.37)"); + assertEvaluatesToTrue(0.37, "not(>=13.37)"); + assertEvaluatesToFalse(0.37, "not(.37)"); + assertEvaluatesToTrue(0.37, "not(<.37)"); + assertEvaluatesToFalse(0.37, "not(<=.37)"); + assertEvaluatesToTrue(0.37, "not(>.37)"); + assertEvaluatesToFalse(0.37, "not(>=.37)"); + } + + @Test + public void testList() { + variables.put("a", "Hello camunda"); + variables.put("y", 0); + + assertEvaluatesToTrue("Hello World", "a,\"Hello World\""); + assertEvaluatesToTrue("Hello camunda", "a,\"Hello World\""); + assertEvaluatesToFalse("Hello unknown", "a,\"Hello World\""); + assertEvaluatesToTrue(0, "y,12,13.37,.37"); + assertEvaluatesToTrue(12, "y,12,13.37,.37"); + assertEvaluatesToTrue(13.37, "y,12,13.37,.37"); + assertEvaluatesToTrue(0.37, "y,12,13.37,.37"); + assertEvaluatesToFalse(0.23, "y,12,13.37,.37"); + assertEvaluatesToTrue(-1, "13.37,>=.37"); + assertEvaluatesToTrue(0.37, "13.37,>=.37"); + assertEvaluatesToFalse(0, "13.37,>=.37"); + } + + @Test + public void testNested() { + variables.put("a", 23.42); + assertEvaluatesToTrue(0.37, "not(>=a,13.37,].37...42),<.37)"); + assertEvaluatesToFalse(23.42, "not(>=a,13.37,].37...42),<.37)"); + assertEvaluatesToFalse(13.37, "not(>=a,13.37,].37...42),<.37)"); + assertEvaluatesToFalse(0.38, "not(>=a,13.37,].37...42),<.37)"); + assertEvaluatesToFalse(0, "not(>=a,13.37,].37...42),<.37)"); + } + + @Test + public void testDontCare() { + assertEvaluatesToTrue(13.37, "-"); + } + + @Test + public void testWhitespace() { + assertEvaluatesToTrue("Hello World", "'Hello World' "); + assertEvaluatesToTrue("Hello World", " 'Hello World'"); + assertEvaluatesToTrue("Hello World", " 'Hello World' "); + assertEvaluatesToTrue(12, " 12 "); + assertEvaluatesToTrue(10.2, " <12 "); + assertEvaluatesToTrue(0, "< 12 "); + assertEvaluatesToTrue(12.3, "\t>=12 "); + assertEvaluatesToTrue(0, " not( 13 ,\t>0)\t"); + } + + @Test + public void testPojo() { + variables.putValue("pojo", new TestPojo("foo", 13.37)); + assertEvaluatesToTrue("foo", "pojo.foo"); + assertEvaluatesToFalse("camunda", "pojo.foo"); + assertEvaluatesToTrue(12, "<= pojo.bar"); + assertEvaluatesToFalse(13.33, ">= pojo.bar"); + } + + public void assertEvaluatesToTrue(Object input, String feelExpression) { + boolean result = evaluateFeel(input, feelExpression); + assertThat(result).isTrue(); + } + + public void assertEvaluatesToFalse(Object input, String feelExpression) { + boolean result = evaluateFeel(input, feelExpression); + assertThat(result).isFalse(); + } + + public boolean evaluateFeel(Object input, String feelExpression) { + variables.putValue(INPUT_VARIABLE, input); + return feelEngine.evaluateSimpleUnaryTests(feelExpression, INPUT_VARIABLE, variables.asVariableContext()); + } + + protected DateValue parseDateAndTime(String dateAndTimeString) { + Date date = FeelFunctionMapper.parseDateAndTime(dateAndTimeString); + return Variables.dateValue(date); + } + + public class TestPojo { + + protected String foo; + protected Double bar; + + public TestPojo(String foo, Double bar) { + this.foo = foo; + this.bar = bar; + } + + public String getFoo() { + return foo; + } + + public Double getBar() { + return bar; + } + + public String toString() { + return "TestPojo{" + + "foo='" + foo + '\'' + + ", bar=" + bar + + '}'; + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelExceptionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelExceptionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2c6b30b22ac5818988100bbc573f4f31fd7cf215 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelExceptionTest.java @@ -0,0 +1,310 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; + +import java.math.BigDecimal; +import java.math.BigInteger; + +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineFactoryImpl; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FeelExceptionTest { + + public static final String INPUT_VARIABLE = "input"; + + public static FeelEngine feelEngine; + + public VariableMap variables; + + @BeforeClass + public static void initFeelEngine() { + feelEngine = new FeelEngineFactoryImpl().createInstance(); + } + + @Test + public void testSimpleExpressionNotSupported() { + try { + feelEngine.evaluateSimpleExpression("12 == 12", Variables.emptyVariableContext()); + failBecauseExceptionWasNotThrown(UnsupportedOperationException.class); + } + catch (UnsupportedOperationException e) { + assertThat(e).hasMessageStartingWith("FEEL-01016"); + } + } + + @Before + public void initVariables() { + variables = Variables.createVariables(); + variables.putValue(INPUT_VARIABLE, 13); + } + + @Test + public void testInvalidNot() { + assertException("FEEL-01001", + "not(", + "not(2", + "not(2, 12", + "not(]", + "not((" + ); + } + + @Test + public void testInvalidInterval() { + assertException("FEEL-01002", + "[1..3", + "(1..3", + "]1..3", + "[1..3(", + "(1..3(", + "]1..3(", + "[1..", + "(1..", + "]1..", + "[1.3", + "[1.3]", + "[1.3)", + "[1.3[", + "(1.3", + "(1.3]", + "(1.3)", + "(1.3[", + "]1.3", + "]1.3]", + "]1.3)", + "]1.3[", + "(1.3", + "(1.3]", + "(1.3)", + "(1.3[", + "[1....3" + ); + } + + @Test + public void testInvalidComparison() { + assertException("FEEL-01003", + ">", + ">=", + "<", + "<=" + ); + } + + @Test + public void testUnknownMethod() { + assertException("FEEL-01007", + "unknown(12)", + "not(unknown(12))", + "12,13,unknown(12),14", + "not(12,13,unknown(12),14)", + "[12..unknown(12))", + "not([12..unknown(12)))", + "12,13,[12..unknown(12)),14", + "not(12,13,[12..unknown(12)),14)" + ); + } + + @Test + public void testUnknownVariable() { + assertException("FEEL-01009", + "a", + "not(a)", + "12,13,a,14", + "not(12,13,a,14)", + "[12..a)", + "not([12..a))", + "12,13,[12..a),14", + "not(12,13,[12..a),14)" + ); + } + + @Test + public void testInvalidSyntax() { + assertException("FEEL-01010", + "!= x", + "== x", + "=< 12", + "=> 12", + "< = 12", + "> = 12", + "1..3]", + "1..3)", + "1..3[", + ")1..3", + "1..3(", + "[1....3]", + "[1....3)", + "[1....3[", + "< [1..3)", + ">= [1..3)", + "${cellInput == 12}" + ); + } + + @Test + public void testUnableToConvertToBoolean() { + variables.putValue(INPUT_VARIABLE, true); + assertException("FEEL-01015", + "''", + "'camunda'", + "12", + "'true'", + "\"false\"" + ); + } + + @Test + public void testUnableToConvertToBigDecimal() { + variables.putValue(INPUT_VARIABLE, BigDecimal.valueOf(10)); + assertException("FEEL-01015", + "''", + "< ''", + "'camunda'", + "< 'camunda'", + "false", + "< true", + "'12'", + "< '12'", + "\"12\"", + "< \"12\"" + ); + } + + @Test + public void testUnableToConvertToBigInteger() { + variables.putValue(INPUT_VARIABLE, BigInteger.valueOf(10)); + assertException("FEEL-01015", + "''", + "< ''", + "'camunda'", + "< 'camunda'", + "false", + "< true", + "'12'", + "< '12'", + "\"12\"", + "< \"12\"" + ); + } + + @Test + public void testUnableToConvertToDouble() { + variables.putValue(INPUT_VARIABLE, 10.0); + assertException("FEEL-01015", + "''", + "< ''", + "'camunda'", + "< 'camunda'", + "false", + "< true", + "'12.2'", + "< '12.2'", + "\"12.2\"", + "< \"12.2\"" + ); + } + + @Test + public void testUnableToConvertToLong() { + variables.putValue(INPUT_VARIABLE, 10L); + assertException("FEEL-01015", + "''", + "< ''", + "'camunda'", + "< 'camunda'", + "false", + "< true", + "'12'", + "< '12'", + "\"12\"", + "< \"12\"" + ); + } + + @Test + public void testUnableToConvertToString() { + variables.putValue(INPUT_VARIABLE, "camunda"); + assertException("FEEL-01015", + "false", + "< true", + "12", + "< 12" + ); + } + + @Test + public void testMissingInputVariable() { + variables.remove(INPUT_VARIABLE); + assertException("FEEL-01017", + "false", + "12", + "< 12", + "'Hello'" + ); + } + + @Test + public void testInvalidDateAndTimeFormat() { + assertException("FEEL-01019", + "date and time('camunda')", + "date and time('2012-13-13')", + "date and time('13:13:13')", + "date and time('2012-12-12T25:00')" + ); + } + + @Test + public void testInvalidListFormat() { + assertException("FEEL-01020", + ",", + "1,", + "1,2,,3", + ",1,2", + "1,2, ,3,4", + "1,\t,2" + ); + } + + public void assertException(String exceptionCode, String... feelExpressions) { + for (String feelExpression : feelExpressions) { + try { + evaluateFeel(feelExpression); + failBecauseExceptionWasNotThrown(FeelException.class); + } + catch (FeelException e) { + assertThat(e).hasMessageStartingWith(exceptionCode); + assertThat(e).hasMessageContaining(feelExpression); + if (!feelExpression.startsWith("${")) { + assertThat(e.getMessage()).doesNotContain("${"); + } + } + } + } + + public boolean evaluateFeel(String feelExpression) { + return feelEngine.evaluateSimpleUnaryTests(feelExpression, INPUT_VARIABLE, variables.asVariableContext()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelToJuelTransformTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelToJuelTransformTest.java new file mode 100644 index 0000000000000000000000000000000000000000..480ed5581a083543697cf0ccc6ad32d86f3b0b2b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/FeelToJuelTransformTest.java @@ -0,0 +1,252 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransform; +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransformImpl; +import org.junit.BeforeClass; +import org.junit.Test; + +public class FeelToJuelTransformTest { + + public static FeelToJuelTransform feelToJuelTransform; + + @BeforeClass + public static void initTransform() { + feelToJuelTransform = new FeelToJuelTransformImpl(); + } + + @Test + public void testEndpointString() { + assertTransform("x", "\"Hello World\"", "${x == \"Hello World\"}"); + assertTransform("x", "\"\"", "${x == \"\"}"); + assertTransform("x", "\"123\"", "${x == \"123\"}"); + assertTransform("x", "\"Why.not?\"", "${x == \"Why.not?\"}"); + assertTransform("x", "'Hello'", "${x == 'Hello'}"); + assertTransform("x", "\"1,2,3\"", "${x == \"1,2,3\"}"); + } + + @Test + public void testEndpointVariable() { + assertTransform("x", "y", "${x == y}"); + assertTransform("x", "customer.y", "${x == customer.y}"); + } + + @Test + public void testEndpointVariableGreater() { + assertTransform("x", "y", "${x > y}"); + assertTransform("x", ">customer.y", "${x > customer.y}"); + } + + @Test + public void testEndpointVariableLessEqual() { + assertTransform("x", ">=y", "${x >= y}"); + assertTransform("x", ">=customer.y", "${x >= customer.y}"); + } + + @Test + public void testEndpointBoolean() { + assertTransform("x", "true", "${x == true}"); + assertTransform("x", "false", "${x == false}"); + } + + @Test + public void testEndpointNumber() { + assertTransform("x", "13", "${x == 13}"); + assertTransform("x", "13.37", "${x == 13.37}"); + assertTransform("x", ".37", "${x == .37}"); + } + + @Test + public void testEndpointNumberGreater() { + assertTransform("x", "<13", "${x < 13}"); + assertTransform("x", "<13.37", "${x < 13.37}"); + assertTransform("x", "<.37", "${x < .37}"); + } + + @Test + public void testEndpointNumberGreaterEqual() { + assertTransform("x", "<=13", "${x <= 13}"); + assertTransform("x", "<=13.37", "${x <= 13.37}"); + assertTransform("x", "<=.37", "${x <= .37}"); + } + + @Test + public void testEndpointNumberLess() { + assertTransform("x", ">13", "${x > 13}"); + assertTransform("x", ">13.37", "${x > 13.37}"); + assertTransform("x", ">.37", "${x > .37}"); + } + + @Test + public void testEndpointNumberLessEqual() { + assertTransform("x", ">=13", "${x >= 13}"); + assertTransform("x", ">=13.37", "${x >= 13.37}"); + assertTransform("x", ">=.37", "${x >= .37}"); + } + + @Test + public void testEndpointDate() { + assertTransform("x", "date(\"2015-12-12\")", "${x == date(\"2015-12-12\")}"); + } + + @Test + public void testIntervalNumber() { + assertTransform("x", "[0..12]", "${x >= 0 && x <= 12}"); + assertTransform("x", "[0..12)", "${x >= 0 && x < 12}"); + assertTransform("x", "[0..12[", "${x >= 0 && x < 12}"); + + assertTransform("x", "[0.12..13.37]", "${x >= 0.12 && x <= 13.37}"); + assertTransform("x", "[0.12..13.37)", "${x >= 0.12 && x < 13.37}"); + assertTransform("x", "[0.12..13.37[", "${x >= 0.12 && x < 13.37}"); + + assertTransform("x", "[.12...37]", "${x >= .12 && x <= .37}"); + assertTransform("x", "[.12...37)", "${x >= .12 && x < .37}"); + assertTransform("x", "[.12...37[", "${x >= .12 && x < .37}"); + + assertTransform("x", "(0..12]", "${x > 0 && x <= 12}"); + assertTransform("x", "(0..12)", "${x > 0 && x < 12}"); + assertTransform("x", "(0..12[", "${x > 0 && x < 12}"); + + assertTransform("x", "(0.12..13.37]", "${x > 0.12 && x <= 13.37}"); + assertTransform("x", "(0.12..13.37)", "${x > 0.12 && x < 13.37}"); + assertTransform("x", "(0.12..13.37[", "${x > 0.12 && x < 13.37}"); + + assertTransform("x", "(.12...37]", "${x > .12 && x <= .37}"); + assertTransform("x", "(.12...37)", "${x > .12 && x < .37}"); + assertTransform("x", "(.12...37[", "${x > .12 && x < .37}"); + + assertTransform("x", "]0..12]", "${x > 0 && x <= 12}"); + assertTransform("x", "]0..12)", "${x > 0 && x < 12}"); + assertTransform("x", "]0..12[", "${x > 0 && x < 12}"); + + assertTransform("x", "]0.12..13.37]", "${x > 0.12 && x <= 13.37}"); + assertTransform("x", "]0.12..13.37)", "${x > 0.12 && x < 13.37}"); + assertTransform("x", "]0.12..13.37[", "${x > 0.12 && x < 13.37}"); + + assertTransform("x", "].12...37]", "${x > .12 && x <= .37}"); + assertTransform("x", "].12...37)", "${x > .12 && x < .37}"); + assertTransform("x", "].12...37[", "${x > .12 && x < .37}"); + } + + @Test + public void testIntervalVariable() { + assertTransform("x", "[a..b]", "${x >= a && x <= b}"); + assertTransform("x", "[a..b)", "${x >= a && x < b}"); + assertTransform("x", "[a..b[", "${x >= a && x < b}"); + + assertTransform("x", "(a..b]", "${x > a && x <= b}"); + assertTransform("x", "(a..b)", "${x > a && x < b}"); + assertTransform("x", "(a..b[", "${x > a && x < b}"); + + assertTransform("x", "]a..b]", "${x > a && x <= b}"); + assertTransform("x", "]a..b)", "${x > a && x < b}"); + assertTransform("x", "]a..b[", "${x > a && x < b}"); + } + + @Test + public void testIntervalDate() { + assertTransform("x", "[date(\"2015-12-12\")..date(\"2016-06-06\")]", "${x >= date(\"2015-12-12\") && x <= date(\"2016-06-06\")}"); + assertTransform("x", "[date(\"2015-12-12\")..date(\"2016-06-06\"))", "${x >= date(\"2015-12-12\") && x < date(\"2016-06-06\")}"); + assertTransform("x", "[date(\"2015-12-12\")..date(\"2016-06-06\")[", "${x >= date(\"2015-12-12\") && x < date(\"2016-06-06\")}"); + + assertTransform("x", "(date(\"2015-12-12\")..date(\"2016-06-06\")]", "${x > date(\"2015-12-12\") && x <= date(\"2016-06-06\")}"); + assertTransform("x", "(date(\"2015-12-12\")..date(\"2016-06-06\"))", "${x > date(\"2015-12-12\") && x < date(\"2016-06-06\")}"); + assertTransform("x", "(date(\"2015-12-12\")..date(\"2016-06-06\")[", "${x > date(\"2015-12-12\") && x < date(\"2016-06-06\")}"); + + assertTransform("x", "]date(\"2015-12-12\")..date(\"2016-06-06\")]", "${x > date(\"2015-12-12\") && x <= date(\"2016-06-06\")}"); + assertTransform("x", "]date(\"2015-12-12\")..date(\"2016-06-06\"))", "${x > date(\"2015-12-12\") && x < date(\"2016-06-06\")}"); + assertTransform("x", "]date(\"2015-12-12\")..date(\"2016-06-06\")[", "${x > date(\"2015-12-12\") && x < date(\"2016-06-06\")}"); + } + + @Test + public void testNot() { + assertTransform("x", "not(\"Hello World\")", "${not(x == \"Hello World\")}"); + assertTransform("x", "not(y)", "${not(x == y)}"); + assertTransform("x", "not(y)", "${not(x > y)}"); + assertTransform("x", "not(>=y)", "${not(x >= y)}"); + assertTransform("x", "not(13.37)", "${not(x == 13.37)}"); + assertTransform("x", "not(<13.37)", "${not(x < 13.37)}"); + assertTransform("x", "not(<=13.37)", "${not(x <= 13.37)}"); + assertTransform("x", "not(>13.37)", "${not(x > 13.37)}"); + assertTransform("x", "not(>=13.37)", "${not(x >= 13.37)}"); + assertTransform("x", "not(.37)", "${not(x == .37)}"); + assertTransform("x", "not(<.37)", "${not(x < .37)}"); + assertTransform("x", "not(<=.37)", "${not(x <= .37)}"); + assertTransform("x", "not(>.37)", "${not(x > .37)}"); + assertTransform("x", "not(>=.37)", "${not(x >= .37)}"); + assertTransform("x", "not(date(\"2015-12-12\"))", "${not(x == date(\"2015-12-12\"))}"); + assertTransform("x", "not(date(\"2015-12-12\"))", "${not(x > date(\"2015-12-12\"))}"); + assertTransform("x", "not(>=date(\"2015-12-12\"))", "${not(x >= date(\"2015-12-12\"))}"); + } + + @Test + public void testList() { + assertTransform("x", "a,\"Hello World\"", "${(x == a) || (x == \"Hello World\")}"); + assertTransform("x", "y,12,13.37,.37", "${(x == y) || (x == 12) || (x == 13.37) || (x == .37)}"); + assertTransform("x", "13.37,>=.37", "${(x < y) || (x <= 12) || (x > 13.37) || (x >= .37)}"); + assertTransform("x", "a,date(\"2015-12-12\"),date(\"2016-06-06\"),date(\"2017-07-07\")", "${(x == a) || (x == date(\"2015-12-12\")) || (x == date(\"2016-06-06\")) || (x == date(\"2017-07-07\"))}"); + assertTransform("x", "date(\"2016-06-06\"),>=date(\"2017-07-07\")", "${(x < a) || (x <= date(\"2015-12-12\")) || (x > date(\"2016-06-06\")) || (x >= date(\"2017-07-07\"))}"); + assertTransform("x", "1,\"2,3,4\",5,\"6,7,8\",9", "${(x == 1) || (x == \"2,3,4\") || (x == 5) || (x == \"6,7,8\") || (x == 9)}"); + } + + @Test + public void testNested() { + assertTransform("x", "not(>=a,13.37,].37...42),<.37)", "${not((x >= a) || (x == 13.37) || (x > .37 && x < .42) || (x < .37))}"); + } + + @Test + public void testDontCare() { + assertTransform("x", "-", "${true}"); + } + + @Test + public void testWhitespace() { + assertTransform("x", "'Hello World' ", "${x == 'Hello World'}"); + assertTransform("x", " 'Hello World'", "${x == 'Hello World'}"); + assertTransform("x", " 'Hello World' ", "${x == 'Hello World'}"); + assertTransform("x", " 12 ", "${x == 12}"); + assertTransform("x", " <12 ", "${x < 12}"); + assertTransform("x", "< 12 ", "${x < 12}"); + assertTransform("x", "\t>=12 ", "${x >= 12}"); + assertTransform("x", " not( x,\t>0, <12 , a )\t", "${not((x == x) || (x > 0) || (x < 12) || (x == a))}"); + } + + public void assertTransform(String input, String feelExpression, String expectedExpression) { + String expression = feelToJuelTransform.transformSimpleUnaryTests(feelExpression, input); + assertThat(expression).isEqualTo(expectedExpression); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/custom/FeelEngineCustomFunctionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/custom/FeelEngineCustomFunctionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..fd97bb3247b7813bfc3f9a03e79c7a450e82ef43 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/custom/FeelEngineCustomFunctionTest.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.custom; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.dmn.feel.impl.FeelEngine; +import org.camunda.bpm.dmn.feel.impl.juel.FeelEngineFactoryImpl; +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelFunctionTransformer; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.junit.Before; +import org.junit.Test; + +public class FeelEngineCustomFunctionTest { + + public static final String INPUT_VARIABLE = "input"; + + public FeelEngine feelEngine; + + public VariableMap variables; + + @Before + public void initEngine() { + variables = Variables.createVariables(); + + List customFunctionTransformers = new ArrayList(); + customFunctionTransformers.add(new StartsWithFunctionTransformer()); + + FeelEngineFactoryImpl feelEngineFactory = new FeelEngineFactoryImpl(customFunctionTransformers); + + feelEngine = feelEngineFactory.createInstance(); + } + + @Test + public void testStringStartsWith() { + assertEvaluatesToTrue("foobar", "starts with(\"foo\")"); + assertEvaluatesToFalse("foobar", "starts with(\"foa\")"); + assertEvaluatesToFalse("foobar", "starts with(\"afoo\")"); + assertEvaluatesToTrue("foobar", "starts with(\"foobar\")"); + assertEvaluatesToFalse("", "starts with(\"foobar\")"); + assertEvaluatesToFalse(null, "starts with(\"foobar\")"); + } + + public void assertEvaluatesToTrue(Object input, String feelExpression) { + boolean result = evaluateFeel(input, feelExpression); + assertThat(result).isTrue(); + } + + public void assertEvaluatesToFalse(Object input, String feelExpression) { + boolean result = evaluateFeel(input, feelExpression); + assertThat(result).isFalse(); + } + + public boolean evaluateFeel(Object input, String feelExpression) { + variables.putValue(INPUT_VARIABLE, input); + return feelEngine.evaluateSimpleUnaryTests(feelExpression, INPUT_VARIABLE, variables.asVariableContext()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/custom/StartsWithFunctionTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/custom/StartsWithFunctionTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..6917f451f837e8d1aaece4c94dd02492fd0c2c54 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-juel/src/test/java/org/camunda/bpm/dmn/feel/impl/custom/StartsWithFunctionTransformer.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.custom; + +import java.lang.reflect.Method; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelFunctionTransformer; +import org.camunda.bpm.dmn.feel.impl.juel.transform.FeelToJuelTransform; + +public class StartsWithFunctionTransformer implements FeelToJuelFunctionTransformer { + + public static final Pattern STARTS_WITH_PATTERN = Pattern.compile("^starts with\\((.+)\\)$"); + + public static final String JUEL_STARTS_WITH = "startsWith"; + + protected static Method method; + + static { + try { + method = StartsWithFunctionTransformer.class.getMethod(JUEL_STARTS_WITH, String.class, String.class); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + + public boolean canTransform(String feelExpression) { + Matcher startsWithMatcher = STARTS_WITH_PATTERN.matcher(feelExpression); + + return startsWithMatcher.matches(); + } + + @Override + public String transform(FeelToJuelTransform transform, String feelExpression, String inputName) { + Matcher startsWithMatcher = STARTS_WITH_PATTERN.matcher(feelExpression); + + if (startsWithMatcher.matches()) { + return JUEL_STARTS_WITH + "(" + inputName + ", " + startsWithMatcher.group(1) + ")"; + } else { + return feelExpression; + } + } + + public static boolean startsWith(final String input, final String match) { + if (input != null) { + return input.startsWith(match); + } + return false; + } + + @Override + public String getName() { + return JUEL_STARTS_WITH; + } + + @Override + public Method getMethod() + { + return method; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/README.md b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8240afe40ee6a8e33822ab7a17d03a96686fcdf7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/README.md @@ -0,0 +1,3 @@ +# Scala FEEL Engine + +An integration of the [Scala FEEL Engine](https://github.com/camunda/feel-scala) for the [Camunda DMN Engine](https://github.com/camunda/camunda-engine-dmn). diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..41ac91888bc61687e1c3d5d8810201b57c57e0c5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/pom.xml @@ -0,0 +1,80 @@ + + 4.0.0 + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + org.camunda.bpm.dmn + camunda-engine-dmn-root + 7.24.0-SNAPSHOT + + + camunda-engine-feel-scala + camunda DMN - engine FEEL - SCALA + + org.camunda.bpm.dmn.feel.impl.scala + + + + + org.camunda.feel + feel-engine + scala-shaded + + + + org.camunda.bpm.dmn + camunda-engine-feel-api + + + + ch.qos.logback + logback-classic + test + + + + junit + junit + test + + + + org.mockito + mockito-core + test + + + + org.assertj + assertj-core + test + + + + + + + org.apache.felix + maven-bundle-plugin + + + generate-sources + + cleanVersions + + + + bundle-manifest + process-classes + + manifest + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ContextVariableWrapper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ContextVariableWrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..4ca9ee4a6f9b445327753d60d18ca7246de61ead --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ContextVariableWrapper.java @@ -0,0 +1,55 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala; + +import org.camunda.bpm.engine.variable.context.VariableContext; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.camunda.feel.context.VariableProvider; +import camundajar.impl.scala.Option; +import camundajar.impl.scala.Some; +import camundajar.impl.scala.collection.Iterable; + +import java.util.Set; + +import static camundajar.impl.scala.jdk.CollectionConverters.SetHasAsScala; + +public class ContextVariableWrapper implements VariableProvider { + + protected VariableContext context; + + public ContextVariableWrapper(VariableContext context) { + this.context = context; + } + + public Option getVariable(String name) { + if (context.containsVariable(name)) { + TypedValue typedValue = context.resolve(name); + Object value = typedValue.getValue(); + return new Some(value); + + } else { + return camundajar.impl.scala.None$.MODULE$; + + } + } + + public Iterable keys() { + Set strings = context.keySet(); + return SetHasAsScala(strings).asScala(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelEngine.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelEngine.java new file mode 100644 index 0000000000000000000000000000000000000000..e725f3c396503a5c30124849d6b97113325708ae --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelEngine.java @@ -0,0 +1,158 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala; + +import org.camunda.bpm.dmn.feel.impl.FeelEngine; +import org.camunda.bpm.dmn.feel.impl.scala.function.CustomFunctionTransformer; +import org.camunda.bpm.dmn.feel.impl.scala.function.FeelCustomFunctionProvider; +import org.camunda.bpm.dmn.feel.impl.scala.spin.SpinValueMapperFactory; +import org.camunda.bpm.engine.variable.context.VariableContext; +import org.camunda.feel.FeelEngine$; +import org.camunda.feel.FeelEngine.Builder; +import org.camunda.feel.FeelEngine.Failure; +import org.camunda.feel.context.CustomContext; +import org.camunda.feel.context.VariableProvider; +import org.camunda.feel.context.VariableProvider.StaticVariableProvider; +import org.camunda.feel.impl.JavaValueMapper; +import org.camunda.feel.valuemapper.CustomValueMapper; +import org.camunda.feel.valuemapper.ValueMapper.CompositeValueMapper; +import camundajar.impl.scala.collection.immutable.List; +import camundajar.impl.scala.collection.immutable.Map; +import camundajar.impl.scala.runtime.BoxesRunTime; +import camundajar.impl.scala.util.Either; +import camundajar.impl.scala.util.Left; +import camundajar.impl.scala.util.Right; + +import java.util.Arrays; + +import static org.camunda.feel.context.VariableProvider.CompositeVariableProvider; +import static camundajar.impl.scala.jdk.CollectionConverters.ListHasAsScala; + +public class ScalaFeelEngine implements FeelEngine { + + protected static final String INPUT_VARIABLE_NAME = "inputVariableName"; + + protected static final ScalaFeelLogger LOGGER = ScalaFeelLogger.LOGGER; + + protected org.camunda.feel.FeelEngine feelEngine; + + public ScalaFeelEngine(java.util.List functionProviders) { + List valueMappers = getValueMappers(); + + CompositeValueMapper compositeValueMapper = new CompositeValueMapper(valueMappers); + + CustomFunctionTransformer customFunctionTransformer = + new CustomFunctionTransformer(functionProviders, compositeValueMapper); + + feelEngine = buildFeelEngine(customFunctionTransformer, compositeValueMapper); + } + + public T evaluateSimpleExpression(String expression, VariableContext variableContext) { + + CustomContext context = new CustomContext() { + public VariableProvider variableProvider() { + return new ContextVariableWrapper(variableContext); + } + }; + + Either either = feelEngine.evalExpression(expression, context); + + if (either instanceof Right) { + Right right = (Right) either; + + return (T) right.value(); + + } else { + Left left = (Left) either; + Failure failure = (Failure) left.value(); + String message = failure.message(); + + throw LOGGER.evaluationException(message); + + } + } + + public boolean evaluateSimpleUnaryTests(String expression, + String inputVariable, + VariableContext variableContext) { + Map inputVariableMap = new Map.Map1(INPUT_VARIABLE_NAME, inputVariable); + + StaticVariableProvider inputVariableContext = new StaticVariableProvider(inputVariableMap); + + ContextVariableWrapper contextVariableWrapper = new ContextVariableWrapper(variableContext); + + CustomContext context = new CustomContext() { + public VariableProvider variableProvider() { + return new CompositeVariableProvider(toScalaList(inputVariableContext, contextVariableWrapper)); + } + }; + + Either either = feelEngine.evalUnaryTests(expression, context); + + if (either instanceof Right) { + Right right = (Right) either; + Object value = right.value(); + + return BoxesRunTime.unboxToBoolean(value); + + } else { + Left left = (Left) either; + Failure failure = (Failure) left.value(); + String message = failure.message(); + + throw LOGGER.evaluationException(message); + + } + } + + protected List getValueMappers() { + SpinValueMapperFactory spinValueMapperFactory = new SpinValueMapperFactory(); + + CustomValueMapper javaValueMapper = new JavaValueMapper(); + + CustomValueMapper spinValueMapper = spinValueMapperFactory.createInstance(); + if (spinValueMapper != null) { + return toScalaList(javaValueMapper, spinValueMapper); + + } else { + return toScalaList(javaValueMapper); + + } + } + + @SafeVarargs + protected final List toScalaList(T... elements) { + java.util.List listAsJava = Arrays.asList(elements); + + return toList(listAsJava); + } + + protected List toList(java.util.List list) { + return ListHasAsScala(list).asScala().toList(); + } + + protected org.camunda.feel.FeelEngine buildFeelEngine(CustomFunctionTransformer transformer, + CompositeValueMapper valueMapper) { + return new Builder() + .functionProvider(transformer) + .valueMapper(valueMapper) + .enableExternalFunctions(false) + .build(); + } + +} + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelEngineFactory.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelEngineFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..3caea9846979f8d878e459bec9f535ce6ac7cb4a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelEngineFactory.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala; + +import org.camunda.bpm.dmn.feel.impl.FeelEngine; +import org.camunda.bpm.dmn.feel.impl.FeelEngineFactory; +import org.camunda.bpm.dmn.feel.impl.scala.function.FeelCustomFunctionProvider; + +import java.util.List; + +public class ScalaFeelEngineFactory implements FeelEngineFactory { + + protected List customFunctionProviders; + + public ScalaFeelEngineFactory() { + } + + public ScalaFeelEngineFactory(List customFunctionProviders) { + this.customFunctionProviders = customFunctionProviders; + } + + public FeelEngine createInstance() { + return new ScalaFeelEngine(customFunctionProviders); + } + + public void setCustomFunctionProviders(List customFunctionProviders) { + this.customFunctionProviders = customFunctionProviders; + } + + public List getCustomFunctionProviders() { + return customFunctionProviders; + } + +} + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelLogger.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelLogger.java new file mode 100644 index 0000000000000000000000000000000000000000..b26b62fbed6b43854dd163d6fe3f16adb5d05a0d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/ScalaFeelLogger.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala; + +import org.camunda.bpm.dmn.feel.impl.FeelException; +import org.camunda.bpm.dmn.feel.impl.scala.spin.SpinValueMapperFactory; +import org.camunda.commons.logging.BaseLogger; + +public class ScalaFeelLogger extends BaseLogger { + + public static final String PROJECT_CODE = "FEEL/SCALA"; + public static final String PROJECT_LOGGER = "org.camunda.bpm.dmn.feel.scala"; + + public static final ScalaFeelLogger LOGGER = createLogger(ScalaFeelLogger.class, + PROJECT_CODE, PROJECT_LOGGER, "01"); + + protected void logError(String id, String messageTemplate, Throwable t) { + super.logError(id, messageTemplate, t); + } + + protected void logInfo(String id, String messageTemplate, Throwable t) { + super.logInfo(id, messageTemplate, t); + } + + public void logSpinValueMapperDetected() { + logInfo("001", "Spin value mapper detected"); + } + + public FeelException spinValueMapperInstantiationException(Throwable cause) { + return new FeelException(exceptionMessage( + "002", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " + + "on class path but cannot be instantiated."), cause); + } + + public FeelException spinValueMapperAccessException(Throwable cause) { + return new FeelException(exceptionMessage( + "003", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " + + "on class path but cannot be accessed."), cause); + } + + public FeelException spinValueMapperCastException(Throwable cause, String className) { + return new FeelException(exceptionMessage( + "004", SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME + " class found " + + "on class path but cannot be cast to " + className), cause); + } + + public FeelException spinValueMapperException(Throwable cause) { + return new FeelException(exceptionMessage( + "005", "Error while looking up or registering Spin value mapper", cause)); + } + + public FeelException functionCountExceededException() { + return new FeelException(exceptionMessage( + "006", "Only set one return value or a function.")); + } + + public FeelException customFunctionNotFoundException() { + return new FeelException(exceptionMessage( + "007", "Custom function not available.")); + } + + public FeelException evaluationException(String message) { + return new FeelException(exceptionMessage( + "008", "Error while evaluating expression: {}", message)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/CustomFunction.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/CustomFunction.java new file mode 100644 index 0000000000000000000000000000000000000000..f57c119683d0ae30c3040904e9d8a00e456f8c19 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/CustomFunction.java @@ -0,0 +1,69 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala.function; + +import org.camunda.bpm.dmn.feel.impl.scala.function.builder.CustomFunctionBuilder; +import org.camunda.bpm.dmn.feel.impl.scala.function.builder.CustomFunctionBuilderImpl; + +import java.util.Collections; +import java.util.List; +import java.util.function.Function; + +public class CustomFunction { + + protected List params; + protected Function, Object> function; + protected boolean hasVarargs; + + public CustomFunction() { + params = Collections.emptyList(); + } + + /** + * Creates a fluent builder to configure a custom function + * + * @return builder to apply configurations on + */ + public static CustomFunctionBuilder create() { + return new CustomFunctionBuilderImpl(); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + public Function, Object> getFunction() { + return function; + } + + public void setFunction(Function, Object> function) { + this.function = function; + } + + public boolean hasVarargs() { + return hasVarargs; + } + + public void setHasVarargs(boolean hasVarargs) { + this.hasVarargs = hasVarargs; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/CustomFunctionTransformer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/CustomFunctionTransformer.java new file mode 100644 index 0000000000000000000000000000000000000000..e77c493b1e7a2e79003ed2ecd10dcaff5e0daa79 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/CustomFunctionTransformer.java @@ -0,0 +1,107 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala.function; + +import org.camunda.bpm.dmn.feel.impl.scala.ScalaFeelLogger; +import org.camunda.feel.context.JavaFunction; +import org.camunda.feel.context.JavaFunctionProvider; +import org.camunda.feel.syntaxtree.Val; +import org.camunda.feel.valuemapper.ValueMapper; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class CustomFunctionTransformer extends JavaFunctionProvider { + + protected static final ScalaFeelLogger LOGGER = ScalaFeelLogger.LOGGER; + + protected Map functions; + protected ValueMapper valueMapper; + + public CustomFunctionTransformer(List functionProviders, + ValueMapper valueMapper) { + this.functions = new HashMap<>(); + this.valueMapper = valueMapper; + + if (functionProviders != null) { + transformFunctions(functionProviders); + } + } + + protected void transformFunctions(List functionProviders) { + functionProviders.forEach(functionProvider -> { + Collection functionNames = functionProvider.getFunctionNames(); + + functionNames.forEach(functionName -> { + CustomFunction customFunction = functionProvider.resolveFunction(functionName) + .orElseThrow(LOGGER::customFunctionNotFoundException); + + List params = customFunction.getParams(); + + Function, Val> function = transformFunction(customFunction); + + boolean hasVarargs = customFunction.hasVarargs(); + + JavaFunction javaFunction = new JavaFunction(params, function, hasVarargs); + + this.functions.put(functionName, javaFunction); + }); + }); + } + + protected Function, Val> transformFunction(CustomFunction function) { + return args -> { + + List unpackedArgs = unpackVals(args); + + Function, Object> functionHandler = function.getFunction(); + Object result = functionHandler.apply(unpackedArgs); + + return toVal(result); + }; + } + + protected List unpackVals(List args) { + return args.stream() + .map(this::unpackVal) + .collect(Collectors.toList()); + } + + protected Val toVal(Object rawResult) { + return valueMapper.toVal(rawResult); + } + + protected Object unpackVal(Val arg) { + return valueMapper.unpackVal(arg); + } + + @Override + public Optional resolveFunction(String functionName) { + return Optional.ofNullable(functions.get(functionName)); + } + + @Override + public Collection getFunctionNames() { + return functions.keySet(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/FeelCustomFunctionProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/FeelCustomFunctionProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..c580a8d025e6975e17b02b69ee824799d72fa0d7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/FeelCustomFunctionProvider.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala.function; + +import java.util.Collection; +import java.util.Optional; + +/** + * Provides one or more functions which can be used in an FEEL expression. + */ +public interface FeelCustomFunctionProvider { + + /** + * Returns the function for the given name. + * + * @param functionName the name of the function + * @return the function or {@link Optional#empty()}, if no function is provided for this name + */ + Optional resolveFunction(String functionName); + + /** + * Returns the names of all functions. + * + * @return the names of all functions + */ + Collection getFunctionNames(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/builder/CustomFunctionBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/builder/CustomFunctionBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..2fc12de51d883b977a6e53a28a9bfeddc40ef824 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/builder/CustomFunctionBuilder.java @@ -0,0 +1,80 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala.function.builder; + +import org.camunda.bpm.dmn.feel.impl.FeelException; +import org.camunda.bpm.dmn.feel.impl.scala.function.CustomFunction; +import org.camunda.bpm.dmn.feel.impl.scala.function.FeelCustomFunctionProvider; + +import java.util.List; +import java.util.function.Function; + +/** + * Fluent builder to create a {@link CustomFunction}. + */ +public interface CustomFunctionBuilder { + + /** + * Define the parameters of the custom function. + * + * @param params of the custom function + * @return the builder + */ + CustomFunctionBuilder setParams(String... params); + + /** + * Enable variable arguments + * + * @return the builder + */ + CustomFunctionBuilder enableVarargs(); + + /** + * Define a custom function that only returns a value and + * has no further business logic (method body). + * + * It is not possible to use this method together with + * {@link #setFunction}. + * + * @param result that should be returned by the custom function + * @return the builder + */ + CustomFunctionBuilder setReturnValue(Object result); + + /** + * Pass a {@link Function} with a {@link List} of objects as argument + * and an object as return value. + * + * It is not possible to use this method together with + * {@link #setReturnValue}. + * + * @param function to be called + * @return the builder + */ + CustomFunctionBuilder setFunction(Function, Object> function); + + /** + * Returns the custom function to be registered in + * {@link FeelCustomFunctionProvider}. + * + * @throws FeelException when both {@link #setFunction} and {@link #setReturnValue} were called + * + * @return a custom function + */ + CustomFunction build(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/builder/CustomFunctionBuilderImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/builder/CustomFunctionBuilderImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..939269652c14d1bbe3bf006fee34cca1797df392 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/function/builder/CustomFunctionBuilderImpl.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala.function.builder; + +import org.camunda.bpm.dmn.feel.impl.scala.ScalaFeelLogger; +import org.camunda.bpm.dmn.feel.impl.scala.function.CustomFunction; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; + +public class CustomFunctionBuilderImpl implements CustomFunctionBuilder { + + protected static final ScalaFeelLogger LOGGER = ScalaFeelLogger.LOGGER; + + protected CustomFunction customFunction; + protected int functionCount; + + public CustomFunctionBuilderImpl() { + customFunction = new CustomFunction(); + functionCount = 0; + } + + @Override + public CustomFunctionBuilder setParams(String... params) { + List paramList = Arrays.asList(params); + customFunction.setParams(paramList); + return this; + } + + @Override + public CustomFunctionBuilder enableVarargs() { + customFunction.setHasVarargs(true); + return this; + } + + @Override + public CustomFunctionBuilder setReturnValue(Object returnValue) { + functionCount++; + customFunction.setFunction((args) -> returnValue); + return this; + } + + @Override + public CustomFunctionBuilder setFunction(Function, Object> function) { + functionCount++; + customFunction.setFunction(function); + return this; + } + + @Override + public CustomFunction build() { + checkHasFunction(); + return customFunction; + } + + protected void checkHasFunction() { + if (functionCount > 1) { + throw LOGGER.functionCountExceededException(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/spin/SpinValueMapperFactory.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/spin/SpinValueMapperFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..6eb8f433692d2b49179e837bf508af7443aa1aeb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/java/org/camunda/bpm/dmn/feel/impl/scala/spin/SpinValueMapperFactory.java @@ -0,0 +1,79 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.feel.impl.scala.spin; + +import org.camunda.bpm.dmn.feel.impl.scala.ScalaFeelLogger; +import org.camunda.feel.valuemapper.CustomValueMapper; + +public class SpinValueMapperFactory { + + protected static final ScalaFeelLogger LOGGER = ScalaFeelLogger.LOGGER; + + public static final String SPIN_VALUE_MAPPER_CLASS_NAME = + "org.camunda.spin.plugin.impl.feel.integration.SpinValueMapper"; + + public CustomValueMapper createInstance() { + Class valueMapperClass = lookupClass(); + + CustomValueMapper valueMapper = null; + if (valueMapperClass != null) { + valueMapper = newInstance(valueMapperClass); + + if (valueMapper != null) { + LOGGER.logSpinValueMapperDetected(); + + } + } // else: engine plugin is not on classpath + + return valueMapper; + } + + protected CustomValueMapper newInstance(Class valueMapperClass) { + try { + return (CustomValueMapper) valueMapperClass.newInstance(); + + } catch (InstantiationException e) { + throw LOGGER.spinValueMapperInstantiationException(e); + + } catch (IllegalAccessException e) { + throw LOGGER.spinValueMapperAccessException(e); + + } catch (ClassCastException e) { + throw LOGGER.spinValueMapperCastException(e, CustomValueMapper.class.getName()); + + } catch (Throwable e) { + throw LOGGER.spinValueMapperException(e); + + } + } + + protected Class lookupClass() { + try { + return Class.forName(SPIN_VALUE_MAPPER_CLASS_NAME); + + } catch (ClassNotFoundException ignored) { + // engine plugin is not on class path => ignore + + } catch (Throwable e) { + throw LOGGER.spinValueMapperException(e); + + } + + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/resources/META-INF/services/org.camunda.feel.valuemapper.CustomValueMapper b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/resources/META-INF/services/org.camunda.feel.valuemapper.CustomValueMapper new file mode 100644 index 0000000000000000000000000000000000000000..406b0defced3d90f49442aa551e294574cfee02e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/main/resources/META-INF/services/org.camunda.feel.valuemapper.CustomValueMapper @@ -0,0 +1 @@ +org.camunda.feel.impl.JavaValueMapper \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/CustomFunctionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/CustomFunctionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d07fbec6e1e3ecb7bdee75b62c786efbe2743270 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/CustomFunctionTest.java @@ -0,0 +1,539 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.engine.feel.function; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; +import org.camunda.bpm.dmn.engine.feel.function.helper.FunctionProvider; +import org.camunda.bpm.dmn.engine.feel.function.helper.MyPojo; +import org.camunda.bpm.dmn.engine.feel.helper.FeelRule; +import org.camunda.bpm.dmn.feel.impl.FeelException; +import org.camunda.bpm.dmn.feel.impl.scala.function.CustomFunction; +import org.camunda.bpm.dmn.feel.impl.scala.function.builder.CustomFunctionBuilder; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.RuleChain; + +public class CustomFunctionTest { + + protected FeelRule feelRule = FeelRule.buildWithFunctionProvider(); + protected ExpectedException thrown = ExpectedException.none(); + + @Rule + public RuleChain ruleChain = RuleChain.outerRule(feelRule).around(thrown); + + protected FunctionProvider functionProvider; + + @Before + public void assign() { + functionProvider = feelRule.getFunctionProvider(); + } + + @Test + public void shouldThrowExceptionBothFunctionAndReturnValueSet() { + // given + CustomFunctionBuilder myFunctionBuilder = CustomFunction.create() + .setParams("x") + .setFunction(args -> "") + .setReturnValue("foo"); + + // then + thrown.expect(FeelException.class); + thrown.expectMessage("Only set one return value or a function."); + + // when + myFunctionBuilder.build(); + } + + @Test + public void shouldSetMultipleArgs() { + // given + CustomFunction myFunction = CustomFunction.create() + .setParams("x", "y", "z") + .setFunction(args -> { + String argX = (String) args.get(0); + boolean argY = (boolean) args.get(1); + List argZ = (List) args.get(2); + + return argX + "-" + argY + "-" + argZ; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + String result = feelRule.evaluateExpression("myFunction(\"foo\", true, [\"elem\"])"); + + // then + assertThat(result).isEqualTo("foo-true-[elem]"); + } + + @Test + public void shouldRegisterMultipleFunctions() { + // given + CustomFunction myFunctionA = CustomFunction.create() + .setReturnValue("A") + .build(); + + CustomFunction myFunctionB = CustomFunction.create() + .setReturnValue("B") + .build(); + + CustomFunction myFunctionC = CustomFunction.create() + .setReturnValue("C") + .build(); + + functionProvider.register("myFunctionA", myFunctionA); + functionProvider.register("myFunctionB", myFunctionB); + functionProvider.register("myFunctionC", myFunctionC); + + // when + String result = feelRule.evaluateExpression("myFunctionA()+myFunctionB()+myFunctionC()"); + + // then + assertThat(result).isEqualTo("ABC"); + } + + @Test + public void shouldCallBean() { + // given + MyPojo testBean = new MyPojo(3); + CustomFunction myFunction = CustomFunction.create() + .setFunction(args -> testBean.call(2)) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + long result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).isEqualTo(6); + } + + @Test + public void shouldPassInteger() { + // given + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isEqualTo((long) 12); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", 12); + } + + @Test + public void shouldPassDouble() { + // given + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isEqualTo((double)12.1); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", 12.1); + } + + @Test + public void shouldPassString() { + // given + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isEqualTo("foo"); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", "foo"); + } + + @Test + public void shouldPassNull() { + // given + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isNull(); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", null); + } + + @Test + public void shouldPassTrue() { + // given + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isEqualTo(true); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", true); + } + + @Test + public void shouldPassDate() { + // given + Date now = new Date(); + LocalDateTime localDateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()); + + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isEqualTo(localDateTime); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", now); + } + + @Test + public void shouldPassList() { + // given + List list = Arrays.asList("foo", "bar", "bazz"); + + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isEqualTo(list); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", list); + } + + @Test + public void shouldPassMap() { + // given + Map map = Collections.singletonMap("foo", "bar"); + + CustomFunction myFunction = CustomFunction.create() + .setParams("x") + .setFunction(args -> { + Object argX = args.get(0); + + // then + assertThat(argX).isEqualTo(map); + + return ""; + }) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + feelRule.evaluateExpression("myFunction(variable)", map); + } + + @Test + public void shouldReturnString() { + // given + CustomFunction myFunction = CustomFunction.create() + .setReturnValue("foo") + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + String result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).isEqualTo("foo"); + } + + @Test + public void shouldReturnDouble() { + // given + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(1.7976931348623157) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + double result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).isEqualTo(1.7976931348623157); + } + + @Test + public void shouldReturnNull() { + // given + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(null) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + Object result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).isNull(); + } + + @Test + public void shouldReturnTrue() { + // given + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(true) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + boolean result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).isTrue(); + } + + @Test + public void shouldReturnDate() { + // given + Date now = new Date(); + + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(now) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + LocalDateTime result = feelRule.evaluateExpression("myFunction()"); + + LocalDateTime localDateTime = LocalDateTime.ofInstant(now.toInstant(), ZoneId.systemDefault()); + + // then + assertThat(result).isEqualTo(localDateTime); + } + + @Test + public void shouldReturnList() { + // given + List list = Arrays.asList("foo", "bar", "bazz"); + + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(list) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + List result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).containsExactly("foo", "bar", "bazz"); + } + + @Test + public void shouldReturnList_Nested() { + // given + List list = Arrays.asList("foo", Arrays.asList("bar", "bazz")); + + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(list) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + List result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).containsExactly("foo", Arrays.asList("bar", "bazz")); + } + + @Test + public void shouldReturnMap() { + // given + Map map = Collections.singletonMap("foo", "bar"); + + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(map) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + Map result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).containsExactly(entry("foo", "bar")); + } + + @Test + public void shouldReturnMap_Nested() { + // given + Map map = Collections.singletonMap("foo", + Collections.singletonMap("bar", "bazz")); + + CustomFunction myFunction = CustomFunction.create() + .setReturnValue(map) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + Map result = feelRule.evaluateExpression("myFunction()"); + + // then + assertThat(result).containsExactly(entry("foo", Collections.singletonMap("bar", "bazz"))); + } + + @Test + public void shouldPassVarargs() { + // given + CustomFunction myFunction = CustomFunction.create() + .enableVarargs() + .setFunction(args -> args) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + List result = feelRule.evaluateExpression("myFunction(\"foo\", \"bar\", \"baz\")"); + + // then + assertThat(result).containsExactly("foo", "bar", "baz"); + } + + @Test + public void shouldThrowExceptionDueToDisabledVarargs() { + // given + CustomFunction myFunction = CustomFunction.create() + .setFunction(args -> args) + .build(); + + functionProvider.register("myFunction", myFunction); + + // when + var result = feelRule.evaluateExpression("myFunction(\"foo\", \"bar\", \"baz\")"); + + // then + assertThat(result).isNull(); + } + + @Test + public void shouldPassExplicitParamsAndVarargs() { + // given + CustomFunction customFunction = CustomFunction.create() + .enableVarargs() + .setParams("x", "y") + .setFunction(args -> args) + .build(); + + functionProvider.register("myFunction", customFunction); + + // when + List result = feelRule.evaluateExpression("myFunction(\"foo\", \"bar\", \"baz\")"); + + // then + assertThat(result).containsExactly("foo", Arrays.asList("bar", "baz")); + } + + @Test + public void shouldPassExplicitParamsWithVarargsEnabled() { + // given + CustomFunction customFunction = CustomFunction.create() + .enableVarargs() + .setParams("x", "y") + .setFunction(args -> args) + .build(); + + functionProvider.register("myFunction", customFunction); + + // when + List result = feelRule.evaluateExpression("myFunction(y: \"bar\", x: \"foo\")"); + + // then + assertThat(result).containsExactly("foo", "bar"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/ExternalFunctionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/ExternalFunctionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..520b1193121805e5520ab20e18b108dc60cc4b49 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/ExternalFunctionTest.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.engine.feel.function; + +import org.camunda.bpm.dmn.engine.feel.helper.FeelRule; +import org.camunda.bpm.dmn.feel.impl.FeelException; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.RuleChain; + +public class ExternalFunctionTest { + + protected FeelRule feelRule = FeelRule.build(); + protected ExpectedException thrown = ExpectedException.none(); + + @Rule + public RuleChain ruleChain = RuleChain.outerRule(feelRule).around(thrown); + + @Test + public void shouldFailWhenUsingExternalFunction() { + // given + + // then + thrown.expect(FeelException.class); + thrown.expectMessage("External functions are disabled"); + + // when + feelRule.evaluateExpression("{ \n" + + " foo: function(x, y) external { \n" + + " java: { \n" + + " class: \"java.lang.Math\", \n" + + " method signature: \"addExact(int, int)\" \n" + + " } \n" + + " },\n" + + " bar: foo(5, 5)\n" + + "}.bar"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/helper/FunctionProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/helper/FunctionProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..536c13d8fee0bddda982d4a6aea5cc572b8b25fa --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/helper/FunctionProvider.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.engine.feel.function.helper; + +import org.camunda.bpm.dmn.feel.impl.scala.function.CustomFunction; +import org.camunda.bpm.dmn.feel.impl.scala.function.FeelCustomFunctionProvider; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class FunctionProvider implements FeelCustomFunctionProvider { + + protected Map functions = new HashMap<>(); + + public FunctionProvider() { + } + + @Override + public Optional resolveFunction(String functionName) { + return Optional.ofNullable(functions.get(functionName)); + } + + @Override + public Collection getFunctionNames() { + return functions.keySet(); + } + + public void clear() { + functions.clear(); + } + + public void register(String functionName, CustomFunction function) { + functions.put(functionName, function); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/helper/MyPojo.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/helper/MyPojo.java new file mode 100644 index 0000000000000000000000000000000000000000..e88d6beee7d69a7e40703bc9a286e80fa6a461ff --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/function/helper/MyPojo.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.engine.feel.function.helper; + +public class MyPojo { + + protected final int factor; + + public MyPojo(int factor) { + this.factor = factor; + } + + public int call(int number) { + return number * factor; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/helper/FeelRule.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/helper/FeelRule.java new file mode 100644 index 0000000000000000000000000000000000000000..c9a14d78ce56b3455245406f28cdefebe856a571 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/java/org/camunda/bpm/dmn/engine/feel/helper/FeelRule.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.dmn.engine.feel.helper; + +import org.camunda.bpm.dmn.engine.feel.function.helper.FunctionProvider; +import org.camunda.bpm.dmn.feel.impl.scala.ScalaFeelEngine; +import org.camunda.bpm.dmn.feel.impl.scala.function.FeelCustomFunctionProvider; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.context.VariableContext; +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; + +import java.util.Collections; +import java.util.List; + +public class FeelRule extends TestWatcher { + + protected FunctionProvider functionProvider; + protected ScalaFeelEngine feelEngine; + + protected FeelRule(FunctionProvider functionProvider) { + this.functionProvider = functionProvider; + } + + protected FeelRule() { + feelEngine = new ScalaFeelEngine(null); + } + + public static FeelRule buildWithFunctionProvider() { + FunctionProvider functionProvider = new FunctionProvider(); + return new FeelRule(functionProvider); + } + + public static FeelRule build() { + return new FeelRule(); + } + + @Override + protected void finished(Description description) { + super.finished(description); + + if (functionProvider != null) { + functionProvider.clear(); + } + } + + public T evaluateExpression(String expression) { + return evaluateExpression(expression, null); + } + + public T evaluateExpression(String expression, Object value) { + if (functionProvider != null) { + List functionProviders = + Collections.singletonList(functionProvider); + + feelEngine = new ScalaFeelEngine(functionProviders); + } + + VariableContext variableCtx = Variables.putValue("variable", value).asVariableContext(); + return feelEngine.evaluateSimpleExpression(expression, variableCtx); + } + + public FunctionProvider getFunctionProvider() { + return functionProvider; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/resources/logback-test.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/resources/logback-test.xml new file mode 100644 index 0000000000000000000000000000000000000000..aa7e0c35ec8761bf2c87a6012c20443aabdf1be0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/feel-scala/src/test/resources/logback-test.xml @@ -0,0 +1,17 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..d2da3cad894db492f723794ed1f2115eca498b62 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-dmn/pom.xml @@ -0,0 +1,67 @@ + + 4.0.0 + + + org.camunda.bpm + camunda-database-settings + ../database + 7.24.0-SNAPSHOT + + + org.camunda.bpm.dmn + camunda-engine-dmn-root + camunda DMN - engine - root + 2015 + pom + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + 2.2.7 + + + + + + + org.camunda.bpm + camunda-core-internal-dependencies + ${project.version} + import + pom + + + + + + bom + engine + feel-api + feel-juel + feel-scala + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + + org.apache.felix + maven-bundle-plugin + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..92c33b7e1f59bb4627ab67468920a59ef9bac653 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/pom.xml @@ -0,0 +1,80 @@ + + + + + camunda-engine-plugins + org.camunda.bpm + 7.24.0-SNAPSHOT + + 4.0.0 + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + camunda-engine-plugin-connect + Camunda Platform - engine plugins - connect + + + + + org.camunda.connect + camunda-connect-core + + + + org.camunda.connect + camunda-connect-http-client + test + + + + org.camunda.connect + camunda-connect-soap-http-client + test + + + + org.assertj + assertj-core + test + + + + ch.qos.logback + logback-classic + test + + + + org.slf4j + jcl-over-slf4j + test + + + + org.slf4j + jul-to-slf4j + test + + + + org.apache.groovy + groovy-jsr223 + test + + + + + + + + maven-surefire-plugin + + true + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectProcessEnginePlugin.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectProcessEnginePlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..01f584511cfaa5e95c27c5fdd38da5c81540bd89 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectProcessEnginePlugin.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseListener; +import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.util.ClassLoaderUtil; +import org.camunda.connect.Connectors; + +public class ConnectProcessEnginePlugin extends AbstractProcessEnginePlugin { + + @Override + public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { + // use classloader which loaded the plugin + ClassLoader classloader = ClassLoaderUtil.getClassloader(ConnectProcessEnginePlugin.class); + Connectors.loadConnectors(classloader); + + addConnectorParseListener(processEngineConfiguration); + } + + private void addConnectorParseListener(ProcessEngineConfigurationImpl processEngineConfiguration) { + List preParseListeners = processEngineConfiguration.getCustomPreBPMNParseListeners(); + if(preParseListeners == null) { + preParseListeners = new ArrayList(); + processEngineConfiguration.setCustomPreBPMNParseListeners(preParseListeners); + } + preParseListeners.add(new ConnectorParseListener()); + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectorParseListener.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectorParseListener.java new file mode 100644 index 0000000000000000000000000000000000000000..6af33ce9fd7cbed4d617dbcc34e0f72bc7c69e55 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectorParseListener.java @@ -0,0 +1,83 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.impl; + +import static org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseUtil.findCamundaExtensionElement; +import static org.camunda.bpm.engine.impl.bpmn.parser.BpmnParseUtil.parseInputOutput; + +import org.camunda.bpm.engine.BpmnParseException; +import org.camunda.bpm.engine.impl.bpmn.parser.AbstractBpmnParseListener; +import org.camunda.bpm.engine.impl.bpmn.parser.BpmnParse; +import org.camunda.bpm.engine.impl.core.variable.mapping.IoMapping; +import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl; +import org.camunda.bpm.engine.impl.pvm.process.ScopeImpl; +import org.camunda.bpm.engine.impl.util.xml.Element; + +public class ConnectorParseListener extends AbstractBpmnParseListener { + + @Override + public void parseServiceTask(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) { + parseConnectorElement(serviceTaskElement, scope, activity); + } + + @Override + public void parseEndEvent(Element endEventElement, ScopeImpl scope, ActivityImpl activity) { + Element messageEventDefinitionElement = endEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION); + + if (messageEventDefinitionElement != null) { + parseConnectorElement(messageEventDefinitionElement, scope, activity); + } + } + + @Override + public void parseIntermediateThrowEvent(Element intermediateEventElement, ScopeImpl scope, ActivityImpl activity) { + Element messageEventDefinitionElement = intermediateEventElement.element(BpmnParse.MESSAGE_EVENT_DEFINITION); + + if (messageEventDefinitionElement != null) { + parseConnectorElement(messageEventDefinitionElement, scope, activity); + } + } + + @Override + public void parseBusinessRuleTask(Element businessRuleTaskElement, ScopeImpl scope, ActivityImpl activity) { + parseConnectorElement(businessRuleTaskElement, scope, activity); + } + + @Override + public void parseSendTask(Element sendTaskElement, ScopeImpl scope, ActivityImpl activity) { + parseConnectorElement(sendTaskElement, scope, activity); + } + + protected void parseConnectorElement(Element serviceTaskElement, ScopeImpl scope, ActivityImpl activity) { + Element connectorDefinition = findCamundaExtensionElement(serviceTaskElement, "connector"); + if (connectorDefinition != null) { + Element connectorIdElement = connectorDefinition.element("connectorId"); + + String connectorId = null; + if (connectorIdElement != null) { + connectorId = connectorIdElement.getText().trim(); + } + if (connectorIdElement == null || connectorId.isEmpty()) { + throw new BpmnParseException("No 'id' defined for connector.", connectorDefinition); + } + + IoMapping ioMapping = parseInputOutput(connectorDefinition); + activity.setActivityBehavior(new ServiceTaskConnectorActivityBehavior(connectorId, ioMapping)); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectorVariableScope.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectorVariableScope.java new file mode 100644 index 0000000000000000000000000000000000000000..2b9003e1d196ed4330ac44eedcafc627e555dcd1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ConnectorVariableScope.java @@ -0,0 +1,88 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.impl; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.camunda.bpm.engine.impl.core.variable.CoreVariableInstance; +import org.camunda.bpm.engine.impl.core.variable.scope.AbstractVariableScope; +import org.camunda.bpm.engine.impl.core.variable.scope.SimpleVariableInstance; +import org.camunda.bpm.engine.impl.core.variable.scope.SimpleVariableInstance.SimpleVariableInstanceFactory; +import org.camunda.bpm.engine.impl.core.variable.scope.VariableInstanceFactory; +import org.camunda.bpm.engine.impl.core.variable.scope.VariableInstanceLifecycleListener; +import org.camunda.bpm.engine.impl.core.variable.scope.VariableStore; +import org.camunda.connect.spi.ConnectorRequest; +import org.camunda.connect.spi.ConnectorResponse; + +/** + * Exposes a connector request as variableScope. + * + * @author Daniel Meyer + * + */ +public class ConnectorVariableScope extends AbstractVariableScope { + + private static final long serialVersionUID = 1L; + + protected AbstractVariableScope parent; + + protected VariableStore variableStore; + + public ConnectorVariableScope(AbstractVariableScope parent) { + this.parent = parent; + this.variableStore = new VariableStore(); + } + + public String getVariableScopeKey() { + return "connector"; + } + + protected VariableStore getVariableStore() { + return (VariableStore) variableStore; + } + + @Override + protected VariableInstanceFactory getVariableInstanceFactory() { + return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; + } + + @Override + protected List> getVariableInstanceLifecycleListeners() { + return Collections.emptyList(); + } + + public AbstractVariableScope getParentVariableScope() { + return parent; + } + + public void writeToRequest(ConnectorRequest request) { + for (CoreVariableInstance variable : variableStore.getVariables()) { + request.setRequestParameter(variable.getName(), variable.getTypedValue(true).getValue()); + } + } + + public void readFromResponse(ConnectorResponse response) { + Map responseParameters = response.getResponseParameters(); + for (Entry entry : responseParameters.entrySet()) { + setVariableLocal(entry.getKey(), entry.getValue()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ServiceTaskConnectorActivityBehavior.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ServiceTaskConnectorActivityBehavior.java new file mode 100644 index 0000000000000000000000000000000000000000..67c8659dfb0a5ae8d89f89214f23d3f714306070 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/main/java/org/camunda/connect/plugin/impl/ServiceTaskConnectorActivityBehavior.java @@ -0,0 +1,105 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.impl; + +import java.util.concurrent.Callable; + +import org.camunda.bpm.engine.impl.bpmn.behavior.TaskActivityBehavior; +import org.camunda.bpm.engine.impl.core.variable.mapping.IoMapping; +import org.camunda.bpm.engine.impl.core.variable.scope.AbstractVariableScope; +import org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution; +import org.camunda.connect.ConnectorException; +import org.camunda.connect.Connectors; +import org.camunda.connect.spi.Connector; +import org.camunda.connect.spi.ConnectorRequest; +import org.camunda.connect.spi.ConnectorResponse; + +/** + * @author Daniel Meyer + * + */ +public class ServiceTaskConnectorActivityBehavior extends TaskActivityBehavior { + + /** the id of the connector */ + protected String connectorId; + + /** cached connector instance for this activity. + * Will be initialized after the first execution of this activity. */ + protected Connector connectorInstance; + + /** the local ioMapping for this connector. */ + protected IoMapping ioMapping; + + public ServiceTaskConnectorActivityBehavior(String connectorId, IoMapping ioMapping) { + this.connectorId = connectorId; + this.ioMapping = ioMapping; + } + + public void execute(final ActivityExecution execution) throws Exception { + ensureConnectorInitialized(); + + executeWithErrorPropagation(execution, new Callable() { + @Override + public Void call() throws Exception { + ConnectorRequest request = connectorInstance.createRequest(); + applyInputParameters(execution, request); + // execute the request and obtain a response: + ConnectorResponse response = request.execute(); + applyOutputParameters(execution, response); + leave(execution); + return null; + } + }); + + } + + protected void applyInputParameters(ActivityExecution execution, ConnectorRequest request) { + if(ioMapping != null) { + // create variable scope for input parameters + ConnectorVariableScope connectorInputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution); + // execute the connector input parameters + ioMapping.executeInputParameters(connectorInputVariableScope); + // write the local variables to the request. + connectorInputVariableScope.writeToRequest(request); + } + } + + protected void applyOutputParameters(ActivityExecution execution, ConnectorResponse response) { + if(ioMapping != null) { + // create variable scope for output parameters + ConnectorVariableScope connectorOutputVariableScope = new ConnectorVariableScope((AbstractVariableScope) execution); + // read parameters from response + connectorOutputVariableScope.readFromResponse(response); + // map variables to parent scope. + ioMapping.executeOutputParameters(connectorOutputVariableScope); + } + } + + protected void ensureConnectorInitialized() { + if(connectorInstance == null) { + synchronized (this) { + if(connectorInstance == null) { + connectorInstance = Connectors.getConnector(connectorId); + if (connectorInstance == null) { + throw new ConnectorException("No connector found for connector id '" + connectorId + "'"); + } + } + } + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1d156058eb1fbed335b76fbb0fb86b08d272db81 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.java @@ -0,0 +1,325 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.BpmnParseException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.delegate.BpmnError; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.connect.ConnectorException; +import org.camunda.connect.Connectors; +import org.camunda.connect.httpclient.HttpConnector; +import org.camunda.connect.httpclient.soap.SoapHttpConnector; +import org.camunda.connect.plugin.util.TestConnector; +import org.camunda.connect.spi.Connector; + +public class ConnectProcessEnginePluginTest extends PluggableProcessEngineTestCase { + + @Override + protected void setUp() throws Exception { + super.setUp(); + TestConnector.responseParameters.clear(); + TestConnector.requestParameters = null; + } + + public void testConnectorsRegistered() { + Connector http = Connectors.getConnector(HttpConnector.ID); + assertNotNull(http); + Connector soap = Connectors.getConnector(SoapHttpConnector.ID); + assertNotNull(soap); + Connector test = Connectors.getConnector(TestConnector.ID); + assertNotNull(test); + } + + public void testConnectorIdMissing() { + try { + repositoryService.createDeployment().addClasspathResource("org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorIdMissing.bpmn") + .deploy(); + fail("Exception expected"); + } + catch (ProcessEngineException e) { + assertFalse(e instanceof BpmnParseException); + } + } + + @Deployment + public void testConnectorIdUnknown() { + try { + runtimeService.startProcessInstanceByKey("testProcess"); + fail("Exception expected"); + } + catch (ConnectorException e) { + // expected + } + } + + @Deployment + public void testConnectorInvoked() { + String outputParamValue = "someOutputValue"; + String inputVariableValue = "someInputVariableValue"; + + TestConnector.responseParameters.put("someOutputParameter", outputParamValue); + + Map vars = new HashMap(); + vars.put("someInputVariable", inputVariableValue); + runtimeService.startProcessInstanceByKey("testProcess", vars); + + // validate input parameter + assertNotNull(TestConnector.requestParameters.get("reqParam1")); + assertEquals(inputVariableValue, TestConnector.requestParameters.get("reqParam1")); + + // validate connector output + VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("out1").singleResult(); + assertNotNull(variable); + assertEquals(outputParamValue, variable.getValue()); + } + + @Deployment + public void testConnectorWithScriptInputOutputMapping() { + int x = 3; + Map variables = new HashMap(); + variables.put("x", x); + runtimeService.startProcessInstanceByKey("testProcess", variables); + + // validate input parameter + Object in = TestConnector.requestParameters.get("in"); + assertNotNull(in); + assertEquals(2 * x, in); + + // validate output parameter + VariableInstance out = runtimeService.createVariableInstanceQuery().variableName("out").singleResult(); + assertNotNull(out); + assertEquals(3 * x, out.getValue()); + } + + + @Deployment + public void testConnectorWithSetVariableInOutputMapping() { + // given process with set variable on connector in output mapping + + // when start process + runtimeService.startProcessInstanceByKey("testProcess"); + + // then variable x is set and no exception is thrown + VariableInstance out = runtimeService.createVariableInstanceQuery().variableName("x").singleResult(); + assertEquals(1, out.getValue()); + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptInputOutputMapping.bpmn") + public void testConnectorBpmnErrorThrownInScriptInputMappingIsHandledByBoundaryEvent() { + Map variables = new HashMap(); + variables.put("throwInMapping", "in"); + variables.put("exception", new BpmnError("error")); + runtimeService.startProcessInstanceByKey("testProcess", variables); + //we will only reach the user task if the BPMNError from the script was handled by the boundary event + Task task = taskService.createTaskQuery().singleResult(); + assertThat(task.getName(), is("User Task")); + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptInputOutputMapping.bpmn") + public void testConnectorRuntimeExceptionThrownInScriptInputMappingIsNotHandledByBoundaryEvent() { + String exceptionMessage = "myException"; + Map variables = new HashMap(); + variables.put("throwInMapping", "in"); + variables.put("exception", new RuntimeException(exceptionMessage)); + try { + runtimeService.startProcessInstanceByKey("testProcess", variables); + } catch(RuntimeException re){ + assertThat(re.getMessage(), containsString(exceptionMessage)); + } + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptInputOutputMapping.bpmn") + public void testConnectorBpmnErrorThrownInScriptOutputMappingIsHandledByBoundaryEvent() { + Map variables = new HashMap(); + variables.put("throwInMapping", "out"); + variables.put("exception", new BpmnError("error")); + runtimeService.startProcessInstanceByKey("testProcess", variables); + //we will only reach the user task if the BPMNError from the script was handled by the boundary event + Task task = taskService.createTaskQuery().singleResult(); + assertThat(task.getName(), is("User Task")); + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptInputOutputMapping.bpmn") + public void testConnectorRuntimeExceptionThrownInScriptOutputMappingIsNotHandledByBoundaryEvent() { + String exceptionMessage = "myException"; + Map variables = new HashMap(); + variables.put("throwInMapping", "out"); + variables.put("exception", new RuntimeException(exceptionMessage)); + try { + runtimeService.startProcessInstanceByKey("testProcess", variables); + } catch(RuntimeException re){ + assertThat(re.getMessage(), containsString(exceptionMessage)); + } + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptResourceInputOutputMapping.bpmn") + public void testConnectorBpmnErrorThrownInScriptResourceInputMappingIsHandledByBoundaryEvent() { + Map variables = new HashMap(); + variables.put("throwInMapping", "in"); + variables.put("exception", new BpmnError("error")); + runtimeService.startProcessInstanceByKey("testProcess", variables); + //we will only reach the user task if the BPMNError from the script was handled by the boundary event + Task task = taskService.createTaskQuery().singleResult(); + assertThat(task.getName(), is("User Task")); + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptResourceInputOutputMapping.bpmn") + public void testConnectorRuntimeExceptionThrownInScriptResourceInputMappingIsNotHandledByBoundaryEvent() { + String exceptionMessage = "myException"; + Map variables = new HashMap(); + variables.put("throwInMapping", "in"); + variables.put("exception", new RuntimeException(exceptionMessage)); + try { + runtimeService.startProcessInstanceByKey("testProcess", variables); + } catch(RuntimeException re){ + assertThat(re.getMessage(), containsString(exceptionMessage)); + } + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptResourceInputOutputMapping.bpmn") + public void testConnectorBpmnErrorThrownInScriptResourceOutputMappingIsHandledByBoundaryEvent() { + Map variables = new HashMap(); + variables.put("throwInMapping", "out"); + variables.put("exception", new BpmnError("error")); + runtimeService.startProcessInstanceByKey("testProcess", variables); + //we will only reach the user task if the BPMNError from the script was handled by the boundary event + Task task = taskService.createTaskQuery().singleResult(); + assertThat(task.getName(), is("User Task")); + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptResourceInputOutputMapping.bpmn") + public void testConnectorRuntimeExceptionThrownInScriptResourceOutputMappingIsNotHandledByBoundaryEvent() { + String exceptionMessage = "myException"; + Map variables = new HashMap(); + variables.put("throwInMapping", "out"); + variables.put("exception", new RuntimeException(exceptionMessage)); + try { + runtimeService.startProcessInstanceByKey("testProcess", variables); + } catch(RuntimeException re){ + assertThat(re.getMessage(), containsString(exceptionMessage)); + } + } + + @Deployment(resources="org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorBpmnErrorThrownInScriptResourceNoAsyncAfterJobIsCreated.bpmn") + public void testConnectorBpmnErrorThrownInScriptResourceNoAsyncAfterJobIsCreated() { + // given + Map variables = new HashMap(); + variables.put("throwInMapping", "in"); + variables.put("exception", new BpmnError("error")); + + // when + runtimeService.startProcessInstanceByKey("testProcess", variables); + + // then + // we will only reach the user task if the BPMNError from the script was handled by the boundary event + Task task = taskService.createTaskQuery().singleResult(); + assertThat(task.getName(), is("User Task")); + + // no job is created + assertThat(managementService.createJobQuery().count(), is(0l)); + } + + @Deployment + public void testFollowingExceptionIsNotHandledByConnector(){ + try { + runtimeService.startProcessInstanceByKey("testProcess"); + } catch(RuntimeException re){ + assertThat(re.getMessage(), containsString("Invalid format")); + } + } + + @Deployment + public void testSendTaskWithConnector() { + String outputParamValue = "someSendTaskOutputValue"; + String inputVariableValue = "someSendTaskInputVariableValue"; + + TestConnector.responseParameters.put("someOutputParameter", outputParamValue); + + Map vars = new HashMap(); + vars.put("someInputVariable", inputVariableValue); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("process_sending_with_connector", vars); + + // validate input parameter + assertNotNull(TestConnector.requestParameters.get("reqParam1")); + assertEquals(inputVariableValue, TestConnector.requestParameters.get("reqParam1")); + + // validate connector output + VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("out1").singleResult(); + assertNotNull(variable); + assertEquals(outputParamValue, variable.getValue()); + } + + @Deployment + public void testIntermediateMessageThrowEventWithConnector() { + String outputParamValue = "someMessageThrowOutputValue"; + String inputVariableValue = "someMessageThrowInputVariableValue"; + + TestConnector.responseParameters.put("someOutputParameter", outputParamValue); + + Map vars = new HashMap(); + vars.put("someInputVariable", inputVariableValue); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("process_sending_with_connector", vars); + + // validate input parameter + assertNotNull(TestConnector.requestParameters.get("reqParam1")); + assertEquals(inputVariableValue, TestConnector.requestParameters.get("reqParam1")); + + // validate connector output + VariableInstance variable = runtimeService.createVariableInstanceQuery().variableName("out1").singleResult(); + assertNotNull(variable); + assertEquals(outputParamValue, variable.getValue()); + } + + @Deployment + public void testMessageEndEventWithConnector() { + String outputParamValue = "someMessageEndOutputValue"; + String inputVariableValue = "someMessageEndInputVariableValue"; + + TestConnector.responseParameters.put("someOutputParameter", outputParamValue); + + Map vars = new HashMap(); + vars.put("someInputVariable", inputVariableValue); + ProcessInstance processInstance = runtimeService + .startProcessInstanceByKey("process_sending_with_connector", vars); + assertProcessEnded(processInstance.getId()); + + // validate input parameter + assertNotNull(TestConnector.requestParameters.get("reqParam1")); + assertEquals(inputVariableValue, TestConnector.requestParameters.get("reqParam1")); + + // validate connector output + HistoricVariableInstance variable = historyService.createHistoricVariableInstanceQuery().variableName("out1").singleResult(); + assertNotNull(variable); + assertEquals(outputParamValue, variable.getValue()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/MockHttpConnectorConfigurator.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/MockHttpConnectorConfigurator.java new file mode 100644 index 0000000000000000000000000000000000000000..25aab021f041295789a44936a69b3b19fc65e355 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/MockHttpConnectorConfigurator.java @@ -0,0 +1,84 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin; + +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.io.entity.StringEntity; +import org.apache.hc.core5.http.message.BasicHttpResponse; +import org.camunda.connect.httpclient.HttpConnector; +import org.camunda.connect.httpclient.impl.HttpResponseImpl; +import org.camunda.connect.spi.ConnectorConfigurator; +import org.camunda.connect.spi.ConnectorInvocation; +import org.camunda.connect.spi.ConnectorRequestInterceptor; + +/** + * @author Daniel Meyer + * + */ +public class MockHttpConnectorConfigurator implements ConnectorConfigurator { + + public void configure(HttpConnector connecor) { + connecor.addRequestInterceptor(new ConnectorRequestInterceptor() { + + public Object handleInvocation(ConnectorInvocation invocation) throws Exception { + + // intercept the call. => do not call invocation.proceed() + + // Could do validation on the invocation here: + // invocation.getRequest() .... + + // build response using http client api... + TestHttpResonse testHttpResonse = new TestHttpResonse(); + testHttpResonse.setEntity(new StringEntity("{...}", ContentType.APPLICATION_JSON)); + + // return the response + return new HttpResponseImpl(testHttpResonse); + } + }); + } + + public Class getConnectorClass() { + return HttpConnector.class; + } + + static class TestHttpResonse extends BasicHttpResponse implements ClassicHttpResponse { + + private HttpEntity entity; + + public TestHttpResonse() { + super(200, "OK"); + } + + @Override + public HttpEntity getEntity() { + return entity; + } + + @Override + public void setEntity(HttpEntity entity) { + this.entity = entity; + } + + @Override + public void close() { + /* NOP */ + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnector.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnector.java new file mode 100644 index 0000000000000000000000000000000000000000..0b3601061f61cc8f6efeac949b3ef440b1903cec --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnector.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.util; + +import java.lang.Exception;import java.lang.Object;import java.lang.RuntimeException;import java.lang.String;import java.util.HashMap; +import java.util.Map; + +import org.camunda.connect.impl.AbstractConnector; + +/** + * @author Daniel Meyer + * + */ +public class TestConnector extends AbstractConnector { + + public static final String ID = "testConnector"; + + public static Map requestParameters; + public static Map responseParameters = new HashMap(); + + public TestConnector(String connectorId) { + super(connectorId); + } + + public TestConnectorRequest createRequest() { + return new TestConnectorRequest(this); + } + + public TestConnectorResponse execute(TestConnectorRequest req) { + // capture request parameters + requestParameters = req.getRequestParameters(); + + TestRequestInvocation testRequestInvocation = new TestRequestInvocation(null, req, requestInterceptors); + + try { + testRequestInvocation.proceed(); + // use response parameters + return new TestConnectorResponse(responseParameters); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..aa5bfe53ee6c405a3e87ad2bcef39bcab5076857 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.util; + +import org.camunda.connect.spi.Connector; +import org.camunda.connect.spi.ConnectorProvider; + +public class TestConnectorProvider implements ConnectorProvider { + + public String getConnectorId() { + return TestConnector.ID; + } + + public Connector createConnectorInstance() { + return new TestConnector(TestConnector.ID); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorRequest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..c0324cf7057fecda0e5566f85035888a6f904931 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorRequest.java @@ -0,0 +1,32 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.util; + +import org.camunda.connect.impl.AbstractConnector; +import org.camunda.connect.impl.AbstractConnectorRequest; + +/** + * @author Daniel Meyer + * + */ +public class TestConnectorRequest extends AbstractConnectorRequest { + + public TestConnectorRequest(AbstractConnector connector) { + super(connector); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorResponse.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorResponse.java new file mode 100644 index 0000000000000000000000000000000000000000..1a60c345395932f6e3a97bbc3ebace1a1867e202 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestConnectorResponse.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.util; + +import java.util.Map; + +import org.camunda.connect.impl.AbstractConnectorResponse; + + +/** + * @author Daniel Meyer + * + */ +public class TestConnectorResponse extends AbstractConnectorResponse { + + private Map responseParameters; + + public TestConnectorResponse(Map responseParameters) { + this.responseParameters = responseParameters; + } + + protected void collectResponseParameters(Map arg0) { + if(responseParameters != null) { + arg0.putAll(responseParameters); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestRequestInvocation.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestRequestInvocation.java new file mode 100644 index 0000000000000000000000000000000000000000..b9e252fe2bb67797c4f480fbe0523f364d2fd442 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/java/org/camunda/connect/plugin/util/TestRequestInvocation.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.connect.plugin.util; + +import java.util.List; + +import org.camunda.connect.impl.AbstractRequestInvocation; +import org.camunda.connect.spi.ConnectorRequest; +import org.camunda.connect.spi.ConnectorRequestInterceptor; + +/** + * @author Daniel Meyer + * + */ +public class TestRequestInvocation extends AbstractRequestInvocation { + + public TestRequestInvocation(Object target, ConnectorRequest request, List interceptorChain) { + super(target, request, interceptorChain); + } + + public Object invokeTarget() throws Exception { + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/META-INF/services/org.camunda.connect.spi.ConnectorProvider b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/META-INF/services/org.camunda.connect.spi.ConnectorProvider new file mode 100644 index 0000000000000000000000000000000000000000..830b2e8d6970a2888ea22b649d2598b47f8cf749 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/META-INF/services/org.camunda.connect.spi.ConnectorProvider @@ -0,0 +1 @@ +org.camunda.connect.plugin.util.TestConnectorProvider diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/camunda.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/camunda.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..e71ac5f0276f1c1a6e5dff1338ae1240beb902cc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/camunda.cfg.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/logback-test.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/logback-test.xml new file mode 100644 index 0000000000000000000000000000000000000000..8f7abe1d379f5f4793868ee77ba3522c5bfe08f3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/logback-test.xml @@ -0,0 +1,27 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/logging.properties b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/logging.properties new file mode 100644 index 0000000000000000000000000000000000000000..4941c55971f365781be2c0903a6f00af84a1a74f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/logging.properties @@ -0,0 +1,2 @@ +#register SLF4JBridgeHandler as handler for the j.u.l. root logger +handlers = org.slf4j.bridge.SLF4JBridgeHandler diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorBpmnErrorThrownInScriptResourceNoAsyncAfterJobIsCreated.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorBpmnErrorThrownInScriptResourceNoAsyncAfterJobIsCreated.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..0830f2aed0cb567fe0e4efe4644d4f8aed9bd16f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorBpmnErrorThrownInScriptResourceNoAsyncAfterJobIsCreated.bpmn @@ -0,0 +1,47 @@ + + + + + + + + + testConnector + + + + if (throwInMapping == 'in') { + throw exception + } + + + + + if (throwInMapping == 'out') { + throw exception + } + + + + + + + + SequenceFlow_3 + + + + + SequenceFlow_3 + SequenceFlow_4 + + + SequenceFlow_4 + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorIdMissing.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorIdMissing.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..dc9c007e42538b581500ebb9a8907142a8420bd9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorIdMissing.bpmn @@ -0,0 +1,19 @@ + + + + + + + + + + ${someInputVariable} + ${someOutputParameter} + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorIdUnknown.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorIdUnknown.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..14a74df491d4a200b80359224e7796d307fa725f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorIdUnknown.bpmn @@ -0,0 +1,20 @@ + + + + + + + + + unknownConnector + + ${someInputVariable} + ${someOutputParameter} + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorInvoked.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorInvoked.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..2caf20be1d001e98c8dd5c3bddb87cbc34ee26ba --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorInvoked.bpmn @@ -0,0 +1,22 @@ + + + + + + + + + testConnector + + ${someInputVariable} + ${someOutputParameter} + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithScriptInputOutputMapping.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithScriptInputOutputMapping.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..57c2d576a006d82934ed0d8dbf4083e9c77bfdff --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithScriptInputOutputMapping.bpmn @@ -0,0 +1,34 @@ + + + + + + + + + testConnector + + + + // test if execution is available + y = execution.getVariable('x') + y + y + + + + + // test if connector is available + y = connector.getVariable('x') + y + y + y + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithSetVariableInOutputMapping.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithSetVariableInOutputMapping.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..48577f6256d57616c8243638aba2ce367aa67d1d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithSetVariableInOutputMapping.bpmn @@ -0,0 +1,27 @@ + + + + + + + + + testConnector + + + + // test if connector is available + y = 1 + connector.setVariable('x', y) + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptInputOutputMapping.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptInputOutputMapping.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..7efe805f9511f08407900e4991ac2863172651f5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptInputOutputMapping.bpmn @@ -0,0 +1,47 @@ + + + + + + + + + testConnector + + + + if (throwInMapping == 'in') { + throw exception + } + + + + + if (throwInMapping == 'out') { + throw exception + } + + + + + + + + SequenceFlow_3 + + + + + SequenceFlow_3 + SequenceFlow_4 + + + SequenceFlow_4 + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptResourceInputOutputMapping.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptResourceInputOutputMapping.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..c2dcdf6f9052b092af22b03a5e434be70dc72c7b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testConnectorWithThrownExceptionInScriptResourceInputOutputMapping.bpmn @@ -0,0 +1,39 @@ + + + + + + + + + testConnector + + + + + + + + + + + + + SequenceFlow_3 + + + + + SequenceFlow_3 + SequenceFlow_4 + + + SequenceFlow_4 + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testFollowingExceptionIsNotHandledByConnector.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testFollowingExceptionIsNotHandledByConnector.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..8e80b17e9c1333f95adfbd6547a6637fc331949b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testFollowingExceptionIsNotHandledByConnector.bpmn @@ -0,0 +1,23 @@ + + + + + + + + + testConnector + + + + + + + + time is just a concept + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testIntermediateMessageThrowEventWithConnector.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testIntermediateMessageThrowEventWithConnector.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..b166387df2ad397d3c4312b45b2c4b221ba79c00 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testIntermediateMessageThrowEventWithConnector.bpmn @@ -0,0 +1,80 @@ + + + + + SequenceFlow_1iyn727 + + + + + SequenceFlow_1iyn727 + SequenceFlow_0w8fzse + + + + + ${someInputVariable} + ${someOutputParameter} + + testConnector + + + + + + SequenceFlow_0im2omf + + + + + SequenceFlow_0w8fzse + SequenceFlow_0im2omf + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testMessageEndEventWithConnector.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testMessageEndEventWithConnector.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..9f2730ca81c820829e4d3fc88a5fef6ac4032e5c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testMessageEndEventWithConnector.bpmn @@ -0,0 +1,47 @@ + + + + + SequenceFlow_1lzfh2c + + + + + SequenceFlow_1lzfh2c + + + + + ${someInputVariable} + ${someOutputParameter} + + testConnector + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testSendTaskWithConnector.bpmn b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testSendTaskWithConnector.bpmn new file mode 100644 index 0000000000000000000000000000000000000000..1d754648356648cbdd9dc308d54c7f551748aaeb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.testSendTaskWithConnector.bpmn @@ -0,0 +1,71 @@ + + + + + SequenceFlow_02p0m3b + + + + + + + ${someInputVariable} + ${someOutputParameter} + + testConnector + + + SequenceFlow_02p0m3b + SequenceFlow_0e4gcph + + + SequenceFlow_0wc0nkt + + + + + SequenceFlow_0e4gcph + SequenceFlow_0wc0nkt + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.throwError.groovy b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.throwError.groovy new file mode 100644 index 0000000000000000000000000000000000000000..6e8c320a1ac020d3e5fa4187f32be6d35f292fdc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/connect-plugin/src/test/resources/org/camunda/connect/plugin/ConnectProcessEnginePluginTest.throwError.groovy @@ -0,0 +1,17 @@ +// helper +def isInputMapping() { + binding.variables.containsKey('execution') +} + +def isOutputMapping() { + binding.variables.containsKey('connector') +} + +// logic +if (isInputMapping() && throwInMapping == 'in') { + throw exception +} + +if (isOutputMapping() != null && throwInMapping == 'out') { + throw exception +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..b5e983a5786c91895904b16e335d581940ffd301 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + + org.camunda.bpm.identity + camunda-identity-ldap + jar + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + Camunda Platform - engine plugins - identity - ldap + + + org.camunda.bpm + camunda-engine-plugins + 7.24.0-SNAPSHOT + + + + 10389 + 5027 + + + + + org.camunda.commons + camunda-commons-logging + + + + + org.apache.directory.server + apacheds-all + + + org.apache.directory.shared + shared-ldap + + + test + + + + + commons-io + commons-io + test + + + + ch.qos.logback + logback-classic + test + + + + + + + src/test/resources + true + + + + + maven-surefire-plugin + + false + false + true + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapAuthenticationException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapAuthenticationException.java new file mode 100644 index 0000000000000000000000000000000000000000..f36e634d72c33d14214e6fc49f921ff27e194068 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapAuthenticationException.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import org.camunda.bpm.engine.impl.identity.IdentityProviderException; + +/** + * @author Daniel Meyer + * + */ +public class LdapAuthenticationException extends IdentityProviderException { + + private static final long serialVersionUID = 1L; + + public LdapAuthenticationException(String message, Throwable cause) { + super(message, cause); + } + + public LdapAuthenticationException(String message) { + super(message); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapClient.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapClient.java new file mode 100644 index 0000000000000000000000000000000000000000..f9a6c090bad0a5805a5b7bbfe08e4ea243521bd8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapClient.java @@ -0,0 +1,184 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import org.camunda.bpm.engine.impl.identity.IdentityProviderException; +import org.camunda.bpm.identity.impl.ldap.util.LdapPluginLogger; + +import javax.naming.AuthenticationException; +import javax.naming.Context; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.SearchResult; +import javax.naming.ldap.Control; +import javax.naming.ldap.InitialLdapContext; +import javax.naming.ldap.LdapContext; +import javax.naming.ldap.PagedResultsControl; +import javax.naming.ldap.SortControl; +import javax.naming.ldap.SortKey; +import java.io.IOException; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +/** + * This wrapper class should ensure that LDAP exceptions are wrapped as process engine exceptions + * to avoid that error details are disclosed in the REST API. + */ +public class LdapClient { + + protected LdapContext initialContext; + protected LdapConfiguration ldapConfiguration; + + public LdapClient(LdapConfiguration ldapConfiguration) { + this.ldapConfiguration = ldapConfiguration; + } + + protected void ensureContextInitialized() { + if (initialContext == null) { + initialContext = openContext(); + } + } + + public LdapContext openContext(String dn, String password) { + Hashtable env = new Hashtable<>(); + env.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfiguration.getInitialContextFactory()); + env.put(Context.SECURITY_AUTHENTICATION, ldapConfiguration.getSecurityAuthentication()); + env.put(Context.PROVIDER_URL, ldapConfiguration.getServerUrl()); + env.put(Context.SECURITY_PRINCIPAL, dn); + env.put(Context.SECURITY_CREDENTIALS, password); + + // for anonymous login + if (ldapConfiguration.isAllowAnonymousLogin() && password.isEmpty()) { + env.put(Context.SECURITY_AUTHENTICATION, "none"); + } + + if (ldapConfiguration.isUseSsl()) { + env.put(Context.SECURITY_PROTOCOL, "ssl"); + } + + // add additional properties + Map contextProperties = ldapConfiguration.getContextProperties(); + if (contextProperties != null) { + env.putAll(contextProperties); + } + + try { + return new InitialLdapContext(env, null); + + } catch (AuthenticationException e) { + throw new LdapAuthenticationException("Could not authenticate with LDAP server", e); + + } catch (NamingException e) { + throw new IdentityProviderException("Could not connect to LDAP server", e); + + } + } + + protected LdapContext openContext() { + return openContext(ldapConfiguration.getManagerDn(), ldapConfiguration.getManagerPassword()); + } + + protected void closeLdapCtx() { + closeLdapCtx(initialContext); + } + + protected void closeLdapCtx(LdapContext context) { + if (context != null) { + try { + context.close(); + } catch (NamingException e) { + // ignore + LdapPluginLogger.INSTANCE.exceptionWhenClosingLdapContext(e); + } + } + } + + public LdapSearchResults search(String baseDn, String searchFilter) { + try { + return new LdapSearchResults(initialContext.search(baseDn, searchFilter, ldapConfiguration.getSearchControls())); + } catch (NamingException e) { + throw new IdentityProviderException("LDAP search request failed.", e); + } + } + + public void setRequestControls(List listControls) { + try { + initialContext.setRequestControls(listControls.toArray(new Control[0])); + } catch (NamingException e) { + throw new IdentityProviderException("LDAP server failed to set request controls.", e); + } + } + + public Control[] getResponseControls() { + try { + return initialContext.getResponseControls(); + } catch (NamingException e) { + throw new IdentityProviderException("Error occurred while getting the response controls from the LDAP server.", e); + } + } + + public static void addPaginationControl(List listControls, byte[] cookie, Integer pageSize) { + try { + listControls.add(new PagedResultsControl(pageSize, cookie, Control.NONCRITICAL)); + } catch (IOException e) { + throw new IdentityProviderException("Pagination couldn't be enabled.", e); + } + } + + public static void addSortKey(SortKey sortKey, List controls) { + try { + controls.add(new SortControl(new SortKey[] { sortKey }, Control.CRITICAL)); + } catch (IOException e) { + throw new IdentityProviderException("Sorting couldn't be enabled.", e); + } + } + + protected static String getValue(String attrName, Attributes attributes) { + Attribute attribute = attributes.get(attrName); + if (attribute != null) { + try { + return (String) attribute.get(); + } catch (NamingException e) { + throw new IdentityProviderException("Error occurred while retrieving the value.", e); + } + } else { + return null; + } + } + + @SuppressWarnings("unchecked") + public static NamingEnumeration getAllMembers(String attributeId, LdapSearchResults searchResults) { + SearchResult result = searchResults.nextElement(); + Attributes attributes = result.getAttributes(); + if (attributes != null) { + Attribute memberAttribute = attributes.get(attributeId); + if (memberAttribute != null) { + try { + return (NamingEnumeration) memberAttribute.getAll(); + } catch (NamingException e) { + throw new IdentityProviderException("Value couldn't be retrieved.", e); + } + } + } + + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapConfiguration.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..edb2be7e60fcdb1e2ce18d4aeab5835a1900ca0d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapConfiguration.java @@ -0,0 +1,310 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + + +import java.util.HashMap; +import java.util.Map; +import javax.naming.directory.SearchControls; + + +/** + *

Java Bean holding LDAP configuration

+ * + * @author Daniel Meyer + * + */ +public class LdapConfiguration { + + public static String LDAP_QUERY_WILDCARD = "*"; + public static String DB_QUERY_WILDCARD = "%"; + + protected String initialContextFactory = "com.sun.jndi.ldap.LdapCtxFactory"; + protected String securityAuthentication = "simple"; + + protected Map contextProperties = new HashMap<>(); + + protected String serverUrl; + protected String managerDn = ""; + protected String managerPassword = ""; + + protected String baseDn = ""; + + protected String userDnPattern = ""; + + protected String userSearchBase = ""; + protected String userSearchFilter = "(objectclass=person)"; + + protected String groupSearchBase = ""; + protected String groupSearchFilter = "(objectclass=groupOfNames)"; + + protected String userIdAttribute = "uid"; + protected String userFirstnameAttribute = "cn"; + protected String userLastnameAttribute = "sn"; + protected String userEmailAttribute = "email"; + protected String userPasswordAttribute = "userpassword"; + + protected String groupIdAttribute = "ou"; + protected String groupNameAttribute = "cn"; + protected String groupTypeAttribute = ""; + protected String groupMemberAttribute = "memberOf"; + + protected boolean sortControlSupported = false; + protected boolean useSsl = false; + protected boolean usePosixGroups = false; + protected boolean allowAnonymousLogin = false; + + protected boolean authorizationCheckEnabled = true; + + protected Integer pageSize = null; // null => disabled + + protected boolean passwordCheckCatchAuthenticationException = true; + + // getters / setters ////////////////////////////////////// + + public String getInitialContextFactory() { + return initialContextFactory; + } + + public void setInitialContextFactory(String initialContextFactory) { + this.initialContextFactory = initialContextFactory; + } + + public String getSecurityAuthentication() { + return securityAuthentication; + } + + public void setSecurityAuthentication(String securityAuthentication) { + this.securityAuthentication = securityAuthentication; + } + + public Map getContextProperties() { + return contextProperties; + } + + public void setContextProperties(Map contextProperties) { + this.contextProperties = contextProperties; + } + + public String getServerUrl() { + return serverUrl; + } + + public void setServerUrl(String serverUrl) { + this.serverUrl = serverUrl; + } + + public String getManagerDn() { + return managerDn; + } + + public void setManagerDn(String managerDn) { + this.managerDn = managerDn; + } + + public String getManagerPassword() { + return managerPassword; + } + + public void setManagerPassword(String managerPassword) { + this.managerPassword = managerPassword; + } + + public String getUserDnPattern() { + return userDnPattern; + } + + public void setUserDnPattern(String userDnPattern) { + this.userDnPattern = userDnPattern; + } + + public String getGroupSearchBase() { + return groupSearchBase; + } + + public void setGroupSearchBase(String groupSearchBase) { + this.groupSearchBase = groupSearchBase; + } + + public String getGroupSearchFilter() { + return groupSearchFilter; + } + + public void setGroupSearchFilter(String groupSearchFilter) { + this.groupSearchFilter = groupSearchFilter; + } + + public String getGroupNameAttribute() { + return groupNameAttribute; + } + + public void setGroupNameAttribute(String groupNameAttribute) { + this.groupNameAttribute = groupNameAttribute; + } + + public String getBaseDn() { + return baseDn; + } + + public void setBaseDn(String baseDn) { + this.baseDn = baseDn; + } + + public String getUserSearchBase() { + return userSearchBase; + } + + public void setUserSearchBase(String userSearchBase) { + this.userSearchBase = userSearchBase; + } + + public String getUserSearchFilter() { + return userSearchFilter; + } + + public void setUserSearchFilter(String userSearchFilter) { + this.userSearchFilter = userSearchFilter; + } + + public String getUserIdAttribute() { + return userIdAttribute; + } + + public void setUserIdAttribute(String userIdAttribute) { + this.userIdAttribute = userIdAttribute; + } + + public String getUserFirstnameAttribute() { + return userFirstnameAttribute; + } + + public void setUserFirstnameAttribute(String userFirstnameAttribute) { + this.userFirstnameAttribute = userFirstnameAttribute; + } + + public String getUserLastnameAttribute() { + return userLastnameAttribute; + } + + public void setUserLastnameAttribute(String userLastnameAttribute) { + this.userLastnameAttribute = userLastnameAttribute; + } + + public String getUserEmailAttribute() { + return userEmailAttribute; + } + + public void setUserEmailAttribute(String userEmailAttribute) { + this.userEmailAttribute = userEmailAttribute; + } + + public String getUserPasswordAttribute() { + return userPasswordAttribute; + } + + public void setUserPasswordAttribute(String userPasswordAttribute) { + this.userPasswordAttribute = userPasswordAttribute; + } + + public boolean isSortControlSupported() { + return sortControlSupported; + } + + public void setSortControlSupported(boolean sortControlSupported) { + this.sortControlSupported = sortControlSupported; + } + + public String getGroupIdAttribute() { + return groupIdAttribute; + } + + public void setGroupIdAttribute(String groupIdAttribute) { + this.groupIdAttribute = groupIdAttribute; + } + + public String getGroupMemberAttribute() { + return groupMemberAttribute; + } + + public void setGroupMemberAttribute(String groupMemberAttribute) { + this.groupMemberAttribute = groupMemberAttribute; + } + + public boolean isUseSsl() { + return useSsl; + } + + public void setUseSsl(boolean useSsl) { + this.useSsl = useSsl; + } + + public boolean isUsePosixGroups() { + return usePosixGroups; + } + + public void setUsePosixGroups(boolean usePosixGroups) { + this.usePosixGroups = usePosixGroups; + } + + public SearchControls getSearchControls() { + SearchControls searchControls = new SearchControls(); + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + searchControls.setTimeLimit(30000); + return searchControls; + } + + public String getGroupTypeAttribute() { + return groupTypeAttribute; + } + + public void setGroupTypeAttribute(String groupTypeAttribute) { + this.groupTypeAttribute = groupTypeAttribute; + } + + public boolean isAllowAnonymousLogin() { + return allowAnonymousLogin; + } + + public void setAllowAnonymousLogin(boolean allowAnonymousLogin) { + this.allowAnonymousLogin = allowAnonymousLogin; + } + + public boolean isAuthorizationCheckEnabled() { + return authorizationCheckEnabled; + } + + public void setAuthorizationCheckEnabled(boolean authorizationCheckEnabled) { + this.authorizationCheckEnabled = authorizationCheckEnabled; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public boolean isPasswordCheckCatchAuthenticationException() { + return passwordCheckCatchAuthenticationException; + } + + public void setPasswordCheckCatchAuthenticationException(boolean passwordCheckCatchAuthenticationException) { + this.passwordCheckCatchAuthenticationException = passwordCheckCatchAuthenticationException; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapGroupEntity.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapGroupEntity.java new file mode 100644 index 0000000000000000000000000000000000000000..9c37eacac707546f51910e9af92b372051587209 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapGroupEntity.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import org.camunda.bpm.engine.impl.persistence.entity.GroupEntity; + +/** + * @author Daniel Meyer + * + */ +public class LdapGroupEntity extends GroupEntity { + + private static final long serialVersionUID = 1L; + + protected String dn; + + public String getDn() { + return dn; + } + + public void setDn(String dn) { + this.dn = dn; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapGroupQuery.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapGroupQuery.java new file mode 100644 index 0000000000000000000000000000000000000000..dde01e88548932c035c16480eb232c3f840eab9a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapGroupQuery.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import java.util.List; + +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.impl.GroupQueryImpl; +import org.camunda.bpm.engine.impl.Page; +import org.camunda.bpm.engine.impl.interceptor.CommandContext; +import org.camunda.bpm.engine.impl.interceptor.CommandExecutor; + +/** + * @author Daniel Meyer + * + */ +public class LdapGroupQuery extends GroupQueryImpl { + + private static final long serialVersionUID = 1L; + + public LdapGroupQuery() { + super(); + } + + public LdapGroupQuery(CommandExecutor commandExecutor) { + super(commandExecutor); + } + + // execute queries //////////////////////////// + + public long executeCount(CommandContext commandContext) { + final LdapIdentityProviderSession identityProvider = getLdapIdentityProvider(commandContext); + return identityProvider.findGroupCountByQueryCriteria(this); + } + + public List executeList(CommandContext commandContext, Page page) { + final LdapIdentityProviderSession identityProvider = getLdapIdentityProvider(commandContext); + return identityProvider.findGroupByQueryCriteria(this); + } + + protected LdapIdentityProviderSession getLdapIdentityProvider(CommandContext commandContext) { + return (LdapIdentityProviderSession) commandContext.getReadOnlyIdentityProvider(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapIdentityProviderFactory.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapIdentityProviderFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..5cd31af3086ccd1baa57de8fa1bdc7972db32327 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapIdentityProviderFactory.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import org.camunda.bpm.engine.impl.identity.ReadOnlyIdentityProvider; +import org.camunda.bpm.engine.impl.interceptor.Session; +import org.camunda.bpm.engine.impl.interceptor.SessionFactory; + +/** + * @author Daniel Meyer + * + */ +public class LdapIdentityProviderFactory implements SessionFactory { + + protected LdapConfiguration ldapConfiguration; + + public Class getSessionType() { + return ReadOnlyIdentityProvider.class; + } + + public Session openSession() { + return new LdapIdentityProviderSession(ldapConfiguration); + } + + public LdapConfiguration getLdapConfiguration() { + return ldapConfiguration; + } + + public void setLdapConfiguration(LdapConfiguration ldapConfiguration) { + this.ldapConfiguration = ldapConfiguration; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapIdentityProviderSession.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapIdentityProviderSession.java new file mode 100644 index 0000000000000000000000000000000000000000..62bf9ba2e1f482a150e315514b53e8fb6bd318f3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapIdentityProviderSession.java @@ -0,0 +1,707 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Resources.GROUP; +import static org.camunda.bpm.engine.authorization.Resources.USER; +import static org.camunda.bpm.engine.impl.context.Context.getCommandContext; +import static org.camunda.bpm.engine.impl.context.Context.getProcessEngineConfiguration; +import static org.camunda.bpm.identity.impl.ldap.LdapConfiguration.DB_QUERY_WILDCARD; +import static org.camunda.bpm.identity.impl.ldap.LdapConfiguration.LDAP_QUERY_WILDCARD; + +import java.io.StringWriter; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Predicate; + +import javax.naming.NamingEnumeration; +import javax.naming.directory.Attributes; +import javax.naming.directory.SearchResult; +import javax.naming.ldap.Control; +import javax.naming.ldap.LdapContext; +import javax.naming.ldap.SortKey; +import javax.naming.ldap.PagedResultsResponseControl; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.identity.NativeUserQuery; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.identity.TenantQuery; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.impl.AbstractQuery; +import org.camunda.bpm.engine.impl.QueryOrderingProperty; +import org.camunda.bpm.engine.impl.UserQueryImpl; +import org.camunda.bpm.engine.impl.UserQueryProperty; +import org.camunda.bpm.engine.impl.GroupQueryProperty; +import org.camunda.bpm.engine.impl.db.DbEntity; +import org.camunda.bpm.engine.impl.identity.IdentityProviderException; +import org.camunda.bpm.engine.impl.identity.ReadOnlyIdentityProvider; +import org.camunda.bpm.engine.impl.interceptor.CommandContext; +import org.camunda.bpm.engine.impl.persistence.entity.GroupEntity; +import org.camunda.bpm.engine.impl.persistence.entity.UserEntity; +import org.camunda.bpm.engine.impl.Direction; +import org.camunda.bpm.identity.impl.ldap.util.LdapPluginLogger; + +/** + *

LDAP {@link ReadOnlyIdentityProvider}.

+ * + * @author Daniel Meyer + */ +public class LdapIdentityProviderSession implements ReadOnlyIdentityProvider { + + protected LdapConfiguration ldapConfiguration; + + protected LdapClient ldapClient; + + public LdapIdentityProviderSession(LdapConfiguration ldapConfiguration) { + this.ldapConfiguration = ldapConfiguration; + this.ldapClient = new LdapClient(ldapConfiguration); + } + + // Session Lifecycle ////////////////////////////////// + + public void flush() { + // nothing to do + } + + public void close() { + ldapClient.closeLdapCtx(); + } + + // Users ///////////////////////////////////////////////// + + public User findUserById(String userId) { + return createUserQuery(getCommandContext()).userId(userId).singleResult(); + } + + public UserQuery createUserQuery() { + return new LdapUserQueryImpl(getProcessEngineConfiguration().getCommandExecutorTxRequired(), ldapConfiguration); + } + + public UserQueryImpl createUserQuery(CommandContext commandContext) { + return new LdapUserQueryImpl(ldapConfiguration); + } + + @Override + public NativeUserQuery createNativeUserQuery() { + throw new BadUserRequestException("Native user queries are not supported for LDAP identity service provider."); + } + + public long findUserCountByQueryCriteria(LdapUserQueryImpl query) { + ldapClient.ensureContextInitialized(); + return findUserByQueryCriteria(query).size(); + } + + public List findUserByQueryCriteria(LdapUserQueryImpl query) { + ldapClient.ensureContextInitialized(); + + // convert DB wildcards to LDAP wildcards if necessary + if (query.getEmailLike() != null) { + query.userEmailLike(query.getEmailLike().replaceAll(DB_QUERY_WILDCARD, LDAP_QUERY_WILDCARD)); + } + if (query.getFirstNameLike() != null) { + query.userFirstNameLike(query.getFirstNameLike().replaceAll(DB_QUERY_WILDCARD, LDAP_QUERY_WILDCARD)); + } + if (query.getLastNameLike() != null) { + query.userLastNameLike(query.getLastNameLike().replaceAll(DB_QUERY_WILDCARD, LDAP_QUERY_WILDCARD)); + } + + if (query.getGroupId() != null) { + // if restriction on groupId is provided, we need to search in group tree first, look for the group and then further restrict on the members + return findUsersByGroupId(query); + } else { + String userBaseDn = composeDn(ldapConfiguration.getUserSearchBase(), ldapConfiguration.getBaseDn()); + return findUsersWithoutGroupId(query, userBaseDn, false); + } + } + + protected boolean paginationContinues(int currentSize, int maxResults) { + return nextPageDetected() && currentSize < maxResults; + } + + protected List findUsersByGroupId(LdapUserQueryImpl query) { + String baseDn = getDnForGroup(query.getGroupId()); + + // compose group search filter + String groupSearchFilter = "(& " + ldapConfiguration.getGroupSearchFilter() + ")"; + + initializeControls(query); + + List groupMembers = new ArrayList<>(); + int resultCount = 0; + + do { + try (LdapSearchResults searchResults = ldapClient.search(baseDn, groupSearchFilter)) { + // first find group + while (searchResults.hasMoreElements()) { + String groupMemberAttribute = ldapConfiguration.getGroupMemberAttribute(); + NamingEnumeration allGroupMembers = LdapClient.getAllMembers(groupMemberAttribute, searchResults); + if (allGroupMembers != null) { + // iterate group members + while (allGroupMembers.hasMoreElements()) { + if (resultCount >= query.getFirstResult()) { + groupMembers.add(allGroupMembers.nextElement()); + } + resultCount++; + } + } + } + } + } while (paginationContinues(groupMembers.size(), query.getMaxResults())); + + List userList = new ArrayList<>(); + String userBaseDn = composeDn(ldapConfiguration.getUserSearchBase(), ldapConfiguration.getBaseDn()); + int memberCount = 0; + for (String memberId : groupMembers) { + if (userList.size() < query.getMaxResults() && memberCount >= query.getFirstResult()) { + if (ldapConfiguration.isUsePosixGroups()) { + query.userId(memberId); + } + List users = ldapConfiguration.isUsePosixGroups() ? + findUsersWithoutGroupId(query, userBaseDn, true) : + findUsersWithoutGroupId(query, memberId, true); + if (!users.isEmpty()) { + userList.add(users.get(0)); + } + } + memberCount++; + } + + return userList; + } + + public boolean checkPassword(String userId, String password) { + + // prevent a null password + if (password == null) { + return false; + } + + // engine can't work without users + if (userId == null || userId.isEmpty()) { + return false; + } + + /* + * We only allow login with no password if anonymous login is set. + * RFC allows such a behavior but discourages the usage, so we provide it for + * user which have a ldap with anonymous login. + */ + if (!ldapConfiguration.isAllowAnonymousLogin() && password.isEmpty()) { + return false; + } + + // first search for user using manager DN + LdapUserEntity user = (LdapUserEntity) findUserById(userId); + close(); + + if (user == null) { + return false; + } else { + + LdapContext context = null; + + try { + // bind authenticate for user + supplied password + context = ldapClient.openContext(user.getDn(), password); + return true; + + } catch (LdapAuthenticationException e) { + if(ldapConfiguration.isPasswordCheckCatchAuthenticationException()) { + return false; + } else { + throw e; + } + + } finally { + ldapClient.closeLdapCtx(context); + + } + + } + + } + + protected String getUserSearchFilter(LdapUserQueryImpl query) { + + StringWriter search = new StringWriter(); + search.write("(&"); + + // restrict to users + search.write(ldapConfiguration.getUserSearchFilter()); + + // add additional filters from query + if (query.getId() != null) { + addFilter(ldapConfiguration.getUserIdAttribute(), escapeLDAPSearchFilter(query.getId()), search); + } + if (query.getIds() != null && query.getIds().length > 0) { + // wrap ids in OR statement + search.write("(|"); + for (String userId : query.getIds()) { + addFilter(ldapConfiguration.getUserIdAttribute(), escapeLDAPSearchFilter(userId), search); + } + search.write(")"); + } + if (query.getEmail() != null) { + addFilter(ldapConfiguration.getUserEmailAttribute(), query.getEmail(), search); + } + if (query.getEmailLike() != null) { + addFilter(ldapConfiguration.getUserEmailAttribute(), query.getEmailLike(), search); + } + if (query.getFirstName() != null) { + addFilter(ldapConfiguration.getUserFirstnameAttribute(), query.getFirstName(), search); + } + if (query.getFirstNameLike() != null) { + addFilter(ldapConfiguration.getUserFirstnameAttribute(), query.getFirstNameLike(), search); + } + if (query.getLastName() != null) { + addFilter(ldapConfiguration.getUserLastnameAttribute(), query.getLastName(), search); + } + if (query.getLastNameLike() != null) { + addFilter(ldapConfiguration.getUserLastnameAttribute(), query.getLastNameLike(), search); + } + + search.write(")"); + + return search.toString(); + } + protected boolean isAuthenticatedAndAuthorized(String userId) { + return isAuthenticatedUser(userId) || isAuthorizedToRead(USER, userId); + } + + public List findUsersWithoutGroupId(LdapUserQueryImpl query, String userBaseDn, boolean ignorePagination) { + initializeControls(query); + + return retrieveResults(userBaseDn, + getUserSearchFilter(query), + this::transformUser, + this::isAuthenticatedAndAuthorized, + query.getMaxResults(), + query.getFirstResult(), + ignorePagination); + } + + // Groups /////////////////////////////////////////////// + + public Group findGroupById(String groupId) { + return createGroupQuery(getCommandContext()).groupId(groupId).singleResult(); + } + + public GroupQuery createGroupQuery() { + return new LdapGroupQuery(getProcessEngineConfiguration().getCommandExecutorTxRequired()); + } + + public GroupQuery createGroupQuery(CommandContext commandContext) { + return new LdapGroupQuery(); + } + + public long findGroupCountByQueryCriteria(LdapGroupQuery ldapGroupQuery) { + ldapClient.ensureContextInitialized(); + return findGroupByQueryCriteria(ldapGroupQuery).size(); + } + + protected boolean isAuthorizedToReadGroup(String groupId) { + return isAuthorizedToRead(GROUP, groupId); + } + + public List findGroupByQueryCriteria(LdapGroupQuery query) { + + // convert DB wildcards to LDAP wildcards if necessary + if (query.getNameLike() != null) { + query.groupNameLike(query.getNameLike().replaceAll(DB_QUERY_WILDCARD, LDAP_QUERY_WILDCARD)); + } + + ldapClient.ensureContextInitialized(); + + String groupBaseDn = composeDn(ldapConfiguration.getGroupSearchBase(), ldapConfiguration.getBaseDn()); + + initializeControls(query); + + return retrieveResults(groupBaseDn, + getGroupSearchFilter(query), + this::transformGroup, + this::isAuthorizedToReadGroup, + query.getMaxResults(), + query.getFirstResult(), + false); + } + + protected String getGroupSearchFilter(LdapGroupQuery query) { + + StringWriter search = new StringWriter(); + search.write("(&"); + + // restrict to groups + search.write(ldapConfiguration.getGroupSearchFilter()); + + // add additional filters from query + if (query.getId() != null) { + addFilter(ldapConfiguration.getGroupIdAttribute(), query.getId(), search); + } + if (query.getIds() != null && query.getIds().length > 0) { + search.write("(|"); + for (String id : query.getIds()) { + addFilter(ldapConfiguration.getGroupIdAttribute(), id, search); + } + search.write(")"); + } + if (query.getName() != null) { + addFilter(ldapConfiguration.getGroupNameAttribute(), query.getName(), search); + } + if (query.getNameLike() != null) { + addFilter(ldapConfiguration.getGroupNameAttribute(), query.getNameLike(), search); + } + if (query.getUserId() != null) { + String userDn = null; + if (ldapConfiguration.isUsePosixGroups()) { + userDn = query.getUserId(); + } else { + userDn = getDnForUser(query.getUserId()); + } + addFilter(ldapConfiguration.getGroupMemberAttribute(), escapeLDAPSearchFilter(userDn), search); + } + search.write(")"); + + return search.toString(); + } + + // Utils //////////////////////////////////////////// + + @SuppressWarnings("unchecked") + protected List retrieveResults(String baseDn, + String filter, + Function transformEntity, + Predicate resultCountPredicate, + int maxResults, + int firstResult, + boolean ignorePagination) { + StringBuilder resultLogger = new StringBuilder(); + if (LdapPluginLogger.INSTANCE.isDebugEnabled()) { + resultLogger.append("LDAP query results: ["); + } + + List entities = new ArrayList<>(); + + int resultCount = 0; + + do { + try (LdapSearchResults searchResults = ldapClient.search(baseDn, filter)) { + while (searchResults.hasMoreElements() && (entities.size() < maxResults || ignorePagination)) { + SearchResult result = searchResults.nextElement(); + + E entity = transformEntity.apply(result); + + String id = entity.getId(); + if (id == null) { + LdapPluginLogger.INSTANCE.invalidLdapEntityReturned(entity, result); + } else { + if (resultCountPredicate.test(id)) { + if (resultCount >= firstResult || ignorePagination) { + if (LdapPluginLogger.INSTANCE.isDebugEnabled()) { + resultLogger.append(entity); + resultLogger.append(" based on "); + resultLogger.append(result); + resultLogger.append(", "); + } + entities.add((T) entity); + } + resultCount++; + } + } + } + } + } while (paginationContinues(entities.size(), maxResults)); + + if (LdapPluginLogger.INSTANCE.isDebugEnabled()) { + resultLogger.append("]"); + LdapPluginLogger.INSTANCE.queryResult(resultLogger.toString()); + } + + return entities; + } + + protected String getDnForUser(String userId) { + LdapUserEntity user = (LdapUserEntity) createUserQuery(getCommandContext()).userId(userId).singleResult(); + if (user == null) { + return ""; + } else { + return user.getDn(); + } + } + + protected String getDnForGroup(String groupId) { + LdapGroupEntity group = (LdapGroupEntity) createGroupQuery(getCommandContext()).groupId(groupId).singleResult(); + if (group == null) { + return ""; + } else { + return group.getDn(); + } + } + + protected void addFilter(String attributeName, String attributeValue, StringWriter writer) { + writer.write("("); + writer.write(attributeName); + writer.write("="); + writer.write(attributeValue); + writer.write(")"); + } + + protected UserEntity transformUser(SearchResult result) { + final Attributes attributes = result.getAttributes(); + LdapUserEntity user = new LdapUserEntity(); + user.setDn(result.getNameInNamespace()); + user.setId(LdapClient.getValue(ldapConfiguration.getUserIdAttribute(), attributes)); + user.setFirstName(LdapClient.getValue(ldapConfiguration.getUserFirstnameAttribute(), attributes)); + user.setLastName(LdapClient.getValue(ldapConfiguration.getUserLastnameAttribute(), attributes)); + user.setEmail(LdapClient.getValue(ldapConfiguration.getUserEmailAttribute(), attributes)); + return user; + } + + protected GroupEntity transformGroup(SearchResult result) { + final Attributes attributes = result.getAttributes(); + LdapGroupEntity group = new LdapGroupEntity(); + group.setDn(result.getNameInNamespace()); + group.setId(LdapClient.getValue(ldapConfiguration.getGroupIdAttribute(), attributes)); + group.setName(LdapClient.getValue(ldapConfiguration.getGroupNameAttribute(), attributes)); + group.setType(LdapClient.getValue(ldapConfiguration.getGroupTypeAttribute(), attributes)); + return group; + } + + /** + * Return the list of Controls requested in the query. Query may be run on USERS or on GROUP + * + * @param query query asks, contains the order by requested + * @return list of control to send to LDAP + */ + protected List getSortingControls(AbstractQuery query) { + List controls = new ArrayList<>(); + + List orderBy = query.getOrderingProperties(); + if (orderBy != null) { + for (QueryOrderingProperty orderingProperty : orderBy) { + String propertyName = orderingProperty.getQueryProperty().getName(); + SortKey sortKey = getSortKey(query, propertyName, orderingProperty); + + if (sortKey != null) { + LdapClient.addSortKey(sortKey, controls); + } + } + } + + return controls; + } + + protected SortKey getSortKey(AbstractQuery query, String propertyName, QueryOrderingProperty orderingProperty) { + if (query instanceof LdapUserQueryImpl) { + if (UserQueryProperty.USER_ID.getName().equals(propertyName)) { + return new SortKey(ldapConfiguration.getUserIdAttribute(), + Direction.ASCENDING.equals(orderingProperty.getDirection()), null); + + } else if (UserQueryProperty.EMAIL.getName().equals(propertyName)) { + return new SortKey(ldapConfiguration.getUserEmailAttribute(), + Direction.ASCENDING.equals(orderingProperty.getDirection()), null); + + } else if (UserQueryProperty.FIRST_NAME.getName().equals(propertyName)) { + return new SortKey(ldapConfiguration.getUserFirstnameAttribute(), + Direction.ASCENDING.equals(orderingProperty.getDirection()), null); + + } else if (UserQueryProperty.LAST_NAME.getName().equals(propertyName)) { + return new SortKey(ldapConfiguration.getUserLastnameAttribute(), + Direction.ASCENDING.equals(orderingProperty.getDirection()), null); + } + } else if (query instanceof LdapGroupQuery) { + if (GroupQueryProperty.GROUP_ID.getName().equals(propertyName)) { + return new SortKey(ldapConfiguration.getGroupIdAttribute(), + Direction.ASCENDING.equals(orderingProperty.getDirection()), null); + } else if (GroupQueryProperty.NAME.getName().equals(propertyName)) { + return new SortKey(ldapConfiguration.getGroupNameAttribute(), + Direction.ASCENDING.equals(orderingProperty.getDirection()), null); + } + // not possible to order by Type: LDAP may not support the type + } + + return null; + } + + protected String composeDn(String... parts) { + StringWriter resultDn = new StringWriter(); + for (String s : parts) { + String part = s; + if (part == null || part.length() == 0) { + continue; + } + if (part.endsWith(",")) { + part = part.substring(part.length() - 2, part.length() - 1); + } + if (part.startsWith(",")) { + part = part.substring(1); + } + String currentDn = resultDn.toString(); + if (!currentDn.endsWith(",") && currentDn.length() > 0) { + resultDn.write(","); + } + resultDn.write(part); + } + return resultDn.toString(); + } + + /** + * @return true if the passed-in user is currently authenticated + */ + protected boolean isAuthenticatedUser(String userid) { + if (userid == null) { + return false; + } + return userid.equalsIgnoreCase(getCommandContext().getAuthenticatedUserId()); + } + + protected boolean isAuthorizedToRead(Resource resource, String resourceId) { + return !ldapConfiguration.isAuthorizationCheckEnabled() || + getCommandContext().getAuthorizationManager() + .isAuthorized(READ, resource, resourceId); + } + + // Based on https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java + protected final String escapeLDAPSearchFilter(String filter) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < filter.length(); i++) { + char curChar = filter.charAt(i); + switch (curChar) { + case '\\': + sb.append("\\5c"); + break; + case '*': + sb.append("\\2a"); + break; + case '(': + sb.append("\\28"); + break; + case ')': + sb.append("\\29"); + break; + case '\u0000': + sb.append("\\00"); + break; + default: + sb.append(curChar); + } + } + return sb.toString(); + } + + /** + * Initializes paged results and sort controls. Might not be supported by all LDAP implementations. + */ + protected void initializeControls(AbstractQuery query) { + List listControls = new ArrayList<>(); + if (ldapConfiguration.isSortControlSupported()) { + listControls.addAll(getSortingControls(query)); + } + + try { + if (isPaginationSupported()) { + LdapClient.addPaginationControl(listControls, null, getPageSize()); + } + } catch (IdentityProviderException ignored) { + // Ignore exception when pagination is not supported + } finally { + if (!listControls.isEmpty()) { + ldapClient.setRequestControls(listControls); + } + } + } + + /** + * Check in the context if we reach the last page on the query + * + * @return new page detected + */ + protected boolean nextPageDetected() { + // if the pagination is not activated, there isn't a next page. + if (!isPaginationSupported()) { + return false; + } + + Control[] controls = ldapClient.getResponseControls(); + if (controls == null) { + return false; + } + + List newControlList = new ArrayList<>(); + boolean newPageDetected = false; + for (Control control : controls) { + if (control instanceof PagedResultsResponseControl) { + PagedResultsResponseControl prrc = (PagedResultsResponseControl) control; + byte[] cookie = prrc.getCookie(); + + // Re-activate paged results + try { + LdapClient.addPaginationControl(newControlList, cookie, getPageSize()); + } catch (IdentityProviderException e) { + return false; + } + newPageDetected = cookie != null; + } + } + + if (!newControlList.isEmpty()) { + // This is more an UPDATE than a SET. All previous control (sorting) does not need to + // be set again, the current context keeps them, and the next page is correctly ordered for example. + // In the current context, just the PageResultControl must be re-set (even this a xxxResultxxx) + // All another result (SortResponseControl for example) must not be set again, nor the SortControl. + ldapClient.setRequestControls(newControlList); + } + + return newPageDetected; + } + + protected boolean isPaginationSupported() { + return getPageSize() != null; + } + + /** + * Return the pageSize. Returns null if pagination is disabled. + * + * @return the pageSize + */ + protected Integer getPageSize() { + return ldapConfiguration.getPageSize(); + } + + @Override + public TenantQuery createTenantQuery() { + return new LdapTenantQuery(getProcessEngineConfiguration().getCommandExecutorTxRequired()); + } + + @Override + public TenantQuery createTenantQuery(CommandContext commandContext) { + return new LdapTenantQuery(); + } + + @Override + public Tenant findTenantById(String id) { + // since multi-tenancy is not supported for the LDAP plugin, always return null + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapSearchResults.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapSearchResults.java new file mode 100644 index 0000000000000000000000000000000000000000..6ef29e9708c2cd12a4b41a3bb0ff14b507e88d72 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapSearchResults.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.SearchResult; + +public class LdapSearchResults implements NamingEnumeration, AutoCloseable { + + protected NamingEnumeration enumeration; + + public LdapSearchResults(NamingEnumeration enumeration) { + this.enumeration = enumeration; + } + + @Override + public SearchResult next() throws NamingException { + return enumeration.next(); + } + + @Override + public boolean hasMore() throws NamingException { + return enumeration.hasMore(); + } + + @Override + public boolean hasMoreElements() { + return enumeration.hasMoreElements(); + } + + @Override + public SearchResult nextElement() { + return enumeration.nextElement(); + } + + @Override + public void close() { + try { + if (enumeration != null) { + enumeration.close(); + } + } catch (Exception e) { + // ignore silently + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapTenantQuery.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapTenantQuery.java new file mode 100644 index 0000000000000000000000000000000000000000..f98a14f45660b54c3ccb426ecb5d6f7509f5e243 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapTenantQuery.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import java.util.Collections; +import java.util.List; + +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.impl.Page; +import org.camunda.bpm.engine.impl.TenantQueryImpl; +import org.camunda.bpm.engine.impl.interceptor.CommandContext; +import org.camunda.bpm.engine.impl.interceptor.CommandExecutor; + +/** + * Since multi-tenancy is not supported for the LDAP plugin, the query always + * returns 0 or an empty list. + */ +public class LdapTenantQuery extends TenantQueryImpl { + + private static final long serialVersionUID = 1L; + + public LdapTenantQuery() { + super(); + } + + public LdapTenantQuery(CommandExecutor commandExecutor) { + super(commandExecutor); + } + + @Override + public long executeCount(CommandContext commandContext) { + return 0; + } + + @Override + public List executeList(CommandContext commandContext, Page page) { + return Collections.emptyList(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapUserEntity.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapUserEntity.java new file mode 100644 index 0000000000000000000000000000000000000000..34c13ad8c84c9afde692fbf919aef674ac809192 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapUserEntity.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import org.camunda.bpm.engine.impl.persistence.entity.UserEntity; + +/** + * @author Daniel Meyer + * + */ +public class LdapUserEntity extends UserEntity { + + private static final long serialVersionUID = 1L; + + protected String dn; + + public String getDn() { + return dn; + } + + public void setDn(String dn) { + this.dn = dn; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapUserQueryImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapUserQueryImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..ccb9d38c2df286c826643ab36214547e4586d4d4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/LdapUserQueryImpl.java @@ -0,0 +1,73 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.impl.Page; +import org.camunda.bpm.engine.impl.UserQueryImpl; +import org.camunda.bpm.engine.impl.interceptor.CommandContext; +import org.camunda.bpm.engine.impl.interceptor.CommandExecutor; + +import java.util.List; + +/** + * @author Daniel Meyer + * + */ +public class LdapUserQueryImpl extends UserQueryImpl { + + private static final long serialVersionUID = 1L; + private final LdapConfiguration ldapConfiguration; + + public LdapUserQueryImpl(LdapConfiguration ldapConfiguration) { + super(); + this.ldapConfiguration = ldapConfiguration; + } + + public LdapUserQueryImpl(CommandExecutor commandExecutor, LdapConfiguration ldapConfiguration) { + super(commandExecutor); + this.ldapConfiguration = ldapConfiguration; + } + + // execute queries ///////////////////////////////////////// + + public long executeCount(CommandContext commandContext) { + final LdapIdentityProviderSession provider = getLdapIdentityProvider(commandContext); + return provider.findUserCountByQueryCriteria(this); + } + + public List executeList(CommandContext commandContext, Page page) { + final LdapIdentityProviderSession provider = getLdapIdentityProvider(commandContext); + return provider.findUserByQueryCriteria(this); + } + + protected LdapIdentityProviderSession getLdapIdentityProvider(CommandContext commandContext) { + return (LdapIdentityProviderSession) commandContext.getReadOnlyIdentityProvider(); + } + + @Override + public UserQuery desc() { + // provide this exception then a popup will be visible in the admin task, but display will run correctly + if (ldapConfiguration != null && !ldapConfiguration.isSortControlSupported()) { + throw new UnsupportedOperationException("The LDAP identity provider does not support descending search order."); + } + + return this; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/plugin/LdapIdentityProviderPlugin.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/plugin/LdapIdentityProviderPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..d6c80d2e77be619940a16e928d863ecc29ef2ccb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/plugin/LdapIdentityProviderPlugin.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap.plugin; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.cfg.ProcessEnginePlugin; +import org.camunda.bpm.identity.impl.ldap.LdapConfiguration; +import org.camunda.bpm.identity.impl.ldap.LdapIdentityProviderFactory; +import org.camunda.bpm.identity.impl.ldap.util.CertificateHelper; +import org.camunda.bpm.identity.impl.ldap.util.LdapPluginLogger; + +/** + *

{@link ProcessEnginePlugin} providing Ldap Identity Provider support

+ * + *

This class extends {@link LdapConfiguration} such that the configuration properties + * can be set directly on this class vie the <properties .../> element + * in bpm-platform.xml / processes.xml

+ * + * @author Daniel Meyer + * + */ +public class LdapIdentityProviderPlugin extends LdapConfiguration implements ProcessEnginePlugin { + + protected boolean acceptUntrustedCertificates = false; + + public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { + + LdapPluginLogger.INSTANCE.pluginActivated(getClass().getSimpleName(), processEngineConfiguration.getProcessEngineName()); + + if(acceptUntrustedCertificates) { + CertificateHelper.acceptUntrusted(); + LdapPluginLogger.INSTANCE.acceptingUntrustedCertificates(); + } + + LdapIdentityProviderFactory ldapIdentityProviderFactory = new LdapIdentityProviderFactory(); + ldapIdentityProviderFactory.setLdapConfiguration(this); + processEngineConfiguration.setIdentityProviderSessionFactory(ldapIdentityProviderFactory); + + } + + public void postInit(ProcessEngineConfigurationImpl processEngineConfiguration) { + // nothing to do + } + + public void postProcessEngineBuild(ProcessEngine processEngine) { + // nothing to do + } + + public void setAcceptUntrustedCertificates(boolean acceptUntrustedCertificates) { + this.acceptUntrustedCertificates = acceptUntrustedCertificates; + } + + public boolean isAcceptUntrustedCertificates() { + return acceptUntrustedCertificates; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/util/CertificateHelper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/util/CertificateHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..0209a426c60e46b0e536ae1c6aa7ef438dc56020 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/util/CertificateHelper.java @@ -0,0 +1,57 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap.util; + +import java.security.SecureRandom; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + + +public class CertificateHelper { + + public static void acceptUntrusted() { + try { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); + SSLContext.setDefault(sslContext); + } catch (Exception ex) { + throw new RuntimeException("Could not change SSL TrustManager to accept arbitrary certificates", ex); + } + } + + private static class DefaultTrustManager implements X509TrustManager { + + @Override + public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + + @Override + public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/util/LdapPluginLogger.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/util/LdapPluginLogger.java new file mode 100644 index 0000000000000000000000000000000000000000..e52c6dd5ce165c8aeae2543107df9dd9039d9ec4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/main/java/org/camunda/bpm/identity/impl/ldap/util/LdapPluginLogger.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap.util; + +import javax.naming.directory.SearchResult; + +import org.camunda.bpm.engine.impl.db.DbEntity; +import org.camunda.bpm.engine.impl.persistence.entity.UserEntity; +import org.camunda.commons.logging.BaseLogger; + +/** + * @author Thorben Lindhauer + * + */ +public class LdapPluginLogger extends BaseLogger { + + public static final String PROJECT_CODE = "LDAP"; + + public static final LdapPluginLogger INSTANCE = BaseLogger.createLogger( + LdapPluginLogger.class, PROJECT_CODE, "org.camunda.bpm.identity.impl.ldap", "00"); + + public void pluginActivated(String pluginClassName, String engineName) { + logInfo("001", "PLUGIN {} activated on process engine {}", pluginClassName, engineName); + } + + public void acceptingUntrustedCertificates() { + logWarn("002", "Enabling accept of untrusted certificates. Use at own risk."); + } + + public void exceptionWhenClosingLdapContext(Exception e) { + logDebug("003", "exception while closing LDAP DIR CTX", e); + } + + public void invalidLdapEntityReturned(E entity, SearchResult searchResult) { + String entityType = entity instanceof UserEntity ? "user" : "group"; + logError("004", "LDAP {} query returned a {} with id null. This {} will be ignored. " + + "This indicates a misconfiguration of the LDAP plugin or a problem with the LDAP service." + + " Enable DEBUG/FINE logging for details.", entityType, entityType, entityType); + // log sensitive data only on FINE + logDebug("004", "Invalid {}: {} based on search result {}", entityType, entity, searchResult); + } + + public void queryResult(String summary) { + // log sensitive data only on FINE + logDebug("005", summary); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapDisableAuthorizationCheckTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapDisableAuthorizationCheckTest.java new file mode 100644 index 0000000000000000000000000000000000000000..16c0a94c0499adcea1033a582c904c688484621b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapDisableAuthorizationCheckTest.java @@ -0,0 +1,170 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.camunda.bpm.engine.authorization.Authorization.AUTH_TYPE_GRANT; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Resources.GROUP; +import static org.camunda.bpm.engine.authorization.Resources.USER; +import static org.camunda.bpm.identity.ldap.util.LdapTestUtilities.testGroupPaging; +import static org.camunda.bpm.identity.ldap.util.LdapTestUtilities.testUserPaging; + +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.camunda.bpm.identity.ldap.util.LdapTestUtilities; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +/** + * @author Roman Smirnov + * + */ +public class LdapDisableAuthorizationCheckTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule("camunda.ldap.disable.authorization.check.cfg.xml"); + + ProcessEngineConfiguration processEngineConfiguration; + IdentityService identityService; + AuthorizationService authorizationService; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + processEngineConfiguration = engineRule.getProcessEngineConfiguration(); + identityService = engineRule.getIdentityService(); + authorizationService = engineRule.getAuthorizationService(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + @Test + public void testUserQueryPagination() { + LdapTestUtilities.testUserPaging(identityService, ldapTestEnvironment); + } + + @Test + public void testUserQueryPaginationWithAuthenticatedUserWithoutAuthorizations() { + try { + processEngineConfiguration.setAuthorizationEnabled(true); + + identityService.setAuthenticatedUserId("oscar"); + testUserPaging(identityService, ldapTestEnvironment); + + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + } + } + + @Test + public void testUserQueryPaginationWithAuthenticatedUserWithAuthorizations() { + createGrantAuthorization(USER, "roman", "oscar", READ); + createGrantAuthorization(USER, "daniel", "oscar", READ); + createGrantAuthorization(USER, "monster", "oscar", READ); + createGrantAuthorization(USER, "ruecker", "oscar", READ); + + try { + processEngineConfiguration.setAuthorizationEnabled(true); + + identityService.setAuthenticatedUserId("oscar"); + testUserPaging(identityService, ldapTestEnvironment); + + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + + for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { + authorizationService.deleteAuthorization(authorization.getId()); + } + + } + } + + @Test + public void testGroupQueryPagination() { + testGroupPaging(identityService); + } + + @Test + public void testGroupQueryPaginationWithAuthenticatedUserWithoutAuthorizations() { + try { + processEngineConfiguration.setAuthorizationEnabled(true); + + identityService.setAuthenticatedUserId("oscar"); + testGroupPaging(identityService); + + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + } + } + + @Test + public void testGroupQueryPaginationWithAuthenticatedUserWithAuthorizations() { + createGrantAuthorization(GROUP, "management", "oscar", READ); + createGrantAuthorization(GROUP, "consulting", "oscar", READ); + createGrantAuthorization(GROUP, "external", "oscar", READ); + + try { + processEngineConfiguration.setAuthorizationEnabled(true); + + identityService.setAuthenticatedUserId("oscar"); + testGroupPaging(identityService); + + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + + for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { + authorizationService.deleteAuthorization(authorization.getId()); + } + + } + } + + protected void createGrantAuthorization(Resource resource, String resourceId, String userId, Permission... permissions) { + Authorization authorization = createAuthorization(AUTH_TYPE_GRANT, resource, resourceId); + authorization.setUserId(userId); + for (Permission permission : permissions) { + authorization.addPermission(permission); + } + authorizationService.saveAuthorization(authorization); + } + + protected Authorization createAuthorization(int type, Resource resource, String resourceId) { + Authorization authorization = authorizationService.createNewAuthorization(type); + + authorization.setResource(resource); + if (resourceId != null) { + authorization.setResourceId(resourceId); + } + + return authorization; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapEnableSortControlSupportTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapEnableSortControlSupportTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f72b43ed7b59e1ffbf2cc4131e62a6a779acdabc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapEnableSortControlSupportTest.java @@ -0,0 +1,273 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +/** + * Represents a test case where the sortControlSupport property is enabled. + * + * @author Christopher Zell + */ +public class LdapEnableSortControlSupportTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule("camunda.ldap.enable.sort.control.support.cfg.xml"); + + IdentityService identityService; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + identityService = engineRule.getIdentityService(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + /** + * FirstName + */ + @Test + public void testOrderByUserFirstNameAsc() { + List orderedUsers = identityService.createUserQuery().orderByUserFirstName().asc().list(); + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getFirstName)) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getId()).isEqualTo(manualOrderedUsers.get(i).getId()); + } + } + + @Test + public void testOrderByUserFirstNameDesc() { + List orderedUsers = identityService.createUserQuery().orderByUserFirstName().desc().list(); + + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getFirstName).reversed()) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getId()).isEqualTo(manualOrderedUsers.get(i).getId()); + } + } + + /** + * LastName + */ + @Test + public void testOrderByUserLastNameAsc() { + List orderedUsers = identityService.createUserQuery().orderByUserLastName().asc().list(); + + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getLastName)) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getLastName()).isEqualTo(manualOrderedUsers.get(i).getLastName()); + } + } + + @Test + public void testOrderByUserLastNameDesc() { + List orderedUsers = identityService.createUserQuery().orderByUserLastName().desc().list(); + + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getLastName).reversed()) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getLastName()).isEqualTo(manualOrderedUsers.get(i).getLastName()); + } + } + + /** + * EMAIL + */ + @Test + public void testOrderByUserEmailAsc() { + List orderedUsers = identityService.createUserQuery().orderByUserEmail().asc().list(); + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getEmail)) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getId()).isEqualTo(manualOrderedUsers.get(i).getId()); + } + } + + @Test + public void testOrderByUserEmailDesc() { + List orderedUsers = identityService.createUserQuery().orderByUserEmail().desc().list(); + + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getEmail).reversed()) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getId()).isEqualTo(manualOrderedUsers.get(i).getId()); + } + } + + /** + * ID + */ + @Test + public void testOrderByUserIdAsc() { + List orderedUsers = identityService.createUserQuery().orderByUserId().asc().list(); + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getId)) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getId()).isEqualTo(manualOrderedUsers.get(i).getId()); + } + } + + @Test + public void testOrderByUserIdDesc() { + List orderedUsers = identityService.createUserQuery().orderByUserId().desc().list(); + + List manualOrderedUsers = identityService.createUserQuery() + .list() + .stream() + .sorted(Comparator.comparing(User::getId).reversed()) + .collect(Collectors.toList()); + + assertThat(orderedUsers.size()).isEqualTo(manualOrderedUsers.size()); + + for (int i = 0; i < orderedUsers.size(); i++) { + assertThat(orderedUsers.get(i).getId()).isEqualTo(manualOrderedUsers.get(i).getId()); + } + } + + /** + * Group ID Ordering + */ + @Test + public void testOrderByGroupIdAsc() { + List orderedGroup = identityService.createGroupQuery().orderByGroupId().asc().list(); + List manualOrderedGroups = identityService.createGroupQuery() + .list() + .stream() + .sorted(Comparator.comparing(Group::getId)) + .collect(Collectors.toList()); + + assertThat(orderedGroup.size()).isEqualTo(manualOrderedGroups.size()); + + for (int i = 0; i < orderedGroup.size(); i++) { + assertThat(orderedGroup.get(i).getId()).isEqualTo(manualOrderedGroups.get(i).getId()); + } + } + + @Test + public void testOrderByGroupIdDesc() { + List orderedGroup = identityService.createGroupQuery().orderByGroupId().desc().list(); + List manualOrderedGroups = identityService.createGroupQuery() + .list() + .stream() + .sorted(Comparator.comparing(Group::getId).reversed()) + .collect(Collectors.toList()); + + assertThat(orderedGroup.size()).isEqualTo(manualOrderedGroups.size()); + + for (int i = 0; i < orderedGroup.size(); i++) { + assertThat(orderedGroup.get(i).getId()).isEqualTo(manualOrderedGroups.get(i).getId()); + } + } + + /** + * Group Name Ordering + */ + @Test + public void testOrderByGroupNameAsc() { + List orderedGroup = identityService.createGroupQuery().orderByGroupName().asc().list(); + List manualOrderedGroups = identityService.createGroupQuery() + .list() + .stream() + .sorted(Comparator.comparing(Group::getName)) + .collect(Collectors.toList()); + + assertThat(orderedGroup.size()).isEqualTo(manualOrderedGroups.size()); + + for (int i = 0; i < orderedGroup.size(); i++) { + assertThat(orderedGroup.get(i).getId()).isEqualTo(manualOrderedGroups.get(i).getId()); + } + } + + @Test + public void testOrderByGroupNameDesc() { + List orderedGroup = identityService.createGroupQuery().orderByGroupName().desc().list(); + List manualOrderedGroups = identityService.createGroupQuery() + .list() + .stream() + .sorted(Comparator.comparing(Group::getName).reversed()) + .collect(Collectors.toList()); + + assertThat(orderedGroup.size()).isEqualTo(manualOrderedGroups.size()); + + for (int i = 0; i < orderedGroup.size(); i++) { + assertThat(orderedGroup.get(i).getId()).isEqualTo(manualOrderedGroups.get(i).getId()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapGroupLargeQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapGroupLargeQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c423d7eceba12622c5a55b0f1f07d8be101a732a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapGroupLargeQueryTest.java @@ -0,0 +1,103 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +public class LdapGroupLargeQueryTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule().additionalNumberOfUsers(5).additionnalNumberOfGroups(5).additionalNumberOfRoles(80); // the TestEnvironment creates groups for roles. Attention, stay under 80, there is a limitation in the query on 100 + + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule("camunda.ldap.pages.cfg.xml"); // pageSize = 3 in this configuration + + IdentityService identityService; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + identityService = engineRule.getIdentityService(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + @Test + public void testAllGroupsQuery() { + List listGroups = identityService.createGroupQuery().list(); + + // In this group, we expect more than a page size + // Attention, in the test environment, a Role is implemented by a groupOfNames. the groupQuery search for groups + // So the comparison must be done via the Roles name + assertThat(listGroups).hasSize(ldapTestEnvironment.getTotalNumberOfRolesCreated()); + } + + @Test + public void testPagesAllGroupsQuery() { + List listGroups = identityService.createGroupQuery().list(); + + assertThat(listGroups).hasSize(ldapTestEnvironment.getTotalNumberOfRolesCreated()); + + // ask 3 pages + for (int firstResult = 2; firstResult < 10; firstResult += 4) { + List listPages = identityService.createGroupQuery().listPage(firstResult, 5); + assertThat(listPages.size()).as("Maximum 5 results expected").isLessThanOrEqualTo(5); + + for (int i = 0; i < listPages.size(); i++) { + assertThat(listPages.get(i).getId()).isEqualTo(listGroups.get(firstResult + i).getId()); + assertThat(listPages.get(i).getName()).isEqualTo(listGroups.get(firstResult + i).getName()); + } + + } + } + + @Test + public void testQueryPaging() { + GroupQuery query = identityService.createGroupQuery(); + + assertThat(query.listPage(0, Integer.MAX_VALUE)).hasSize(86); + + // Verifying the un-paged results + assertThat(query.count()).isEqualTo(86); + assertThat(query.list()).hasSize(86); + + // Verifying paged results + assertThat(query.listPage(0, 2)).hasSize(2); + assertThat(query.listPage(2, 2)).hasSize(2); + assertThat(query.listPage(4, 3)).hasSize(3); + assertThat(query.listPage(85, 3)).hasSize(1); + assertThat(query.listPage(85, 1)).hasSize(1); + + // Verifying odd usages + assertThat(query.listPage(-1, -1)).hasSize(0); + assertThat(query.listPage(86, 2)).hasSize(0); // 86 is the last index with a result + assertThat(query.listPage(0, 87)).hasSize(86); // there are only 86 groups + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapGroupQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapGroupQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..026b033ecfd08b37652cb0e18602b5e28290a985 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapGroupQueryTest.java @@ -0,0 +1,361 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.authorization.Authorization.AUTH_TYPE_GRANT; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Resources.GROUP; +import static org.camunda.bpm.identity.ldap.util.LdapTestUtilities.checkPagingResults; +import static org.camunda.bpm.identity.ldap.util.LdapTestUtilities.testGroupPaging; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + + +public class LdapGroupQueryTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(); + + ProcessEngineConfiguration processEngineConfiguration; + IdentityService identityService; + AuthorizationService authorizationService; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + processEngineConfiguration = engineRule.getProcessEngineConfiguration(); + identityService = engineRule.getIdentityService(); + authorizationService = engineRule.getAuthorizationService(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + @Test + public void testCountGroups() { + // given + + // when + GroupQuery groupQuery = identityService.createGroupQuery(); + + // then + assertThat(groupQuery.listPage(0, Integer.MAX_VALUE).size()).isEqualTo(6); + assertThat(groupQuery.count()).isEqualTo(6); + } + + @Test + public void testQueryNoFilter() { + // given + + // when + List groupList = identityService.createGroupQuery().list(); + + // then + assertThat(groupList.size()).isEqualTo(6); + } + + @Test + public void testFilterByGroupId() { + // given + + // when + Group group = identityService.createGroupQuery().groupId("management").singleResult(); + + // then + assertThat(group).isNotNull(); + // validate result + assertThat(group.getId()).isEqualTo("management"); + assertThat(group.getName()).isEqualTo("management"); + } + + @Test + public void testFilterByNonexistingGroupId() { + // given + + // when + Group group = identityService.createGroupQuery().groupId("whatever").singleResult(); + + // then + assertThat(group).isNull(); + } + + @Test + public void testFilterByGroupIdIn() { + // given + + // when + List groups = identityService.createGroupQuery().groupIdIn("external", "management").list(); + + // then + assertThat(groups.size()).isEqualTo(2); + assertThat(groups).extracting("id").containsOnly("external", "management"); + } + + @Test + public void testFilterByGroupName() { + // given + + // when + Group group = identityService.createGroupQuery().groupName("management").singleResult(); + + // then + assertThat(group).isNotNull(); + // validate result + assertThat(group.getId()).isEqualTo("management"); + assertThat(group.getName()).isEqualTo("management"); + } + + @Test + public void testFilterByNonexistingGroupName() { + // given + + // when + Group group = identityService.createGroupQuery().groupName("whatever").singleResult(); + + // then + assertThat(group).isNull(); + } + + @Test + public void testFilterByGroupNameLikeTrailingWildcard() { + // given + + // when + Group group = identityService.createGroupQuery().groupNameLike("manage*").singleResult(); + + // then + assertThat(group).isNotNull(); + assertThat(group.getId()).isEqualTo("management"); + assertThat(group.getName()).isEqualTo("management"); + } + + @Test + public void testFilterByGroupNameLikeLeadingWildcard() { + // given + + // when + Group group = identityService.createGroupQuery().groupNameLike("*agement").singleResult(); + + // then + assertThat(group).isNotNull(); + assertThat(group.getId()).isEqualTo("management"); + assertThat(group.getName()).isEqualTo("management"); + } + + @Test + public void testFilterByGroupNameLikeLeadingAndTrailingWildCard() { + // given + + // when + Group group = identityService.createGroupQuery().groupNameLike("*ageme*").singleResult(); + + // then + assertThat(group).isNotNull(); + assertThat(group.getId()).isEqualTo("management"); + assertThat(group.getName()).isEqualTo("management"); + } + + @Test + public void testFilterByGroupNameLikeMIddleWildCard() { + // given + + // when + Group group = identityService.createGroupQuery().groupNameLike("man*nt").singleResult(); + + // then + assertThat(group).isNotNull(); + assertThat(group.getId()).isEqualTo("management"); + assertThat(group.getName()).isEqualTo("management"); + } + + @Test + public void testFilterByNonexistingGroupNameLike() { + // given + + // when + Group group = identityService.createGroupQuery().groupNameLike("what*").singleResult(); + + // then + assertThat(group).isNull(); + } + + @Test + public void testFilterByGroupNameLikeConvertFromDbWildcard() { + // given + + // when using the SQL wildcard (%) instead of LDAP (*) + Group group = identityService.createGroupQuery().groupNameLike("manage%").singleResult(); + + // then + assertThat(group).isNotNull(); + assertThat(group.getId()).isEqualTo("management"); + assertThat(group.getName()).isEqualTo("management"); + } + + @Test + public void testFilterByGroupMember() { + // given + + // when + List list = identityService.createGroupQuery().groupMember("daniel").list(); + + // then + assertThat(list).hasSize(3); + assertThat(list).extracting("name").containsOnly("development", "management", "all"); + } + + @Test + public void testFilterByNonexistingGroupMember() { + // given + + // when + List list = identityService.createGroupQuery().groupMember("non-existing").list(); + + // then + assertThat(list).isEmpty(); + } + + @Test + public void testFilterByGroupMemberSpecialCharacter() { + // given + + // when + List list = identityService.createGroupQuery().groupMember("david(IT)").list(); + + // then + assertThat(list).hasSize(2); + assertThat(list).extracting("name").containsOnly("sales", "all"); + } + + @Test + public void testFilterByGroupMemberPosix() { + // given + // by default the configuration does not use posix groups + LdapConfiguration ldapConfiguration = new LdapConfiguration(); + ldapConfiguration.setGroupMemberAttribute("memberUid"); + ldapConfiguration.setGroupSearchFilter("(someFilter)"); + + LdapIdentityProviderSession session = new LdapIdentityProviderSession(ldapConfiguration) { + // mock getDnForUser + protected String getDnForUser(String userId) { + return userId+ ", fullDn"; + } + }; + + // when I query for groups by group member + LdapGroupQuery query = new LdapGroupQuery(); + query.groupMember("jonny"); + + // then the full DN is requested. This is the default behavior. + String filter = session.getGroupSearchFilter(query); + assertThat(filter).isEqualTo("(&(someFilter)(memberUid=jonny, fullDn))"); + + // If I turn on posix groups + ldapConfiguration.setUsePosixGroups(true); + + // then the filter string does not contain the full DN for the + // user but the simple (unqualified) userId as provided in the query + filter = session.getGroupSearchFilter(query); + assertThat(filter).isEqualTo("(&(someFilter)(memberUid=jonny))"); + } + + + @Test + public void testPagination() { + testGroupPaging(identityService); + } + + @Test + public void testPaginationWithAuthenticatedUser() { + createGrantAuthorization(GROUP, "management", "oscar", READ); + createGrantAuthorization(GROUP, "consulting", "oscar", READ); + createGrantAuthorization(GROUP, "external", "oscar", READ); + + try { + processEngineConfiguration.setAuthorizationEnabled(true); + + identityService.setAuthenticatedUserId("oscar"); + + Set groupNames = new HashSet<>(); + List groups = identityService.createGroupQuery().listPage(0, 2); + assertThat(groups).hasSize(2); + checkPagingResults(groupNames, groups.get(0).getId(), groups.get(1).getId()); + + groups = identityService.createGroupQuery().listPage(2, 2); + assertThat(groups).hasSize(1); + assertThat(groupNames).doesNotContain(groups.get(0).getId()); + groupNames.add(groups.get(0).getId()); + + groups = identityService.createGroupQuery().listPage(4, 2); + assertThat(groups).hasSize(0); + + identityService.setAuthenticatedUserId("daniel"); + + groups = identityService.createGroupQuery().listPage(0, 2); + assertThat(groups).hasSize(0); + + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + + for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { + authorizationService.deleteAuthorization(authorization.getId()); + } + + } + } + + protected void createGrantAuthorization(Resource resource, String resourceId, String userId, Permission... permissions) { + Authorization authorization = createAuthorization(AUTH_TYPE_GRANT, resource, resourceId); + authorization.setUserId(userId); + for (Permission permission : permissions) { + authorization.addPermission(permission); + } + authorizationService.saveAuthorization(authorization); + } + + protected Authorization createAuthorization(int type, Resource resource, String resourceId) { + Authorization authorization = authorizationService.createNewAuthorization(type); + + authorization.setResource(resource); + if (resourceId != null) { + authorization.setResourceId(resourceId); + } + + return authorization; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapLoginCatchAuthenticationExceptionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapLoginCatchAuthenticationExceptionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5583eb4dd68b9d1cbb9a22fda5d87b056e67b58c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapLoginCatchAuthenticationExceptionTest.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +public class LdapLoginCatchAuthenticationExceptionTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule("camunda.ldap.disable.catch.authentication.exception.cfg.xml"); + + IdentityService identityService; + + @Before + public void setup() { + identityService = engineRule.getIdentityService(); + } + + @Test + public void shouldThrowExceptionOnFailedLogin() { + // given config passwordCheckCatchAuthenticationException=false + + // when + assertThatThrownBy(() -> identityService.checkPassword("roman", "wrongPW")) + .isInstanceOf(LdapAuthenticationException.class) + .hasMessage("Could not authenticate with LDAP server"); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapLoginTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapLoginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..dd453d0e2a74201fa65a80eec3a8e0fb6563299d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapLoginTest.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +/** + * @author Daniel Meyer + * + */ +public class LdapLoginTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(); + + IdentityService identityService; + + @Before + public void setup() { + identityService = engineRule.getIdentityService(); + } + + @Test + public void testLdapLoginSuccess() { + assertThat(identityService.checkPassword("roman", "roman")).isTrue(); + } + + @Test + public void testLdapLoginCapitalization() { + assertThat(identityService.checkPassword("Roman", "roman")).isTrue(); + } + + @Test + public void testLdapLoginFailure() { + assertThat(identityService.checkPassword("roman", "ro")).isFalse(); + assertThat(identityService.checkPassword("r", "roman")).isFalse(); + } + + @Test + public void testLdapLoginNullValues() { + assertThat(identityService.checkPassword(null, "roman")).isFalse(); + assertThat(identityService.checkPassword("roman", null)).isFalse(); + assertThat(identityService.checkPassword(null, null)).isFalse(); + } + + @Test + public void testLdapLoginEmptyPassword() { + assertThat(identityService.checkPassword("roman", "")).isTrue(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapQueryToleranceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapQueryToleranceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ff30deb8955b85df623bd9ac7ae7d89c54f0958a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapQueryToleranceTest.java @@ -0,0 +1,100 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.camunda.commons.testing.ProcessEngineLoggingRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; + + +/** + * @author Thorben Lindhauer + * + */ +public class LdapQueryToleranceTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule("invalid-id-attributes.cfg.xml"); + @Rule + public ProcessEngineLoggingRule loggingRule = new ProcessEngineLoggingRule().level(Level.ERROR).watch("org.camunda.bpm.identity.impl.ldap"); + + ProcessEngine processEngine; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + processEngine = engineRule.getProcessEngine(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + @Test + public void testNotReturnGroupsWithNullId() { + // given + // LdapTestEnvironment creates six roles (groupOfNames) by default; + // these won't return a group id, because they do not have the group id attribute + // defined in the ldap plugin config + // the plugin should not return such groups and instead log an error + + // when + List groups = processEngine.getIdentityService().createGroupQuery().list(); + long count = processEngine.getIdentityService().createGroupQuery().count(); + + // then + // groups with id null were not returned + assertThat(groups).hasSize(0); + assertThat(count).isEqualTo(0); + List filteredLog = loggingRule.getFilteredLog("LDAP-00004 LDAP group query returned a group with id null."); + assertThat(filteredLog).hasSize(12); // 2 queries * 6 roles (groupOfNames) + } + + @Test + public void testNotReturnUsersWithNullId() { + // given + // LdapTestEnvironment creates 12 users by default; + // these won't return a group id, because they do not have the group id attribute + // defined in the ldap plugin config + // the plugin should not return such groups and instead log an error + + // when + List users = processEngine.getIdentityService().createUserQuery().list(); + long count = processEngine.getIdentityService().createUserQuery().count(); + + // then + // groups with id null were not returned + assertThat(users).hasSize(0); + assertThat(count).isEqualTo(0); + List filteredLog = loggingRule.getFilteredLog("LDAP-00004 LDAP user query returned a user with id null."); + assertThat(filteredLog).hasSize(24); // 2 queries * 12 users + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapUserLargeQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapUserLargeQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b83bd9c5c9fdee58109fd668f909cc9081e0457d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapUserLargeQueryTest.java @@ -0,0 +1,101 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +public class LdapUserLargeQueryTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule().additionalNumberOfUsers(80).additionnalNumberOfGroups(5).additionalNumberOfRoles(5); // Attention, stay under 80, there is a limitation in the query on 100 + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule("camunda.ldap.pages.cfg.xml"); // pageSize = 3 in this configuration + + ProcessEngineConfiguration processEngineConfiguration; + IdentityService identityService; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + processEngineConfiguration = engineRule.getProcessEngineConfiguration(); + identityService = engineRule.getIdentityService(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + @Test + public void testAllUsersQuery() { + List listUsers = identityService.createUserQuery().list(); + + // In this group, we expect more than a page size + assertThat(listUsers).hasSize(ldapTestEnvironment.getTotalNumberOfUsersCreated()); + } + + @Test + public void testPagesAllUsersQuery() { + List listUsers = identityService.createUserQuery().list(); + + assertThat(listUsers).hasSize(ldapTestEnvironment.getTotalNumberOfUsersCreated()); + + // ask 3 pages + for (int firstResult = 0; firstResult < 10; firstResult += 4) { + List listPages = identityService.createUserQuery().listPage(firstResult, 5); + for (int i = 0; i < listPages.size(); i++) { + assertThat(listPages.get(i).getId()).isEqualTo(listUsers.get(firstResult + i).getId()); + assertThat(listPages.get(i).getLastName()).isEqualTo(listUsers.get(firstResult + i).getLastName()); + } + + } + } + + @Test + public void testQueryPaging() { + UserQuery query = identityService.createUserQuery(); + + assertThat(query.listPage(0, Integer.MAX_VALUE)).hasSize(92); + + // Verifying the un-paged results + assertThat(query.count()).isEqualTo(92); + assertThat(query.list()).hasSize(92); + + // Verifying paged results + assertThat(query.listPage(0, 2)).hasSize(2); + assertThat(query.listPage(2, 2)).hasSize(2); + assertThat(query.listPage(4, 3)).hasSize(3); + assertThat(query.listPage(91, 3)).hasSize(1); + assertThat(query.listPage(91, 1)).hasSize(1); + + // Verifying odd usages + assertThat(query.listPage(-1, -1)).hasSize(0); + assertThat(query.listPage(92, 2)).hasSize(0); // 92 is the last index with a result + assertThat(query.listPage(0, 93)).hasSize(92); // there are only 92 groups + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapUserQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapUserQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..45716b5437838ee0598170bd30040a3c8cc8cafc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/LdapUserQueryTest.java @@ -0,0 +1,674 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.camunda.bpm.engine.authorization.Authorization.AUTH_TYPE_GRANT; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Resources.USER; +import static org.camunda.bpm.identity.ldap.util.LdapTestUtilities.checkPagingResults; +import static org.camunda.bpm.identity.ldap.util.LdapTestUtilities.testUserPaging; +import static org.camunda.bpm.identity.ldap.util.LdapTestUtilities.testUserPagingWithMemberOfGroup; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +public class LdapUserQueryTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(); + + ProcessEngineConfiguration processEngineConfiguration; + IdentityService identityService; + AuthorizationService authorizationService; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + processEngineConfiguration = engineRule.getProcessEngineConfiguration(); + identityService = engineRule.getIdentityService(); + authorizationService = engineRule.getAuthorizationService(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + @Test + public void testCountUsers() { + // given + + // when + UserQuery userQuery = identityService.createUserQuery(); + + // then + assertThat(userQuery.listPage(0, Integer.MAX_VALUE)).hasSize(12); + assertThat(userQuery.count()).isEqualTo(12); + } + + @Test + public void testQueryNoFilter() { + // given + + // when + List result = identityService.createUserQuery().list(); + + // then + assertThat(result).hasSize(ldapTestEnvironment.getTotalNumberOfUsersCreated()); + } + + @Test + public void testFilterByUserId() { + // given + + // when + User user = identityService.createUserQuery().userId("oscar").singleResult(); + + // then + assertThat(user).isNotNull(); + + // validate user + assertThat(user.getId()).isEqualTo("oscar"); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByNonexistentUserId() { + // given + + // when + User user = identityService.createUserQuery().userId("non-existing").singleResult(); + + // then + assertThat(user).isNull(); + } + + @Test + public void testFilterByUserIdIn() { + // given + + // when + List users = identityService.createUserQuery().userIdIn("oscar", "monster").list(); + + // then + assertThat(users).hasSize(2); + assertThat(users).extracting("id").containsOnly("oscar", "monster"); + } + + @Test + public void testFilterByNonExistingUserIdIn() { + // given + + // when + List users = identityService.createUserQuery().userIdIn("oscar", "monster", "daniel", "non-existing").list(); + + // then + assertThat(users).isNotNull(); + assertThat(users).hasSize(3); + assertThat(users).extracting("id").containsOnly("oscar", "monster", "daniel"); + } + + @Test + public void testFilterByUserIdWithCapitalization() { + try { + // given + processEngineConfiguration.setAuthorizationEnabled(true); + identityService.setAuthenticatedUserId("Oscar"); + + // when + User user = identityService.createUserQuery().userId("Oscar").singleResult(); + + // then + assertThat(user).isNotNull(); + + // validate user + assertThat(user.getId()).isEqualTo("oscar"); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + } + } + + @Test + public void testFilterByFirstname() { + // given + + // when + User user = identityService.createUserQuery().userFirstName("Oscar").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + } + + @Test + public void testFilterByNonexistingFirstname() { + // given + + // when + User user = identityService.createUserQuery().userFirstName("non-existing").singleResult(); + + // then + assertThat(user).isNull(); + } + + @Test + public void testFilterByFirstnameLikeTrailingWildcard() { + // given + + // when + User user = identityService.createUserQuery().userFirstNameLike("Osc*").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + } + + @Test + public void testFilterByFirstnameLikeLeadingWildcard() { + // given + + // when + User user = identityService.createUserQuery().userFirstNameLike("*car").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + } + + @Test + public void testFilterByFirstnameLikeLeadingAndTrailingWildcard() { + // given + + // when + User user = identityService.createUserQuery().userFirstNameLike("*sca*").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + } + + @Test + public void testFilterByFirstnameLikeMiddleWildcard() { + // given + + // when + User user = identityService.createUserQuery().userFirstNameLike("O*ar").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + } + + @Test + public void testFilterByFirstnameLikeConvertFromDbWildcard() { + // given + + // when using the SQL wildcard (%) instead of LDAP (*) + User user = identityService.createUserQuery().userFirstNameLike("Osc%").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getFirstName()).isEqualTo("Oscar"); + } + + @Test + public void testFilterByNonexistingFirstnameLike() { + // given + + // when + User user = identityService.createUserQuery().userFirstNameLike("non-exist*").singleResult(); + + // then + assertThat(user).isNull(); + } + + @Test + public void testFilterByLastname() { + // given + + // when + User user = identityService.createUserQuery().userLastName("The Crouch").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + } + + @Test + public void testFilterByNonexistingLastname() { + // given + + // when + User user = identityService.createUserQuery().userLastName("non-existing").singleResult(); + + // then + assertThat(user).isNull(); + } + + @Test + public void testFilterByLastnameLikeTrailingWildcard() { + // given + + // when + User user = identityService.createUserQuery().userLastNameLike("The Cro*").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + } + + @Test + public void testFilterByLastnameLikeLeadingWildcard() { + // given + + // when + User user = identityService.createUserQuery().userLastNameLike("* Crouch").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + } + + @Test + public void testFilterByLastnameLikeLeadingAndTrailingWildcard() { + // given + + // when + User user = identityService.createUserQuery().userLastNameLike("* Cro*").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + } + + @Test + public void testFilterByLastnameLikeMiddleWildcard() { + // given + + // when + User user = identityService.createUserQuery().userLastNameLike("The *uch").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + } + + @Test + public void testFilterByNonexistingLastnameLike() { + // given + + // when + User user = identityService.createUserQuery().userLastNameLike("non-exist*").singleResult(); + + // then + assertThat(user).isNull(); + } + + @Test + public void testFilterByLastnameLikeConvertFromDbWildcard() { + // given + + // when using the SQL wildcard (%) instead of LDAP (*) + User user = identityService.createUserQuery().userLastNameLike("The Cro%").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getLastName()).isEqualTo("The Crouch"); + } + + @Test + public void testFilterByEmail() { + // given + + // when + User user = identityService.createUserQuery().userEmail("oscar@camunda.org").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByNonexistingEmail() { + // given + + // when + User user = identityService.createUserQuery().userEmail("non-exist").singleResult(); + + // then + assertThat(user).isNull(); + } + + @Test + public void testFilterByEmailLikeTrailingWildCard() { + // given + + // when + User user = identityService.createUserQuery().userEmailLike("oscar@*").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByEmailLikeLeadingWildCard() { + // given + + // when + User user = identityService.createUserQuery().userEmailLike("*car@camunda.org").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByEmailLikeLeadingAndTrailingWildCard() { + // given + + // when + User user = identityService.createUserQuery().userEmailLike("*car@*").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByEmailLikeMiddleWildCard() { + // given + + // when + User user = identityService.createUserQuery().userEmailLike("oscar@*.org").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByNonexistingEmailLike() { + // given + + // when + User user = identityService.createUserQuery().userEmailLike("non-exist*").singleResult(); + + // then + assertThat(user).isNull(); + } + + @Test + public void testFilterByEmailLikeConvertFromDbWildcard() { + // given + + // when using the SQL wildcard (%) instead of LDAP (*) + User user = identityService.createUserQuery().userEmailLike("oscar@%").singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByGroupId() { + // given + + // when + List result = identityService.createUserQuery().memberOfGroup("development").list(); + + // then + assertThat(result).hasSize(3); + assertThat(result).extracting("id").containsOnly("roman", "daniel", "oscar"); + } + + @Test + public void testFilterByGroupIdAndFirstname() { + // given + + // when + List result = identityService.createUserQuery() + .memberOfGroup("development") + .userFirstName("Oscar") + .list(); + + // then + assertThat(result).hasSize(1); + assertThat(result.get(0).getFirstName()).isEqualTo("Oscar"); + } + + @Test + public void testFilterByGroupIdAndId() { + // given + + // when + List result = identityService.createUserQuery() + .memberOfGroup("development") + .userId("oscar") + .list(); + + // then + assertThat(result).hasSize(1); + assertThat(result.get(0).getId()).isEqualTo("oscar"); + } + + @Test + public void testFilterByGroupIdAndLastname() { + // given + + // when + List result = identityService.createUserQuery() + .memberOfGroup("development") + .userLastName("The Crouch") + .list(); + + // then + assertThat(result).hasSize(1); + assertThat(result.get(0).getLastName()).isEqualTo("The Crouch"); + } + + @Test + public void testFilterByGroupIdAndEmail() { + // given + + // when + List result = identityService.createUserQuery() + .memberOfGroup("development") + .userEmail("oscar@camunda.org") + .list(); + + // then + assertThat(result).hasSize(1); + assertThat(result.get(0).getEmail()).isEqualTo("oscar@camunda.org"); + } + + @Test + public void testFilterByGroupIdAndEmailLike() { + // given + + // when + List result = identityService.createUserQuery() + .memberOfGroup("development") + .userEmailLike("*@camunda.org") + .list(); + + // then + assertThat(result).hasSize(3); + assertThat(result).extracting("email").containsOnly("daniel@camunda.org", "roman@camunda.org", "oscar@camunda.org"); + } + + @Test + public void testFilterByGroupIdAndIdForDnUsingCn() { + // given + + // when + List result = identityService.createUserQuery() + .memberOfGroup("external") + .userId("fozzie") + .list(); + + // then + assertThat(result).hasSize(1); + assertThat(result.get(0).getId()).isEqualTo("fozzie"); + } + + @Test + public void testAuthenticatedUserSeesThemselve() { + try { + // given + processEngineConfiguration.setAuthorizationEnabled(true); + identityService.setAuthenticatedUserId("oscar"); + + // when + User user = identityService.createUserQuery().singleResult(); + + // then + assertThat(user).isNotNull(); + assertThat(user.getId()).isEqualTo("oscar"); + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + } + } + + @Test + public void testNonexistingAuthenticatedUserDoesNotSeeThemselve() { + try { + // given + processEngineConfiguration.setAuthorizationEnabled(true); + identityService.setAuthenticatedUserId("non-existing"); + + // when + User user = identityService.createUserQuery().singleResult(); + + // then + assertThat(user).isNull(); + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + } + } + + @Test + public void testPagination() { + testUserPaging(identityService, ldapTestEnvironment); + } + + @Test + public void testPaginationWithMemberOfGroup() { + testUserPagingWithMemberOfGroup(identityService); + } + + @Test + public void testPaginationWithAuthenticatedUser() { + createGrantAuthorization(USER, "roman", "oscar", READ); + createGrantAuthorization(USER, "daniel", "oscar", READ); + createGrantAuthorization(USER, "monster", "oscar", READ); + createGrantAuthorization(USER, "ruecker", "oscar", READ); + + try { + processEngineConfiguration.setAuthorizationEnabled(true); + + identityService.setAuthenticatedUserId("oscar"); + + Set userNames = new HashSet<>(); + List users = identityService.createUserQuery().listPage(0, 2); + assertThat(users).hasSize(2); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().listPage(2, 2); + assertThat(users).hasSize(2); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().listPage(4, 2); + assertThat(users).hasSize(1); + assertThat(userNames).doesNotContain(users.get(0).getId()); + userNames.add(users.get(0).getId()); + + identityService.setAuthenticatedUserId("daniel"); + + users = identityService.createUserQuery().listPage(0, 2); + assertThat(users).hasSize(1); + + assertThat(users.get(0).getId()).isEqualTo("daniel"); + + users = identityService.createUserQuery().listPage(2, 2); + assertThat(users).hasSize(0); + + } finally { + processEngineConfiguration.setAuthorizationEnabled(false); + identityService.clearAuthentication(); + + for (Authorization authorization : authorizationService.createAuthorizationQuery().list()) { + authorizationService.deleteAuthorization(authorization.getId()); + } + + } + } + + @Test + public void testNativeQueryFail() { + assertThatThrownBy(() -> identityService.createNativeUserQuery()) + .isInstanceOf(BadUserRequestException.class) + .hasMessageContaining("Native user queries are not supported for LDAP"); + } + + protected void createGrantAuthorization(Resource resource, String resourceId, String userId, Permission... permissions) { + Authorization authorization = createAuthorization(AUTH_TYPE_GRANT, resource, resourceId); + authorization.setUserId(userId); + for (Permission permission : permissions) { + authorization.addPermission(permission); + } + authorizationService.saveAuthorization(authorization); + } + + protected Authorization createAuthorization(int type, Resource resource, String resourceId) { + Authorization authorization = authorizationService.createNewAuthorization(type); + + authorization.setResource(resource); + if (resourceId != null) { + authorization.setResourceId(resourceId); + } + + return authorization; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/ProcessDefinitionQueryWithCustomIdentityProviderTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/ProcessDefinitionQueryWithCustomIdentityProviderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..72da1dce83e8aad02000365c29a44fd7291b036f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/ProcessDefinitionQueryWithCustomIdentityProviderTest.java @@ -0,0 +1,107 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +@Deployment +public class ProcessDefinitionQueryWithCustomIdentityProviderTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule(); + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(); + + RepositoryService repositoryService; + + @Before + public void setup() { + repositoryService = engineRule.getRepositoryService(); + } + + @Test + public void test_shouldFindAllProcessesForCandidateUser() { + // given + + // when + List processDefinitions = repositoryService.createProcessDefinitionQuery().startableByUser("oscar").list(); + + // then + assertThat(processDefinitions).hasSize(2); + assertThat(processDefinitions.get(0).getKey()).isEqualTo("process1"); + assertThat(processDefinitions.get(1).getKey()).isEqualTo("process2"); + } + + @Test + public void test_shouldFindNoProcessesForCandidateUser() { + // given + + // when + List processDefinitions = repositoryService.createProcessDefinitionQuery().startableByUser("pepe").list(); + // then + assertThat(processDefinitions).hasSize(0); + } + + @Test + public void test_shouldFindAllProcessesForUserInCandidateGroup() { + // given + + // when + List processDefinitions = repositoryService.createProcessDefinitionQuery().startableByUser("david(IT)").list(); + + // then + assertThat(processDefinitions).hasSize(1); + assertThat(processDefinitions.get(0).getKey()).isEqualTo("process3"); + } + + @Test + public void test_shouldFindAllProcessesForCandidateUserInCandidateGroup() { + // given + + // when + List processDefinitions = repositoryService.createProcessDefinitionQuery().startableByUser("monster").list(); + + // then + assertThat(processDefinitions).hasSize(2); + assertThat(processDefinitions.get(0).getKey()).isEqualTo("process1"); + assertThat(processDefinitions.get(1).getKey()).isEqualTo("process3"); + } + + @Test + public void test_shouldFindNoDuplicateProcessesForCandidateUserInCandidateGroup() { + // given + + // when + List processDefinitions = repositoryService.createProcessDefinitionQuery().startableByUser("fozzie").list(); + + // then + assertThat(processDefinitions).hasSize(1); + assertThat(processDefinitions.get(0).getKey()).isEqualTo("process3"); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/posix/LdapPosixGroupQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/posix/LdapPosixGroupQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..430058692caa0c966d500c6f9647759ac1fa2f69 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/impl/ldap/posix/LdapPosixGroupQueryTest.java @@ -0,0 +1,98 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.impl.ldap.posix; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironment; +import org.camunda.bpm.identity.ldap.util.LdapTestEnvironmentRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + + +public class LdapPosixGroupQueryTest { + + @ClassRule + public static LdapTestEnvironmentRule ldapRule = new LdapTestEnvironmentRule().posix(true); + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule("posix.camunda.cfg.xml"); + + IdentityService identityService; + LdapTestEnvironment ldapTestEnvironment; + + @Before + public void setup() { + identityService = engineRule.getIdentityService(); + ldapTestEnvironment = ldapRule.getLdapTestEnvironment(); + } + + @Test + public void shouldFindGroupFilterByGroupIdWithoutMembers() { + // given + + // when + Group group = identityService.createGroupQuery().groupId("posix-group-without-members").singleResult(); + + // then + assertThat(group).isNotNull(); + assertThat(group.getId()).isEqualTo("posix-group-without-members"); + } + + @Test + public void shouldFindGroupFilterByGroupIdWithMembers() { + // given + + // when + Group group = identityService.createGroupQuery().groupId("posix-group-with-members").singleResult(); + + // then + assertThat(group).isNotNull(); + assertThat(group.getId()).isEqualTo("posix-group-with-members"); + } + + @Test + public void shouldFindUserFilterByMemberOfGroupWithoutMember() { + // given + + // when + List result = identityService.createUserQuery().memberOfGroup("posix-group-without-members").list(); + + // then + assertThat(result).hasSize(0); + } + + @Test + public void shouldFindUserFilterByMemberOfGroupWithMember() { + // given + + // when + List result = identityService.createUserQuery().memberOfGroup("posix-group-with-members").list(); + + // then + assertThat(result).hasSize(3); + assertThat(result).extracting("id").containsOnly("fozzie", "monster", "ruecker"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapPosixTestEnvironment.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapPosixTestEnvironment.java new file mode 100644 index 0000000000000000000000000000000000000000..0079e05d1e26f338dc01466651ca91dd33a0cb7c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapPosixTestEnvironment.java @@ -0,0 +1,92 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.ldap.util; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.directory.api.ldap.model.entry.Attribute; +import org.apache.directory.api.ldap.model.entry.DefaultModification; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.entry.Modification; +import org.apache.directory.api.ldap.model.entry.ModificationOperation; +import org.apache.directory.api.ldap.model.name.Dn; + +/** + *

+ * LDAP test setup for posix groups using apache directory

+ * + * @author Tom Crossland + */ +public class LdapPosixTestEnvironment extends LdapTestEnvironment { + + public LdapPosixTestEnvironment() { + super(); + // overwrite the name of the directory to use + workingDirectory = new File(System.getProperty("java.io.tmpdir") + "/ldap-posix-work"); + } + + @Override + public void init() throws Exception { + initializeDirectory(); + + // Enable POSIX groups in ApacheDS + Dn nis = new Dn("cn=nis,ou=schema"); + if (service.getAdminSession().exists(nis)) { + Entry entry = service.getAdminSession().lookup(nis); + Attribute nisDisabled = entry.get("m-disabled"); + if (null != nisDisabled && "TRUE".equalsIgnoreCase(nisDisabled.getString())) { + nisDisabled.remove("TRUE"); + nisDisabled.add("FALSE"); + List modifications = new ArrayList<>(); + modifications.add(new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, nisDisabled)); + service.getAdminSession().modify(nis, modifications); + service.shutdown(); + initializeDirectory(); // Note: This instantiates service again for schema modifications to take effect. + } + } + + startServer(); + + createGroup("office-berlin"); + createUserUid("daniel", "office-berlin", "Daniel", "Meyer", "daniel@camunda.org"); + + createGroup("people"); + createUserUid("ruecker", "people", "Bernd", "Ruecker", "ruecker@camunda.org"); + createUserUid("monster", "people", "Cookie", "Monster", "monster@camunda.org"); + createUserUid("fozzie", "people", "Bear", "Fozzie", "fozzie@camunda.org"); + + createGroup("groups"); + createPosixGroup("1", "posix-group-without-members"); + createPosixGroup("2", "posix-group-with-members", "fozzie", "monster", "ruecker"); + } + + protected void createPosixGroup(String gid, String name, String... memberUids) throws Exception { + Dn dn = new Dn("cn=" + name + ",ou=groups,o=camunda,c=org"); + if (!service.getAdminSession().exists(dn)) { + Entry entry = service.newEntry(dn); + entry.add("objectClass", "top", "posixGroup"); + entry.add("cn", name); + entry.add("gidNumber", gid); + for (String memberUid : memberUids) { + entry.add("memberUid", memberUid); + } + service.getAdminSession().add(entry); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestEnvironment.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestEnvironment.java new file mode 100644 index 0000000000000000000000000000000000000000..4bb57d989f37e35d644d5c6f69044073a4fbc39b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestEnvironment.java @@ -0,0 +1,419 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.ldap.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.io.FileUtils; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.directory.api.ldap.model.schema.SchemaManager; +import org.apache.directory.api.ldap.model.schema.registries.SchemaLoader; +import org.apache.directory.api.ldap.schema.extractor.SchemaLdifExtractor; +import org.apache.directory.api.ldap.schema.extractor.impl.DefaultSchemaLdifExtractor; +import org.apache.directory.api.ldap.schema.loader.LdifSchemaLoader; +import org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager; +import org.apache.directory.api.util.exception.Exceptions; +import org.apache.directory.server.constants.ServerDNConstants; +import org.apache.directory.server.core.DefaultDirectoryService; +import org.apache.directory.server.core.api.CacheService; +import org.apache.directory.server.core.api.DirectoryService; +import org.apache.directory.server.core.api.DnFactory; +import org.apache.directory.server.core.api.InstanceLayout; +import org.apache.directory.server.core.api.partition.Partition; +import org.apache.directory.server.core.api.schema.SchemaPartition; +import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex; +import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition; +import org.apache.directory.server.core.partition.ldif.LdifPartition; +import org.apache.directory.server.i18n.I18n; +import org.apache.directory.server.ldap.LdapServer; +import org.apache.directory.server.protocol.shared.transport.TcpTransport; +import org.apache.directory.server.xdbm.Index; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + *

+ * LDAP test setup using apache directory

+ * + * @author Bernd Ruecker + * @author Daniel Meyer + */ +public class LdapTestEnvironment { + + private final static Logger LOG = LoggerFactory.getLogger(LdapTestEnvironment.class.getName()); + + private static final String BASE_DN = "o=camunda,c=org"; + public static final String OFFICE_BERKELEY = "office-berkeley"; + + protected DirectoryService service; + protected LdapServer ldapService; + protected String configFilePath = "ldap.properties"; + protected File workingDirectory = new File(System.getProperty("java.io.tmpdir") + "/server-work"); + + private int numberOfUsersCreated = 0; + private int numberOfGroupsCreated = 0; + private int numberOfRolesCreated = 0; + + private int numberOfUsersCreatedInBerkeleyOffice = 0; + + public LdapTestEnvironment() { + } + + /** + * initialize the schema manager and add the schema partition to directory + * service + * + * @throws Exception if the schema LDIF files are not found on the classpath + */ + protected void initSchemaPartition() throws Exception { + InstanceLayout instanceLayout = service.getInstanceLayout(); + + File schemaPartitionDirectory = new File(instanceLayout.getPartitionsDirectory(), "schema"); + + // Extract the schema on disk (a brand new one) and load the registries + if (schemaPartitionDirectory.exists()) { + LOG.info("schema partition already exists, skipping schema extraction"); + } else { + SchemaLdifExtractor extractor = new DefaultSchemaLdifExtractor(instanceLayout.getPartitionsDirectory()); + extractor.extractOrCopy(); + } + + SchemaLoader loader = new LdifSchemaLoader(schemaPartitionDirectory); + SchemaManager schemaManager = new DefaultSchemaManager(loader); + + // We have to load the schema now, otherwise we won't be able + // to initialize the Partitions, as we won't be able to parse + // and normalize their suffix Dn + schemaManager.loadAllEnabled(); + + List errors = schemaManager.getErrors(); + + if (!errors.isEmpty()) { + throw new Exception(I18n.err(I18n.ERR_317, Exceptions.printErrors(errors))); + } + + service.setSchemaManager(schemaManager); + + // Init the LdifPartition with schema + LdifPartition schemaLdifPartition = new LdifPartition(schemaManager, service.getDnFactory()); + schemaLdifPartition.setPartitionPath(schemaPartitionDirectory.toURI()); + + // The schema partition + SchemaPartition schemaPartition = new SchemaPartition(schemaManager); + schemaPartition.setWrappedPartition(schemaLdifPartition); + service.setSchemaPartition(schemaPartition); + } + + /** + * Initialize the server. It creates the partition, adds the index, and + * injects the context entries for the created partitions. + * + * @throws Exception if there were some problems while initializing the system + */ + protected void initializeDirectory() throws Exception { + + workingDirectory.mkdirs(); + + service = new DefaultDirectoryService(); + InstanceLayout il = new InstanceLayout(workingDirectory); + service.setInstanceLayout(il); + + CacheService cacheService = new CacheService(); + cacheService.initialize(service.getInstanceLayout()); + service.setCacheService(cacheService); + + initSchemaPartition(); + + // then the system partition + // this is a MANDATORY partition + // DO NOT add this via addPartition() method, trunk code complains about duplicate partition + // while initializing + JdbmPartition systemPartition = new JdbmPartition(service.getSchemaManager(), service.getDnFactory()); + systemPartition.setId("system"); + systemPartition.setPartitionPath(new File(service.getInstanceLayout().getPartitionsDirectory(), systemPartition.getId()).toURI()); + systemPartition.setSuffixDn(new Dn(ServerDNConstants.SYSTEM_DN)); + systemPartition.setSchemaManager(service.getSchemaManager()); + + // mandatory to call this method to set the system partition + // Note: this system partition might be removed from trunk + service.setSystemPartition(systemPartition); + + // Disable the ChangeLog system + service.getChangeLog().setEnabled(false); + service.setDenormalizeOpAttrsEnabled(true); + + Partition camundaPartition = addPartition("camunda", BASE_DN, service.getDnFactory()); + addIndex(camundaPartition, "objectClass", "ou", "uid"); + + service.startup(); + + // Create the root entry + if (!service.getAdminSession().exists(camundaPartition.getSuffixDn())) { + Dn dn = new Dn(BASE_DN); + Entry entry = service.newEntry(dn); + entry.add("objectClass", "top", "domain", "extensibleObject"); + entry.add("dc", "camunda"); + service.getAdminSession().add(entry); + } + } + + /** + * starts the LdapServer + * + * @throws Exception + */ + public void startServer() throws Exception { + ldapService = new LdapServer(); + Properties properties = loadTestProperties(); + String port = properties.getProperty("ldap.server.port"); + ldapService.setTransports(new TcpTransport(Integer.parseInt(port))); + ldapService.setDirectoryService(service); + ldapService.start(); + } + + public void init() throws Exception { + /// create a simple test + init(0,0,0); + } + + /** + * create a specific test case. Test creates a minimum users/groups/roles but aditionnal users can be added to reach this number. + * @param additionalNumberOfUsers add this number of user. + * @param additionnalNumberOfGroups add this number of groups + * @param additionalNumberOfRoles add this number of roles + * @throws Exception + */ + public void init(int additionalNumberOfUsers, int additionnalNumberOfGroups, int additionalNumberOfRoles) throws Exception { + initializeDirectory(); + startServer(); + + createGroup("office-berlin"); + + String dnRoman = createUserUid("roman", "office-berlin", "Roman", "Smirnov", "roman@camunda.org"); + String dnRobert = createUserUid("robert", "office-berlin", "Robert", "Gimbel", "robert@camunda.org"); + String dnDaniel = createUserUid("daniel", "office-berlin", "Daniel", "Meyer", "daniel@camunda.org"); + String dnGonzo = createUserUid("gonzo", "office-berlin", "Gonzo", "The Great", "gonzo@camunda.org"); + String dnRowlf = createUserUid("rowlf", "office-berlin", "Rowlf", "The Dog", "rowlf@camunda.org"); + String dnPepe = createUserUid("pepe", "office-berlin", "Pepe", "The King Prawn", "pepe@camunda.org"); + String dnRizzo = createUserUid("rizzo", "office-berlin", "Rizzo", "The Rat", "rizzo@camunda.org"); + + createGroup("office-london"); + + String dnOscar = createUserUid("oscar", "office-london", "Oscar", "The Crouch", "oscar@camunda.org"); + String dnMonster = createUserUid("monster", "office-london", "Cookie", "Monster", "monster@camunda.org"); + + createGroup("office-home"); + + // Doesn't work using backslashes, end up with two uid attributes + // See https://issues.apache.org/jira/browse/DIRSERVER-1442 + String dnDavid = createUserUid("david(IT)", "office-home", "David", "Howe\\IT\\", "david@camunda.org"); + + String dnRuecker = createUserUid("ruecker", "office-home", "Bernd", "Ruecker", "ruecker@camunda.org"); + + createGroup("office-external"); + + String dnFozzie = createUserCN("fozzie", "office-external", "Bear", "Fozzie", "fozzie@camunda.org"); + + createRole("management", dnRuecker, dnRobert, dnDaniel); + createRole("development", dnRoman, dnDaniel, dnOscar); + createRole("consulting", dnRuecker); + createRole("sales", dnRuecker, dnMonster, dnDavid); + createRole("external", dnFozzie); + createRole("all", dnRuecker, dnRobert, dnDaniel, dnRoman, dnOscar, dnMonster, dnDavid, dnFozzie, dnGonzo, dnRowlf, dnPepe, dnRizzo); + + // create a large number of users + createGroup(OFFICE_BERKELEY); + + // record more than a page in this group + for (int i = 1; i <= additionalNumberOfUsers; i++) { + String lastName = "fisher" + String.format("%04d", i); + createUserUid("jan.fisher." + lastName, + OFFICE_BERKELEY, + "jan", + lastName, + "jan.fisher" + lastName + "@camunda.org"); + } + + // Create a lot of groups + for (int i = 1; i <= additionnalNumberOfGroups; i++) { + String groupName = "Paris" + String.format("%04d", i); + createGroup(groupName); + } + + // Create a lot of roles + for (int i = 1; i <= additionalNumberOfRoles; i++) { + String roleName = "Support" + String.format("%04d", i); + createRole(roleName, dnFozzie); + } + + } + + public int getTotalNumberOfUsersCreated() { + return numberOfUsersCreated; + } + + public int getTotalNumberOfGroupsCreated() { + return numberOfGroupsCreated; + } + + public int getTotalNumberOfRolesCreated() { + return numberOfRolesCreated; + } + + public int getTotalNumberOfUserInOfficeBerkeley() { + return numberOfUsersCreatedInBerkeleyOffice; + } + + protected String createUserUid(String user, String group, String firstname, String lastname, String email) throws Exception { + Dn dn = new Dn("uid=" + user + ",ou=" + group + ",o=camunda,c=org"); + createUser(user, firstname, lastname, email, dn); + return dn.getNormName(); + } + + protected String createUserCN(String user, String group, String firstname, String lastname, String email) throws Exception { + Dn dn = new Dn("cn=" + lastname + "\\," + firstname + ",ou=" + group + ",o=camunda,c=org"); + createUser(user, firstname, lastname, email, dn); + return dn.getNormName(); + } + + protected void createUser(String user, String firstname, String lastname, + String email, Dn dn) throws Exception { + if (!service.getAdminSession().exists(dn)) { + Entry entry = service.newEntry(dn); + entry.add("objectClass", "top", "person", "inetOrgPerson"); //, "extensibleObject"); //make extensible to allow for the "memberOf" field + entry.add("uid", user); + entry.add("cn", firstname); + entry.add("sn", lastname); + entry.add("mail", email); + entry.add("userPassword", user.getBytes(StandardCharsets.UTF_8)); + service.getAdminSession().add(entry); + System.out.println("created entry: " + dn.getNormName()); + numberOfUsersCreated++; + } + } + + /** + * A role is implemented by a LDAP organizationalUnit + * + * @param name group to create + * @throws Exception in case of error + */ + public void createGroup(String name) throws Exception { + Dn dn = new Dn("ou=" + name + ",o=camunda,c=org"); + if (!service.getAdminSession().exists(dn)) { + Entry entry = service.newEntry(dn); + entry.add("objectClass", "top", "organizationalUnit"); + entry.add("ou", name); + service.getAdminSession().add(entry); + System.out.println("created entry: " + dn.getNormName()); + numberOfGroupsCreated++; + } + } + + /** + * A role is implemented by a LDAP groupOfNames + * + * @param roleName role to create (cn) + * @param users users members of this role + * @throws Exception in case of error + */ + protected void createRole(String roleName, String... users) throws Exception { + Dn dn = new Dn("ou=" + roleName + ",o=camunda,c=org"); + if (!service.getAdminSession().exists(dn)) { + Entry entry = service.newEntry(dn); + entry.add("objectClass", "top", "groupOfNames"); + entry.add("cn", roleName); + for (String user : users) { + entry.add("member", user); + } + service.getAdminSession().add(entry); + numberOfRolesCreated++; + } + } + + /** + * Add a new partition to the server + * + * @param partitionId The partition Id + * @param partitionDn The partition DN + * @param dnFactory the DN factory + * @return The newly added partition + * @throws Exception If the partition can't be added + */ + protected Partition addPartition(String partitionId, String partitionDn, DnFactory dnFactory) throws Exception { + // Create a new partition with the given partition id + JdbmPartition partition = new JdbmPartition(service.getSchemaManager(), dnFactory); + partition.setId(partitionId); + partition.setPartitionPath(new File(service.getInstanceLayout().getPartitionsDirectory(), partitionId).toURI()); + partition.setSuffixDn(new Dn(partitionDn)); + service.addPartition(partition); + + return partition; + } + + /** + * Add a new set of index on the given attributes + * + * @param partition The partition on which we want to add index + * @param attrs The list of attributes to index + */ + protected void addIndex(Partition partition, String... attrs) { + // Index some attributes on the apache partition + Set> indexedAttributes = new HashSet<>(); + + for (String attribute : attrs) { + indexedAttributes.add(new JdbmIndex(attribute, false)); + } + + ((JdbmPartition) partition).setIndexedAttributes(indexedAttributes); + } + + public void shutdown() { + try { + ldapService.stop(); + service.shutdown(); + if (workingDirectory.exists()) { + FileUtils.deleteDirectory(workingDirectory); + } + } catch (Exception e) { + LOG.error("exception while shutting down ldap", e); + } + } + + protected Properties loadTestProperties() throws IOException { + Properties properties = new Properties(); + File file = IoUtil.getFile(configFilePath); + FileInputStream propertiesStream = null; + try { + propertiesStream = new FileInputStream(file); + properties.load(propertiesStream); + } finally { + IoUtil.closeSilently(propertiesStream); + } + return properties; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestEnvironmentRule.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestEnvironmentRule.java new file mode 100644 index 0000000000000000000000000000000000000000..b87f947283a154d12409060f05b4211384eebc5c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestEnvironmentRule.java @@ -0,0 +1,80 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.ldap.util; + +import org.junit.rules.ExternalResource; + +public class LdapTestEnvironmentRule extends ExternalResource { + + LdapTestEnvironment ldapTestEnvironment; + + int additionalNumberOfUsers = 0; + int additionnalNumberOfGroups = 0; + int additionalNumberOfRoles = 0; + boolean posix = false; + + @Override + protected void before() throws Exception { + if(posix) { + setupPosix(); + } else { + setupLdap(); + } + } + + @Override + protected void after() { + if (ldapTestEnvironment != null) { + ldapTestEnvironment.shutdown(); + ldapTestEnvironment = null; + } + } + + private void setupLdap() throws Exception { + ldapTestEnvironment = new LdapTestEnvironment(); + ldapTestEnvironment.init(additionalNumberOfUsers, additionnalNumberOfGroups, additionalNumberOfRoles); + } + + public void setupPosix() throws Exception { + ldapTestEnvironment = new LdapPosixTestEnvironment(); + ldapTestEnvironment.init(); + } + + public LdapTestEnvironmentRule additionalNumberOfUsers(int additionalNumberOfUsers) { + this.additionalNumberOfUsers = additionalNumberOfUsers; + return this; + } + + public LdapTestEnvironmentRule additionnalNumberOfGroups(int additionnalNumberOfGroups) { + this.additionnalNumberOfGroups = additionnalNumberOfGroups; + return this; + } + + public LdapTestEnvironmentRule additionalNumberOfRoles(int additionalNumberOfRoles) { + this.additionalNumberOfRoles = additionalNumberOfRoles; + return this; + } + + public LdapTestEnvironmentRule posix(boolean posix) { + this.posix = posix; + return this; + } + + public LdapTestEnvironment getLdapTestEnvironment() { + return ldapTestEnvironment; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestUtilities.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestUtilities.java new file mode 100644 index 0000000000000000000000000000000000000000..8a144853c4d03a5626f3b438e06bd5b7e187f420 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/java/org/camunda/bpm/identity/ldap/util/LdapTestUtilities.java @@ -0,0 +1,107 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.identity.ldap.util; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertNotSame; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.User; + +/** + * Contains some test utilities to test the Ldap plugin. + * + * @author Christopher Zell + */ +public final class LdapTestUtilities { + + public static void checkPagingResults(Set results, String result1, String result2) { + assertNotSame(result1, result2); + assertFalse(results.contains(result1)); + results.add(result1); + assertFalse(results.contains(result2)); + results.add(result2); + } + + public static void testGroupPaging(IdentityService identityService) { + Set groupNames = new HashSet(); + List groups = identityService.createGroupQuery().listPage(0, 2); + assertEquals(2, groups.size()); + checkPagingResults(groupNames, groups.get(0).getId(), groups.get(1).getId()); + + groups = identityService.createGroupQuery().listPage(2, 2); + assertEquals(2, groups.size()); + checkPagingResults(groupNames, groups.get(0).getId(), groups.get(1).getId()); + + groups = identityService.createGroupQuery().listPage(4, 2); + assertEquals(2, groups.size()); + assertFalse(groupNames.contains(groups.get(0).getId())); + groupNames.add(groups.get(0).getId()); + + groups = identityService.createGroupQuery().listPage(6, 2); + assertEquals(0, groups.size()); + } + + public static void testUserPaging(IdentityService identityService, LdapTestEnvironment ldapTestEnvironment) { + Set userNames = new HashSet(); + List users = identityService.createUserQuery().listPage(0, 2); + assertEquals(2, users.size()); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().listPage(2, 2); + assertEquals(2, users.size()); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().listPage(4, 2); + assertEquals(2, users.size()); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().listPage(6, 2); + assertEquals(2, users.size()); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + // over the page. + users = identityService.createUserQuery().listPage(ldapTestEnvironment.getTotalNumberOfUsersCreated() + 1, 2); + assertEquals(0, users.size()); + } + + public static void testUserPagingWithMemberOfGroup(IdentityService identityService) { + Set userNames = new HashSet(); + List users = identityService.createUserQuery().memberOfGroup("all").listPage(0, 2); + assertEquals(2, users.size()); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().memberOfGroup("all").listPage(2, 2); + assertEquals(2, users.size()); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().memberOfGroup("all").listPage(4, 2); + assertEquals(2, users.size()); + checkPagingResults(userNames, users.get(0).getId(), users.get(1).getId()); + + users = identityService.createUserQuery().memberOfGroup("all").listPage(11, 2); + assertEquals(1, users.size()); + assertFalse(userNames.contains(users.get(0).getId())); + + users = identityService.createUserQuery().memberOfGroup("all").listPage(12, 2); + assertEquals(0, users.size()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..0657fb5f95c4a40516e907e49dadb0031dfe0340 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.cfg.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.disable.authorization.check.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.disable.authorization.check.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..8f415c0d2a10136a0202ad36809532f030782706 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.disable.authorization.check.cfg.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.disable.catch.authentication.exception.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.disable.catch.authentication.exception.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..e3323bef3e9bca6c2ceeb78152fcf5e1ada92b45 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.disable.catch.authentication.exception.cfg.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.enable.sort.control.support.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.enable.sort.control.support.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..19f482c0dfdb77097e26baa5a90d9187df0e92ba --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.enable.sort.control.support.cfg.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.pages.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.pages.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..7b7c96b759496312931e5739e5644f71ef79113d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/camunda.ldap.pages.cfg.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/invalid-id-attributes.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/invalid-id-attributes.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..189633d4e33b6de5c800722921554aa6a908dd3d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/invalid-id-attributes.cfg.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/ldap.properties b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/ldap.properties new file mode 100644 index 0000000000000000000000000000000000000000..0417466c77b4ac002f7c52c51d34b62f95a18bc9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/ldap.properties @@ -0,0 +1 @@ +ldap.server.port=${ldap.server.port} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/logback-test.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/logback-test.xml new file mode 100644 index 0000000000000000000000000000000000000000..d6c9b544a6573f5d763470b9924f72206143733a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/logback-test.xml @@ -0,0 +1,28 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/org/camunda/bpm/identity/impl/ldap/ProcessDefinitionQueryWithCustomIdentityProviderTest.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/org/camunda/bpm/identity/impl/ldap/ProcessDefinitionQueryWithCustomIdentityProviderTest.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..0e5e3f8e0c3ea9b49ea4fd3fbdae40116425805a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/org/camunda/bpm/identity/impl/ldap/ProcessDefinitionQueryWithCustomIdentityProviderTest.bpmn20.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/posix.camunda.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/posix.camunda.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..779cb6be45fa235d1a32cdbb6e8c571ddee1dbb5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/identity-ldap/src/test/resources/posix.camunda.cfg.xml @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..b4b86472ac5299003648bf0429c6eebfb3ce69a5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/pom.xml @@ -0,0 +1,75 @@ + + 4.0.0 + + + org.camunda.bpm + camunda-database-settings + ../database + 7.24.0-SNAPSHOT + + + camunda-engine-plugins + pom + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + Camunda Platform - engine plugins + + + identity-ldap + connect-plugin + spin-plugin + + + + + + org.camunda.bpm + camunda-core-internal-dependencies + ${project.version} + import + pom + + + com.sun.xml.bind + jaxb-impl + ${version.xml.jaxb-impl} + + + + + + + org.camunda.bpm + camunda-engine + provided + + + + com.h2database + h2 + test + + + + junit + junit + test + + + + org.assertj + assertj-core + test + + + + org.camunda.commons + camunda-commons-testing + test + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..c1af4e5490263c66db8afa2d386bfb6159a4bb87 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/pom.xml @@ -0,0 +1,153 @@ + + + + + camunda-engine-plugins + org.camunda.bpm + 7.24.0-SNAPSHOT + + 4.0.0 + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + camunda-engine-plugin-spin + Camunda Platform - engine plugins - spin + + + + + org.camunda.spin + camunda-spin-core + + + + org.camunda.bpm.dmn + camunda-engine-feel-scala + provided + + + + org.camunda.bpm + camunda-engine + tests + test + ${project.version} + + + + org.camunda.spin + camunda-spin-dataformat-json-jackson + test + + + + org.camunda.spin + camunda-spin-dataformat-xml-dom + test + + + + org.assertj + assertj-core + test + + + + ch.qos.logback + logback-classic + test + + + + org.slf4j + jcl-over-slf4j + test + + + + org.slf4j + jul-to-slf4j + test + + + + org.apache.groovy + groovy-jsr223 + test + + + + org.graalvm.js + js + test + + + + org.graalvm.js + js-scriptengine + test + + + + org.camunda.bpm.model + camunda-bpmn-model + test + + + + org.skyscreamer + jsonassert + test + + + + org.python + jython + test + + + + org.jruby + jruby-complete + test + + + + org.mockito + mockito-core + test + + + org.hamcrest + hamcrest-core + + + + + + org.camunda.commons + camunda-commons-testing + test + + + + com.sun.xml.bind + jaxb-impl + test + + + + + + + maven-surefire-plugin + + true + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/FallbackSpinObjectValueSerializer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/FallbackSpinObjectValueSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..d68c08f8baa66a008581c01834f50999aa20b2da --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/FallbackSpinObjectValueSerializer.java @@ -0,0 +1,67 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import org.camunda.bpm.engine.impl.variable.serializer.AbstractObjectValueSerializer; + +/** + * @author Thorben Lindhauer + */ +public class FallbackSpinObjectValueSerializer extends AbstractObjectValueSerializer { + + private final static SpinPluginLogger LOG = SpinPluginLogger.LOGGER; + + public static final String DESERIALIZED_OBJECTS_EXCEPTION_MESSAGE = "Fallback serializer cannot handle deserialized objects"; + + protected String serializationFormat; + + public FallbackSpinObjectValueSerializer(String serializationFormat) { + super(serializationFormat); + this.serializationFormat = serializationFormat; + } + + @Override + public String getName() { + return "spin://" + serializationFormat; + } + + @Override + protected String getTypeNameForDeserialized(Object deserializedObject) { + throw LOG.fallbackSerializerCannotDeserializeObjects(); + } + + @Override + protected byte[] serializeToByteArray(Object deserializedObject) throws Exception { + throw LOG.fallbackSerializerCannotDeserializeObjects(); + } + + @Override + protected Object deserializeFromByteArray(byte[] object, String objectTypeName) throws Exception { + throw LOG.fallbackSerializerCannotDeserializeObjects(); + } + + @Override + protected boolean isSerializationTextBased() { + return true; + } + + @Override + protected boolean canSerializeValue(Object value) { + throw LOG.fallbackSerializerCannotDeserializeObjects(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/JsonValueSerializer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/JsonValueSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..2ca3c52cb724636964a9a0cb0495bcd5fa61211e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/JsonValueSerializer.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import org.camunda.bpm.engine.impl.variable.serializer.ValueFields; +import org.camunda.bpm.engine.variable.impl.value.UntypedValueImpl; +import org.camunda.spin.DataFormats; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.variable.SpinValues; +import org.camunda.spin.plugin.variable.type.JsonValueType; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.plugin.variable.value.impl.JsonValueImpl; +import org.camunda.spin.spi.DataFormat; + +/** + * @author Roman Smirnov + * + */ +public class JsonValueSerializer extends SpinValueSerializer { + + public JsonValueSerializer(DataFormat dataFormat) { + super(SpinValueType.JSON, dataFormat, JsonValueType.TYPE_NAME); + } + + public JsonValueSerializer() { + this(DataFormats.json()); + } + + public SpinValue convertToTypedValue(UntypedValueImpl untypedValue) { + return SpinValues.jsonValue((SpinJsonNode) untypedValue.getValue()).create(); + } + + protected SpinValue createDeserializedValue(Object deserializedObject, String serializedStringValue, ValueFields valueFields, boolean asTransientValue) { + SpinJsonNode value = (SpinJsonNode) deserializedObject; + JsonValueImpl jsonValue = new JsonValueImpl(value, serializedStringValue, dataFormat.getName(), true); + jsonValue.setTransient(asTransientValue); + return jsonValue; + } + + protected SpinValue createSerializedValue(String serializedStringValue, ValueFields valueFields, boolean asTransientValue) { + JsonValueImpl jsonValue = new JsonValueImpl(serializedStringValue, serializationDataFormat); + jsonValue.setTransient(asTransientValue); + return jsonValue; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinBpmPlatformPlugin.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinBpmPlatformPlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..8992e49618f27f911a7902b3108b57ccb4326f12 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinBpmPlatformPlugin.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import java.util.List; + +import org.camunda.bpm.application.AbstractProcessApplication; +import org.camunda.bpm.application.ProcessApplicationInterface; +import org.camunda.bpm.container.impl.plugin.BpmPlatformPlugin; +import org.camunda.bpm.engine.impl.variable.serializer.DefaultVariableSerializers; +import org.camunda.bpm.engine.impl.variable.serializer.TypedValueSerializer; +import org.camunda.bpm.engine.impl.variable.serializer.VariableSerializers; +import org.camunda.spin.DataFormats; + +/** + * @author Thorben Lindhauer + * + */ +public class SpinBpmPlatformPlugin implements BpmPlatformPlugin { + + private static final SpinPluginLogger LOG = SpinPluginLogger.LOGGER; + + @Override + public void postProcessApplicationDeploy(ProcessApplicationInterface processApplication) { + ProcessApplicationInterface rawPa = processApplication.getRawObject(); + if (rawPa instanceof AbstractProcessApplication) { + initializeVariableSerializers((AbstractProcessApplication) rawPa); + } + else { + LOG.logNoDataFormatsInitiailized("process application data formats", "process application is not a sub class of " + AbstractProcessApplication.class.getName()); + } + } + + protected void initializeVariableSerializers(AbstractProcessApplication abstractProcessApplication) { + VariableSerializers paVariableSerializers = abstractProcessApplication.getVariableSerializers(); + + if (paVariableSerializers == null) { + paVariableSerializers = new DefaultVariableSerializers(); + abstractProcessApplication.setVariableSerializers(paVariableSerializers); + } + + for (TypedValueSerializer serializer : lookupSpinSerializers(abstractProcessApplication.getProcessApplicationClassloader())) { + paVariableSerializers.addSerializer(serializer); + } + } + + protected List> lookupSpinSerializers(ClassLoader classLoader) { + + DataFormats paDataFormats = new DataFormats(); + paDataFormats.registerDataFormats(classLoader); + + // does not create PA-local serializers for native Spin values; + // this is still an open feature CAM-5246 + return SpinVariableSerializers.createObjectValueSerializers(paDataFormats); + } + + @Override + public void postProcessApplicationUndeploy(ProcessApplicationInterface processApplication) { + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinConfiguration.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..3d997c048cafb82488413902fda0c8508f963cf0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinConfiguration.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import org.camunda.bpm.engine.impl.cfg.AbstractProcessEnginePlugin; + +/** + * Java Bean holding Spin configuration properties. + */ +public class SpinConfiguration extends AbstractProcessEnginePlugin { + + protected static final String XXE_PROPERTY = "xxe-processing"; + protected static final String SP_PROPERTY = "secure-processing"; + + protected boolean enableXxeProcessing = false; + protected boolean enableSecureXmlProcessing = true; + + public boolean isEnableXxeProcessing() { + return enableXxeProcessing; + } + + public void setEnableXxeProcessing(boolean enableXxeProcessing) { + this.enableXxeProcessing = enableXxeProcessing; + } + + public boolean isEnableSecureXmlProcessing() { + return enableSecureXmlProcessing; + } + + public void setEnableSecureXmlProcessing(boolean enableSecureXmlProcessing) { + this.enableSecureXmlProcessing = enableSecureXmlProcessing; + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinFallbackSerializerFactory.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinFallbackSerializerFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..f9521b13643459565820b035441d4ae73819a295 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinFallbackSerializerFactory.java @@ -0,0 +1,55 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.camunda.bpm.engine.impl.variable.serializer.TypedValueSerializer; +import org.camunda.bpm.engine.impl.variable.serializer.VariableSerializerFactory; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Thorben Lindhauer + * + */ +public class SpinFallbackSerializerFactory implements VariableSerializerFactory { + + public static final Pattern SPIN_SERIALIZER_NAME_PATTERN = Pattern.compile("spin://(.*)"); + + public TypedValueSerializer getSerializer(String serializerName) { + Matcher matcher = SPIN_SERIALIZER_NAME_PATTERN.matcher(serializerName); + if (matcher.matches()) { + String serializationFormat = matcher.group(1); + return new FallbackSpinObjectValueSerializer(serializationFormat); + } + else { + return null; + } + } + + public TypedValueSerializer getSerializer(TypedValue value) { + if (value instanceof ObjectValue) { + ObjectValue objectValue = (ObjectValue) value; + if (objectValue.getSerializationDataFormat() != null && !objectValue.isDeserialized()) { + return new FallbackSpinObjectValueSerializer(objectValue.getSerializationDataFormat()); + } + } + return null; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinFunctions.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinFunctions.java new file mode 100644 index 0000000000000000000000000000000000000000..13de30432b237123ba1664e8b951d208390caf88 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinFunctions.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +/** + * A FunctionMapper which resolves the Spin functions for Expression Language. + * + *

Lazy loading: This implementation supports lazy loading: the Java Methods + * are loaded upon the first request.

+ * + *

Caching: once the methods are loaded, they are cached in a Map for efficient + * retrieval.

+ * + * @author Daniel Meyer + * + */ +public class SpinFunctions { + public static final String S = "S"; + public static final String XML = "XML"; + public static final String JSON = "JSON"; +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinObjectValueSerializer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinObjectValueSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..417bea898fbb1e2207884acff9a8519b41e18292 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinObjectValueSerializer.java @@ -0,0 +1,126 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; + +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.context.Context; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.impl.variable.serializer.AbstractObjectValueSerializer; +import org.camunda.bpm.engine.impl.variable.serializer.TypedValueSerializer; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.spin.DeserializationTypeValidator; +import org.camunda.spin.spi.DataFormat; +import org.camunda.spin.spi.DataFormatMapper; +import org.camunda.spin.spi.DataFormatReader; +import org.camunda.spin.spi.DataFormatWriter; + +/** + * Implementation of a {@link TypedValueSerializer} for {@link ObjectValue ObjectValues} using a + * Spin-provided {@link DataFormat} to serialize and deserialize java objects. + * + * @author Daniel Meyer + * + */ +public class SpinObjectValueSerializer extends AbstractObjectValueSerializer { + + protected String name; + protected DataFormat dataFormat; + protected DeserializationTypeValidator validator; + + public SpinObjectValueSerializer(String name, DataFormat dataFormat) { + super(dataFormat.getName()); + this.name = name; + this.dataFormat = dataFormat; + } + + public String getName() { + return name; + } + + protected boolean isSerializationTextBased() { + // for the moment we assume that all spin data formats are text based. + return true; + } + + protected String getTypeNameForDeserialized(Object deserializedObject) { + return dataFormat.getMapper().getCanonicalTypeName(deserializedObject); + } + + protected byte[] serializeToByteArray(Object deserializedObject) throws Exception { + DataFormatMapper mapper = dataFormat.getMapper(); + DataFormatWriter writer = dataFormat.getWriter(); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + OutputStreamWriter outWriter = new OutputStreamWriter(out, Context.getProcessEngineConfiguration().getDefaultCharset()); + BufferedWriter bufferedWriter = new BufferedWriter(outWriter); + + try { + Object mappedObject = mapper.mapJavaToInternal(deserializedObject); + writer.writeToWriter(bufferedWriter, mappedObject); + return out.toByteArray(); + } + finally { + IoUtil.closeSilently(out); + IoUtil.closeSilently(outWriter); + IoUtil.closeSilently(bufferedWriter); + } + } + + protected Object deserializeFromByteArray(byte[] bytes, String objectTypeName) throws Exception { + ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); + DataFormatMapper mapper = dataFormat.getMapper(); + DataFormatReader reader = dataFormat.getReader(); + + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + InputStreamReader inReader = new InputStreamReader(bais, processEngineConfiguration.getDefaultCharset()); + BufferedReader bufferedReader = new BufferedReader(inReader); + + try { + Object mappedObject = reader.readInput(bufferedReader); + return mapper.mapInternalToJava(mappedObject, objectTypeName, getValidator(processEngineConfiguration)); + } + finally{ + IoUtil.closeSilently(bais); + IoUtil.closeSilently(inReader); + IoUtil.closeSilently(bufferedReader); + } + } + + protected boolean canSerializeValue(Object value) { + return dataFormat.getMapper().canMap(value); + } + + protected DeserializationTypeValidator getValidator(final ProcessEngineConfigurationImpl processEngineConfiguration) { + if (validator == null && processEngineConfiguration.isDeserializationTypeValidationEnabled()) { + validator = new DeserializationTypeValidator() { + @Override + public boolean validate(String type) { + return processEngineConfiguration.getDeserializationTypeValidator().validate(type); + } + }; + } + return validator; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinPluginLogger.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinPluginLogger.java new file mode 100644 index 0000000000000000000000000000000000000000..e081682a8bf36cb43ca5add02d6493fbc271816f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinPluginLogger.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.commons.logging.BaseLogger; + +/** + * @author Thorben Lindhauer + * + */ +public class SpinPluginLogger extends BaseLogger { + + public static final String PROJECT_CODE = "SPIN-PLUGIN"; + + public static final SpinPluginLogger LOGGER = BaseLogger.createLogger(SpinPluginLogger.class, PROJECT_CODE, "org.camunda.spin.plugin", "01"); + + public void logNoDataFormatsInitiailized(String dataFormatDescription, String reason) { + logInfo( + "001", "Cannot initialize %s: %s", dataFormatDescription, reason); + } + + public ProcessEngineException fallbackSerializerCannotDeserializeObjects() { + return new ProcessEngineException(exceptionMessage( + "002", "Fallback serializer cannot handle deserialized objects")); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinProcessEnginePlugin.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinProcessEnginePlugin.java new file mode 100644 index 0000000000000000000000000000000000000000..6af5bb6027148ecd39315b47b606fa2518a5f7c5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinProcessEnginePlugin.java @@ -0,0 +1,112 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import static org.camunda.spin.plugin.variable.type.SpinValueType.JSON; +import static org.camunda.spin.plugin.variable.type.SpinValueType.XML; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.el.ExpressionManager; +import org.camunda.bpm.engine.impl.util.ClassLoaderUtil; +import org.camunda.bpm.engine.impl.util.ReflectUtil; +import org.camunda.bpm.engine.impl.variable.serializer.JavaObjectSerializer; +import org.camunda.bpm.engine.impl.variable.serializer.TypedValueSerializer; +import org.camunda.bpm.engine.impl.variable.serializer.VariableSerializers; +import org.camunda.bpm.engine.variable.type.ValueTypeResolver; +import org.camunda.spin.DataFormats; +import org.camunda.spin.Spin; + +/** + * @author Thorben Lindhauer + * + */ +public class SpinProcessEnginePlugin extends SpinConfiguration { + + @Override + public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { + // use classloader which loaded the plugin + ClassLoader classloader = ClassLoaderUtil.getClassloader(SpinProcessEnginePlugin.class); + + // use Spin plugin configuration properties + Map configurationOptions = new HashMap<>(); + configurationOptions.put(XXE_PROPERTY, isEnableXxeProcessing()); + configurationOptions.put(SP_PROPERTY, isEnableSecureXmlProcessing()); + + DataFormats.loadDataFormats(classloader, configurationOptions); + } + + @Override + public void postInit(ProcessEngineConfigurationImpl processEngineConfiguration) { + registerFunctionMapper(processEngineConfiguration); + registerScriptResolver(processEngineConfiguration); + registerSerializers(processEngineConfiguration); + registerValueTypes(processEngineConfiguration); + registerFallbackSerializer(processEngineConfiguration); + } + + protected void registerFallbackSerializer(ProcessEngineConfigurationImpl processEngineConfiguration) { + processEngineConfiguration.setFallbackSerializerFactory(new SpinFallbackSerializerFactory()); + } + + protected void registerSerializers(ProcessEngineConfigurationImpl processEngineConfiguration) { + + List> spinDataFormatSerializers = lookupSpinSerializers(); + + VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers(); + + int javaObjectSerializerIdx = variableSerializers.getSerializerIndexByName(JavaObjectSerializer.NAME); + + for (TypedValueSerializer spinSerializer : spinDataFormatSerializers) { + // add before java object serializer + variableSerializers.addSerializer(spinSerializer, javaObjectSerializerIdx); + } + } + + protected List> lookupSpinSerializers() { + DataFormats globalFormats = DataFormats.getInstance(); + List> serializers = + SpinVariableSerializers.createObjectValueSerializers(globalFormats); + serializers.addAll(SpinVariableSerializers.createSpinValueSerializers(globalFormats)); + + return serializers; + } + + protected void registerScriptResolver(ProcessEngineConfigurationImpl processEngineConfiguration) { + processEngineConfiguration.getEnvScriptResolvers().add(new SpinScriptEnvResolver()); + } + + protected void registerFunctionMapper(ProcessEngineConfigurationImpl processEngineConfiguration) { + ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager(); + expressionManager.addFunction(SpinFunctions.S, + ReflectUtil.getMethod(Spin.class, SpinFunctions.S, Object.class)); + expressionManager.addFunction(SpinFunctions.XML, + ReflectUtil.getMethod(Spin.class, SpinFunctions.XML, Object.class)); + expressionManager.addFunction(SpinFunctions.JSON, + ReflectUtil.getMethod(Spin.class, SpinFunctions.JSON, Object.class)); + } + + protected void registerValueTypes(ProcessEngineConfigurationImpl processEngineConfiguration){ + ValueTypeResolver resolver = processEngineConfiguration.getValueTypeResolver(); + resolver.addType(JSON); + resolver.addType(XML); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinScriptEnvResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinScriptEnvResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..b46cf3622ae395857ce4e40757db468503a95999 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinScriptEnvResolver.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import org.camunda.bpm.engine.impl.scripting.env.ScriptEnvResolver; +import org.camunda.spin.scripting.SpinScriptEnv; + +/** + * Resolves Spin Environment Scripts. + * + * @author Daniel Meyer + * + */ +public class SpinScriptEnvResolver implements ScriptEnvResolver { + + public String[] resolve(String language) { + String envScript = SpinScriptEnv.get(language); + if(envScript != null) { + return new String[] { envScript }; + } + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinValueSerializer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinValueSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..5ce8ab28e8de839eeadd3a6a676406b2a4213ed9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinValueSerializer.java @@ -0,0 +1,112 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; + +import org.camunda.bpm.engine.impl.context.Context; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.impl.variable.serializer.AbstractSerializableValueSerializer; +import org.camunda.bpm.engine.impl.variable.serializer.ValueFields; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.spin.Spin; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.plugin.variable.value.impl.SpinValueImpl; +import org.camunda.spin.spi.DataFormat; + +/** + * @author Roman Smirnov + * + */ +public abstract class SpinValueSerializer extends AbstractSerializableValueSerializer { + + protected DataFormat dataFormat; + protected String name; + + public SpinValueSerializer(SerializableValueType type, DataFormat dataFormat, String name) { + super(type, dataFormat.getName()); + this.dataFormat = dataFormat; + this.name = name; + } + + public String getName() { + return name; + } + + protected void writeToValueFields(SpinValue value, ValueFields valueFields, byte[] serializedValue) { + valueFields.setByteArrayValue(serializedValue); + } + + protected void updateTypedValue(SpinValue value, String serializedStringValue) { + SpinValueImpl spinValue = (SpinValueImpl) value; + spinValue.setValueSerialized(serializedStringValue); + spinValue.setSerializationDataFormat(serializationDataFormat); + } + + protected boolean canSerializeValue(Object value) { + if (value instanceof Spin) { + Spin wrapper = (Spin) value; + return wrapper.getDataFormatName().equals(serializationDataFormat); + } + + return false; + } + + protected byte[] serializeToByteArray(Object deserializedObject) throws Exception { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + OutputStreamWriter outWriter = new OutputStreamWriter(out, Context.getProcessEngineConfiguration().getDefaultCharset()); + BufferedWriter bufferedWriter = new BufferedWriter(outWriter); + + try { + Spin wrapper = (Spin) deserializedObject; + wrapper.writeToWriter(bufferedWriter); + return out.toByteArray(); + } + finally { + IoUtil.closeSilently(out); + IoUtil.closeSilently(outWriter); + IoUtil.closeSilently(bufferedWriter); + } + } + + protected Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception { + ByteArrayInputStream bais = new ByteArrayInputStream(object); + InputStreamReader inReader = new InputStreamReader(bais, Context.getProcessEngineConfiguration().getDefaultCharset()); + BufferedReader bufferedReader = new BufferedReader(inReader); + + try { + Object wrapper = dataFormat.getReader().readInput(bufferedReader); + return dataFormat.createWrapperInstance(wrapper); + } + finally{ + IoUtil.closeSilently(bais); + IoUtil.closeSilently(inReader); + IoUtil.closeSilently(bufferedReader); + } + + } + + protected boolean isSerializationTextBased() { + return true; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinVariableSerializers.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinVariableSerializers.java new file mode 100644 index 0000000000000000000000000000000000000000..1061691ee59c3a03220a6e3b9c78b2fa34d39be7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/SpinVariableSerializers.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import org.camunda.bpm.engine.impl.variable.serializer.TypedValueSerializer; +import org.camunda.spin.DataFormats; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.spi.DataFormat; +import org.camunda.spin.xml.SpinXmlElement; + +/** + * @author Thorben Lindhauer + * + */ +public class SpinVariableSerializers { + + public static List> createObjectValueSerializers(DataFormats dataFormats) { + List> serializers = new ArrayList>(); + + Set> availableDataFormats = dataFormats.getAllAvailableDataFormats(); + for (DataFormat dataFormat : availableDataFormats) { + serializers.add(new SpinObjectValueSerializer("spin://"+dataFormat.getName(), dataFormat)); + } + + return serializers; + } + + public static List> createSpinValueSerializers(DataFormats dataFormats) { + List> serializers = new ArrayList>(); + + if(dataFormats.getDataFormatByName(DataFormats.JSON_DATAFORMAT_NAME) != null) { + DataFormat jsonDataFormat = + (DataFormat) dataFormats.getDataFormatByName(DataFormats.JSON_DATAFORMAT_NAME); + serializers.add(new JsonValueSerializer(jsonDataFormat)); + } + if(dataFormats.getDataFormatByName(DataFormats.XML_DATAFORMAT_NAME) != null){ + DataFormat xmlDataFormat = + (DataFormat) dataFormats.getDataFormatByName(DataFormats.XML_DATAFORMAT_NAME); + serializers.add(new XmlValueSerializer(xmlDataFormat)); + } + + return serializers; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/XmlValueSerializer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/XmlValueSerializer.java new file mode 100644 index 0000000000000000000000000000000000000000..7fa4268c6c0eeaf19a6004ee7e2eb8f5c5d2aa6f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/XmlValueSerializer.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import org.camunda.bpm.engine.impl.variable.serializer.ValueFields; +import org.camunda.bpm.engine.variable.impl.value.UntypedValueImpl; +import org.camunda.spin.DataFormats; +import org.camunda.spin.plugin.variable.SpinValues; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.type.XmlValueType; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.plugin.variable.value.impl.XmlValueImpl; +import org.camunda.spin.spi.DataFormat; +import org.camunda.spin.xml.SpinXmlElement; + +/** + * @author Roman Smirnov + * + */ +public class XmlValueSerializer extends SpinValueSerializer { + + public XmlValueSerializer(DataFormat dataFormat) { + super(SpinValueType.XML, dataFormat, XmlValueType.TYPE_NAME); + } + + public XmlValueSerializer() { + this(DataFormats.xml()); + } + + public SpinValue convertToTypedValue(UntypedValueImpl untypedValue) { + return SpinValues.xmlValue((SpinXmlElement) untypedValue.getValue()).create(); + } + + protected SpinValue createDeserializedValue(Object deserializedObject, String serializedStringValue, ValueFields valueFields, boolean asTransientValue) { + SpinXmlElement value = (SpinXmlElement) deserializedObject; + XmlValueImpl xmlValue = new XmlValueImpl(value, serializedStringValue, value.getDataFormatName(), true); + xmlValue.setTransient(asTransientValue); + return xmlValue; + } + + protected SpinValue createSerializedValue(String serializedStringValue, ValueFields valueFields, boolean asTransientValue) { + XmlValueImpl xmlValue = new XmlValueImpl(serializedStringValue, serializationDataFormat); + xmlValue.setTransient(asTransientValue); + return xmlValue; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/feel/integration/SpinValueMapper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/feel/integration/SpinValueMapper.java new file mode 100644 index 0000000000000000000000000000000000000000..8ff6c8f3d8397a8116be13d14ffb63a125fb03fa --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/impl/feel/integration/SpinValueMapper.java @@ -0,0 +1,148 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl.feel.integration; + +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.mapping; +import static java.util.stream.Collectors.toList; +import static java.util.stream.Collectors.toMap; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; + +import org.camunda.feel.syntaxtree.Val; +import org.camunda.feel.syntaxtree.ValString; +import org.camunda.feel.valuemapper.JavaCustomValueMapper; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.xml.SpinXmlAttribute; +import org.camunda.spin.xml.SpinXmlElement; +import org.camunda.spin.xml.SpinXmlNode; + + +public class SpinValueMapper extends JavaCustomValueMapper { + + @Override + public Optional toValue(Object x, Function innerValueMapper) { + if (x instanceof SpinJsonNode) { + SpinJsonNode node = (SpinJsonNode) x; + return Optional.of(this.spinJsonToVal(node, innerValueMapper)); + + } else if (x instanceof SpinXmlElement) { + SpinXmlElement element = (SpinXmlElement) x; + return Optional.of(this.spinXmlToVal(element, innerValueMapper)); + + } else { + return Optional.empty(); + + } + } + + @Override + public Optional unpackValue(Val value, Function innerValueMapper) { + return Optional.empty(); + } + + @Override + public int priority() { + return 30; + } + + protected Val spinJsonToVal(SpinJsonNode node, Function innerValueMapper) { + if (node.isObject()) { + Map pairs = node.fieldNames() + .stream() + .collect(toMap(field -> field, + field -> spinJsonToVal(node.prop(field), innerValueMapper))); + return innerValueMapper.apply(pairs); + + } else if (node.isArray()) { + List values = node.elements() + .stream() + .map(e -> spinJsonToVal(e, innerValueMapper)).collect(toList()); + return innerValueMapper.apply(values); + + } else if (node.isNull()) { + return innerValueMapper.apply(null); + + } else { + return innerValueMapper.apply(node.value()); + + } + } + + protected Val spinXmlToVal(SpinXmlElement element, Function innerValueMapper) { + String name = nodeName(element); + Val value = spinXmlElementToVal(element, innerValueMapper); + Map map = Collections.singletonMap(name, value); + + return innerValueMapper.apply(map); + } + + protected Val spinXmlElementToVal(final SpinXmlElement e, + Function innerValueMapper) { + Map membersMap = new HashMap<>(); + String content = e.textContent().trim(); + if (!content.isEmpty()) { + membersMap.put("$content", new ValString(content)); + } + + Map attributes = e.attrs() + .stream() + .collect(toMap(this::spinXmlAttributeToKey, attr -> new ValString(attr.value()))); + if (!attributes.isEmpty()) { + membersMap.putAll(attributes); + } + + Map childrenMap = e.childElements().stream() + .collect( + groupingBy( + this::nodeName, + mapping(el -> spinXmlElementToVal(el, innerValueMapper), toList()) + )) + .entrySet().stream() + .collect(toMap(Map.Entry::getKey, entry -> { + List valList = entry.getValue(); + if (!valList.isEmpty() && valList.size() > 1) { + return innerValueMapper.apply(valList); + } else { + return valList.get(0); + } + })); + membersMap.putAll(childrenMap); + + if (membersMap.isEmpty()) { + return innerValueMapper.apply(null); + } else { + return innerValueMapper.apply(membersMap); + } + } + + protected String spinXmlAttributeToKey(SpinXmlAttribute attribute) { + return "@" + nodeName(attribute); + } + + protected String nodeName(SpinXmlNode n) { + String prefix = n.prefix(); + String name = n.name(); + return (prefix != null && !prefix.isEmpty())? prefix + "$" + name : name; + } +} + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/SpinValues.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/SpinValues.java new file mode 100644 index 0000000000000000000000000000000000000000..f4f0090672c1142a327e0ff4735ffc592958be90 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/SpinValues.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable; + +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.variable.value.builder.JsonValueBuilder; +import org.camunda.spin.plugin.variable.value.builder.XmlValueBuilder; +import org.camunda.spin.plugin.variable.value.impl.builder.JsonValueBuilderImpl; +import org.camunda.spin.plugin.variable.value.impl.builder.XmlValueBuilderImpl; +import org.camunda.spin.xml.SpinXmlElement; + +/** + * @author Roman Smirnov + * + */ +public class SpinValues { + + public static JsonValueBuilder jsonValue(SpinJsonNode value) { + return jsonValue(value, false); + } + + public static JsonValueBuilder jsonValue(String value) { + return jsonValue(value, false); + } + + public static JsonValueBuilder jsonValue(SpinJsonNode value, boolean isTransient) { + return (JsonValueBuilder) new JsonValueBuilderImpl(value).setTransient(isTransient); + } + + public static JsonValueBuilder jsonValue(String value, boolean isTransient) { + return (JsonValueBuilder) new JsonValueBuilderImpl(value).setTransient(isTransient); + } + + public static XmlValueBuilder xmlValue(SpinXmlElement value) { + return xmlValue(value, false); + } + + public static XmlValueBuilder xmlValue(String value) { + return xmlValue(value, false); + } + + public static XmlValueBuilder xmlValue(SpinXmlElement value, boolean isTransient) { + return (XmlValueBuilder) new XmlValueBuilderImpl(value).setTransient(isTransient); + } + + public static XmlValueBuilder xmlValue(String value, boolean isTransient) { + return (XmlValueBuilder) new XmlValueBuilderImpl(value).setTransient(isTransient); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/JsonValueType.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/JsonValueType.java new file mode 100644 index 0000000000000000000000000000000000000000..aa85774e279832b373a12145976f6fb805042214 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/JsonValueType.java @@ -0,0 +1,27 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.type; + +/** + * @author Roman Smirnov + * + */ +public interface JsonValueType extends SpinValueType { + + public static final String TYPE_NAME = "json"; + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/SpinValueType.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/SpinValueType.java new file mode 100644 index 0000000000000000000000000000000000000000..f1bc3b998387cc4f83cfcd9ff9f0909c8f6f887e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/SpinValueType.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.type; + +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.spin.plugin.variable.type.impl.JsonValueTypeImpl; +import org.camunda.spin.plugin.variable.type.impl.XmlValueTypeImpl; + +/** + * @author Roman Smirnov + * + */ +public interface SpinValueType extends SerializableValueType { + + /** + * Identifies the Spin data format a value is an instance of. + */ + static final String VALUE_INFO_SERIALIZATION_DATA_FORMAT = "serializationDataFormat"; + + static final SpinValueType JSON = new JsonValueTypeImpl(); + + static final SpinValueType XML = new XmlValueTypeImpl(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/XmlValueType.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/XmlValueType.java new file mode 100644 index 0000000000000000000000000000000000000000..27f727f9a3b83d14cceebea2ca4eb0838ebcfa27 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/XmlValueType.java @@ -0,0 +1,27 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.type; + +/** + * @author Roman Smirnov + * + */ +public interface XmlValueType extends SpinValueType { + + public static final String TYPE_NAME = "xml"; + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/JsonValueTypeImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/JsonValueTypeImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..93407dea384ab8754b050c64c1f81f8be982d222 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/JsonValueTypeImpl.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.type.impl; + +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.variable.SpinValues; +import org.camunda.spin.plugin.variable.type.JsonValueType; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.plugin.variable.value.builder.JsonValueBuilder; + +/** + * @author Roman Smirnov + * + */ +public class JsonValueTypeImpl extends SpinValueTypeImpl implements JsonValueType { + + private static final long serialVersionUID = 1L; + + public JsonValueTypeImpl() { + super(TYPE_NAME); + } + + protected JsonValueBuilder createValue(SpinValue value) { + return SpinValues.jsonValue((SpinJsonNode) value); + } + + protected JsonValueBuilder createValueFromSerialized(String value) { + return SpinValues.jsonValue(value); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/SpinValueTypeImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/SpinValueTypeImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..af260a50722a1ce8ca902e7b35d0cc83070a4a4d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/SpinValueTypeImpl.java @@ -0,0 +1,82 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.type.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.variable.impl.type.AbstractValueTypeImpl; +import org.camunda.bpm.engine.variable.value.SerializableValue; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.plugin.variable.value.builder.SpinValueBuilder; + +/** + * @author Roman Smirnov + * + */ +public abstract class SpinValueTypeImpl extends AbstractValueTypeImpl implements SpinValueType { + + private static final long serialVersionUID = 1L; + + public SpinValueTypeImpl(String name) { + super(name); + } + + public TypedValue createValue(Object value, Map valueInfo) { + SpinValueBuilder builder = createValue((SpinValue) value); + applyValueInfo(builder, valueInfo); + return builder.create(); + } + + public SerializableValue createValueFromSerialized(String serializedValue, Map valueInfo) { + SpinValueBuilder builder = createValueFromSerialized(serializedValue); + applyValueInfo(builder, valueInfo); + return builder.create(); + } + + public boolean isPrimitiveValueType() { + return false; + } + + public Map getValueInfo(TypedValue typedValue) { + if(!(typedValue instanceof SpinValue)) { + throw new IllegalArgumentException("Value not of type Spin Value."); + } + SpinValue spinValue = (SpinValue) typedValue; + + Map valueInfo = new HashMap(); + + if (spinValue.isTransient()) { + valueInfo.put(VALUE_INFO_TRANSIENT, spinValue.isTransient()); + } + + return valueInfo; + } + + protected void applyValueInfo(SpinValueBuilder builder, Map valueInfo) { + if(valueInfo != null) { + builder.setTransient(isTransient(valueInfo)); + } + } + + protected abstract SpinValueBuilder createValue(SpinValue value); + + protected abstract SpinValueBuilder createValueFromSerialized(String value); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/XmlValueTypeImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/XmlValueTypeImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..2e423f585aa321539b4c8d4e2147e14ec3c4fe55 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/type/impl/XmlValueTypeImpl.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.type.impl; + +import org.camunda.spin.plugin.variable.SpinValues; +import org.camunda.spin.plugin.variable.type.XmlValueType; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.plugin.variable.value.builder.XmlValueBuilder; +import org.camunda.spin.xml.SpinXmlElement; + +/** + * @author Roman Smirnov + * + */ +public class XmlValueTypeImpl extends SpinValueTypeImpl implements XmlValueType { + + private static final long serialVersionUID = 1L; + + public XmlValueTypeImpl() { + super(TYPE_NAME); + } + + protected XmlValueBuilder createValue(SpinValue value) { + return SpinValues.xmlValue((SpinXmlElement) value); + } + + protected XmlValueBuilder createValueFromSerialized(String value) { + return SpinValues.xmlValue(value); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/JsonValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/JsonValue.java new file mode 100644 index 0000000000000000000000000000000000000000..95daf6305ffc610787f7d8a1f970f7ef657604a7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/JsonValue.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value; + +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.variable.type.JsonValueType; +import org.camunda.spin.spi.DataFormat; + +/** + * @author Roman Smirnov + * + */ +public interface JsonValue extends SpinValue { + + public SpinJsonNode getValue(); + + public DataFormat getDataFormat(); + + public JsonValueType getType(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/SpinValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/SpinValue.java new file mode 100644 index 0000000000000000000000000000000000000000..c75ed593bbb59f857f2c48a32b3c410a93273d36 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/SpinValue.java @@ -0,0 +1,33 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value; + +import org.camunda.bpm.engine.variable.value.SerializableValue; +import org.camunda.spin.Spin; +import org.camunda.spin.spi.DataFormat; + +/** + * @author Roman Smirnov + * + */ +public interface SpinValue extends SerializableValue { + + public Spin getValue(); + + public DataFormat> getDataFormat(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/XmlValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/XmlValue.java new file mode 100644 index 0000000000000000000000000000000000000000..59a801eae28234d9f5f3e2d7ed43fe48d85ca263 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/XmlValue.java @@ -0,0 +1,33 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value; + +import org.camunda.spin.spi.DataFormat; +import org.camunda.spin.xml.SpinXmlElement; + + +/** + * @author Roman Smirnov + * + */ +public interface XmlValue extends SpinValue { + + public SpinXmlElement getValue(); + + public DataFormat getDataFormat(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/JsonValueBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/JsonValueBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..2b8a1d86ebb04fabadbccd9c1cc906e0d342891e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/JsonValueBuilder.java @@ -0,0 +1,32 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.builder; + +import org.camunda.bpm.engine.variable.value.SerializationDataFormat; +import org.camunda.spin.plugin.variable.value.JsonValue; + +/** + * @author Roman Smirnov + * + */ +public interface JsonValueBuilder extends SpinValueBuilder { + + JsonValueBuilder serializationDataFormat(String dataFormatName); + + JsonValueBuilder serializationDataFormat(SerializationDataFormat dataFormat); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/SpinValueBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/SpinValueBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..727b5e742a9eceb56a655938396a8aa3eb8cf2fc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/SpinValueBuilder.java @@ -0,0 +1,33 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.builder; + +import org.camunda.bpm.engine.variable.value.SerializationDataFormat; +import org.camunda.bpm.engine.variable.value.builder.TypedValueBuilder; +import org.camunda.spin.plugin.variable.value.SpinValue; + +/** + * @author Roman Smirnov + * + */ +public interface SpinValueBuilder extends TypedValueBuilder { + + SpinValueBuilder serializationDataFormat(String dataFormatName); + + SpinValueBuilder serializationDataFormat(SerializationDataFormat dataFormat); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/XmlValueBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/XmlValueBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..1f224bfd3964bcef490cbb6656c6a5105f9b5cc6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/builder/XmlValueBuilder.java @@ -0,0 +1,32 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.builder; + +import org.camunda.bpm.engine.variable.value.SerializationDataFormat; +import org.camunda.spin.plugin.variable.value.XmlValue; + +/** + * @author Roman Smirnov + * + */ +public interface XmlValueBuilder extends SpinValueBuilder { + + XmlValueBuilder serializationDataFormat(String dataFormatName); + + XmlValueBuilder serializationDataFormat(SerializationDataFormat dataFormat); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/JsonValueImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/JsonValueImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..83f907275dbdf3e49a6b2135ca0f902782c0b951 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/JsonValueImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.impl; + +import org.camunda.spin.DataFormats; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.variable.type.JsonValueType; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.value.JsonValue; +import org.camunda.spin.spi.DataFormat; + +/** + * @author Roman Smirnov + * + */ +public class JsonValueImpl extends SpinValueImpl implements JsonValue { + + private static final long serialVersionUID = 1L; + + public JsonValueImpl(String value) { + this(null, value, DataFormats.JSON_DATAFORMAT_NAME, false); + } + + public JsonValueImpl(SpinJsonNode value) { + this(value, null, value.getDataFormatName(), true); + } + + public JsonValueImpl(String value, String dataFormatName) { + this(null, value, dataFormatName, false); + } + + public JsonValueImpl( + SpinJsonNode value, + String serializedValue, + String dataFormatName, + boolean isDeserialized) { + this(value, serializedValue, dataFormatName, isDeserialized, false); + } + + public JsonValueImpl( + SpinJsonNode value, + String serializedValue, + String dataFormatName, + boolean isDeserialized, + boolean isTransient) { + super(value, serializedValue, dataFormatName, isDeserialized, SpinValueType.JSON, isTransient); + } + + @SuppressWarnings("unchecked") + public DataFormat getDataFormat() { + return (DataFormat) super.getDataFormat(); + } + + public JsonValueType getType() { + return (JsonValueType) super.getType(); + } + + public SpinJsonNode getValue() { + return (SpinJsonNode) super.getValue(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/SpinValueImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/SpinValueImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..610e02dca435aefad222ebab36618c66328d822a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/SpinValueImpl.java @@ -0,0 +1,105 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.impl; + +import static org.camunda.spin.Spin.S; + +import org.camunda.bpm.engine.variable.impl.value.AbstractTypedValue; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.spin.DataFormats; +import org.camunda.spin.Spin; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.spi.DataFormat; + +/** + * @author Roman Smirnov + * + */ +public abstract class SpinValueImpl extends AbstractTypedValue> implements SpinValue { + + private static final long serialVersionUID = 1L; + protected String serializedValue; + protected boolean isDeserialized; + protected String dataFormatName; + + public SpinValueImpl( + Spin value, + String serializedValue, + String dataFormatName, + boolean isDeserialized, + ValueType type, + boolean isTransient) { + + super(value, type); + + this.serializedValue = serializedValue; + this.dataFormatName = dataFormatName; + this.isDeserialized = isDeserialized; + this.isTransient = isTransient; + } + + public Spin getValue() { + if(isDeserialized) { + return super.getValue(); + } + else { + // deserialize the serialized value by using + // the given data format + value = S(getValueSerialized(), getSerializationDataFormat()); + isDeserialized = true; + + setValueSerialized(null); + + return value; + } + } + + public SpinValueType getType() { + return (SpinValueType) super.getType(); + } + + public boolean isDeserialized() { + return isDeserialized; + } + + public String getValueSerialized() { + return serializedValue; + } + + public void setValueSerialized(String serializedValue) { + this.serializedValue = serializedValue; + } + + public String getSerializationDataFormat() { + return dataFormatName; + } + + public void setSerializationDataFormat(String serializationDataFormat) { + this.dataFormatName = serializationDataFormat; + } + + public DataFormat> getDataFormat() { + if(isDeserialized) { + return DataFormats.getDataFormat(dataFormatName); + } + else { + throw new IllegalStateException("Spin value is not deserialized."); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/XmlValueImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/XmlValueImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e7d9a25736e5fc01ec395cd05c52714707df6807 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/XmlValueImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.impl; + +import org.camunda.spin.DataFormats; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.type.XmlValueType; +import org.camunda.spin.plugin.variable.value.XmlValue; +import org.camunda.spin.spi.DataFormat; +import org.camunda.spin.xml.SpinXmlElement; + +/** + * @author Roman Smirnov + * + */ +public class XmlValueImpl extends SpinValueImpl implements XmlValue { + + private static final long serialVersionUID = 1L; + + public XmlValueImpl(SpinXmlElement value) { + this(value, null, value.getDataFormatName(), true); + } + + public XmlValueImpl(String value, String dataFormatName) { + this(null, value, dataFormatName, false); + } + + public XmlValueImpl(String value) { + this(null, value, DataFormats.XML_DATAFORMAT_NAME, false); + } + + public XmlValueImpl( + SpinXmlElement value, + String serializedValue, + String dataFormatName, + boolean isDeserialized) { + this(value, serializedValue, dataFormatName, isDeserialized, false); + } + + public XmlValueImpl( + SpinXmlElement value, + String serializedValue, + String dataFormatName, + boolean isDeserialized, + boolean isTransient) { + super(value, serializedValue, dataFormatName, isDeserialized, SpinValueType.XML, isTransient); + } + + @SuppressWarnings("unchecked") + public DataFormat getDataFormat() { + return (DataFormat) super.getDataFormat(); + } + + public XmlValueType getType() { + return (XmlValueType) super.getType(); + } + + public SpinXmlElement getValue() { + return (SpinXmlElement) super.getValue(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/JsonValueBuilderImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/JsonValueBuilderImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..5d250f51f257abbcf9290a4e26f6e7741419cff0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/JsonValueBuilderImpl.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.impl.builder; + +import org.camunda.bpm.engine.variable.value.SerializationDataFormat; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.variable.value.JsonValue; +import org.camunda.spin.plugin.variable.value.builder.JsonValueBuilder; +import org.camunda.spin.plugin.variable.value.impl.JsonValueImpl; + +/** + * @author Roman Smirnov + * + */ +public class JsonValueBuilderImpl extends SpinValueBuilderImpl implements JsonValueBuilder { + + public JsonValueBuilderImpl(JsonValue value) { + super(value); + } + + public JsonValueBuilderImpl(String value) { + this(new JsonValueImpl(value)); + } + + public JsonValueBuilderImpl(SpinJsonNode value) { + this(new JsonValueImpl(value)); + } + + public JsonValueBuilder serializationDataFormat(SerializationDataFormat dataFormat) { + return (JsonValueBuilderImpl) super.serializationDataFormat(dataFormat); + } + + public JsonValueBuilder serializationDataFormat(String dataFormatName) { + return (JsonValueBuilderImpl) super.serializationDataFormat(dataFormatName); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/SpinValueBuilderImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/SpinValueBuilderImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..fc77e7abe22746df72668a7885044181286eb1ae --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/SpinValueBuilderImpl.java @@ -0,0 +1,57 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.impl.builder; + +import org.camunda.bpm.engine.variable.impl.value.AbstractTypedValue; +import org.camunda.bpm.engine.variable.value.SerializationDataFormat; +import org.camunda.bpm.engine.variable.value.builder.TypedValueBuilder; +import org.camunda.spin.plugin.variable.value.SpinValue; +import org.camunda.spin.plugin.variable.value.builder.SpinValueBuilder; +import org.camunda.spin.plugin.variable.value.impl.SpinValueImpl; + +/** + * @author Roman Smirnov + * + */ +public abstract class SpinValueBuilderImpl implements SpinValueBuilder { + + protected T variableValue; + + public SpinValueBuilderImpl(T value) { + variableValue = value; + } + + public T create() { + return variableValue; + } + + public SpinValueBuilder serializationDataFormat(String dataFormatName) { + ((SpinValueImpl) variableValue).setSerializationDataFormat(dataFormatName); + return this; + } + + public SpinValueBuilder serializationDataFormat(SerializationDataFormat dataFormat) { + return serializationDataFormat(dataFormat.getName()); + } + + @Override + public TypedValueBuilder setTransient(boolean isTransient) { + ((AbstractTypedValue) variableValue).setTransient(isTransient); + return this; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/XmlValueBuilderImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/XmlValueBuilderImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..198150c66b31a4d573ad8c784e854f78d91a2d3a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/java/org/camunda/spin/plugin/variable/value/impl/builder/XmlValueBuilderImpl.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variable.value.impl.builder; + +import org.camunda.bpm.engine.variable.value.SerializationDataFormat; +import org.camunda.spin.plugin.variable.value.XmlValue; +import org.camunda.spin.plugin.variable.value.builder.XmlValueBuilder; +import org.camunda.spin.plugin.variable.value.impl.XmlValueImpl; +import org.camunda.spin.xml.SpinXmlElement; + +/** + * @author Roman Smirnov + * + */ +public class XmlValueBuilderImpl extends SpinValueBuilderImpl implements XmlValueBuilder { + + public XmlValueBuilderImpl(XmlValue value) { + super(value); + } + + public XmlValueBuilderImpl(String value) { + super(new XmlValueImpl(value)); + } + + public XmlValueBuilderImpl(SpinXmlElement value) { + this(new XmlValueImpl(value)); + } + + public XmlValueBuilder serializationDataFormat(SerializationDataFormat dataFormat) { + return (XmlValueBuilder) super.serializationDataFormat(dataFormat); + } + + public XmlValueBuilder serializationDataFormat(String dataFormatName) { + return (XmlValueBuilder) super.serializationDataFormat(dataFormatName); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/resources/META-INF/services/org.camunda.bpm.container.impl.plugin.BpmPlatformPlugin b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/resources/META-INF/services/org.camunda.bpm.container.impl.plugin.BpmPlatformPlugin new file mode 100644 index 0000000000000000000000000000000000000000..85a6f8fd1c52d43e16b4162084c31457591498c5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/resources/META-INF/services/org.camunda.bpm.container.impl.plugin.BpmPlatformPlugin @@ -0,0 +1 @@ +org.camunda.spin.plugin.impl.SpinBpmPlatformPlugin \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/resources/META-INF/services/org.camunda.feel.valuemapper.CustomValueMapper b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/resources/META-INF/services/org.camunda.feel.valuemapper.CustomValueMapper new file mode 100644 index 0000000000000000000000000000000000000000..5544f480532076771b33d5f979fc1dd5171ddbe8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/main/resources/META-INF/services/org.camunda.feel.valuemapper.CustomValueMapper @@ -0,0 +1 @@ +org.camunda.spin.plugin.impl.feel.integration.SpinValueMapper \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/el/SpinFunctionsTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/el/SpinFunctionsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..39a68f4bc144118775b2ab3965584b914e1f4429 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/el/SpinFunctionsTest.java @@ -0,0 +1,120 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.el; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.delegate.Expression; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.script.TestVariableScope; +import org.camunda.spin.xml.SpinXmlElement; + +/** + *

Testcase ensuring integration of camunda Spin into Process Engine expression language.

+ * + * @author Daniel Meyer + * + */ +public class SpinFunctionsTest extends PluggableProcessEngineTestCase { + + String xmlString = ""; + String jsonString = "{\"foo\": \"bar\"}"; + + @SuppressWarnings("unchecked") + protected T executeExpression(String expression) { + + final TestVariableScope varScope = new TestVariableScope(); + + final Expression compiledExpression = processEngineConfiguration.getExpressionManager() + .createExpression(expression); + + return (T) processEngineConfiguration.getCommandExecutorTxRequired() + .execute(commandContext -> compiledExpression.getValue(varScope)); + } + + public void testSpin_S_Available() { + + SpinXmlElement spinXmlEl = executeExpression("${ S('" + xmlString + "') }"); + assertNotNull(spinXmlEl); + assertEquals("elementName", spinXmlEl.name()); + } + + public void testSpin_XML_Available() { + + SpinXmlElement spinXmlEl = executeExpression("${ XML('" + xmlString + "') }"); + assertNotNull(spinXmlEl); + assertEquals("elementName", spinXmlEl.name()); + } + + public void testSpin_JSON_Available() { + + SpinJsonNode spinJsonEl = executeExpression("${ JSON('" + jsonString + "') }"); + assertNotNull(spinJsonEl); + assertEquals("bar", spinJsonEl.prop("foo").stringValue()); + } + + public void testSpin_XPath_Available() { + + String elName = executeExpression("${ S('" + xmlString + "').xPath('/elementName').element().name() }"); + assertNotNull(elName); + assertEquals("elementName", elName); + } + + public void testSpin_JsonPath_Available() { + + String property = executeExpression("${ S('" + jsonString + "').jsonPath('$.foo').stringValue() }"); + assertNotNull(property); + assertEquals("bar", property); + } + + public void testSpinAvailableInBpmn() { + + BpmnModelInstance bpmnModelInstance = Bpmn.createExecutableProcess("testProcess") + .startEvent() + .serviceTask() + .camundaExpression("${ execution.setVariable('customer', " + + "S(xmlVar).xPath('/customers/customer').element().toString()" + +")}") + .receiveTask("wait") + .endEvent() + .done(); + + Deployment deployment = repositoryService.createDeployment() + .addModelInstance("process.bpmn", bpmnModelInstance) + .deploy(); + + Map variables = new HashMap(); + variables.put("xmlVar", ""); + ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess", variables); + + String customerXml = (String) runtimeService.getVariable(pi.getId(), "customer"); + assertNotNull(customerXml); + assertTrue(customerXml.contains("customer")); + assertFalse(customerXml.contains("customers")); + + runtimeService.signal(pi.getId()); + + repositoryService.deleteDeployment(deployment.getId(), true); + + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/SpinProcessEnginePluginConfigurationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/SpinProcessEnginePluginConfigurationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2f7cf39a07b85b596cd80d7502db3d85190b973c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/SpinProcessEnginePluginConfigurationTest.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.camunda.bpm.engine.impl.cfg.ProcessEnginePlugin; +import org.camunda.bpm.engine.test.util.ProcessEngineBootstrapRule; +import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule; +import org.junit.Rule; +import org.junit.Test; + +public class SpinProcessEnginePluginConfigurationTest { + + @Rule + public ProcessEngineBootstrapRule bootstrapRule + = new ProcessEngineBootstrapRule("custom.camunda.cfg.xml"); + + @Rule + public ProvidedProcessEngineRule engineRule = new ProvidedProcessEngineRule(bootstrapRule); + + @Test + public void shouldSetCustomSpinPluginProperties() { + + // when + List pluginList = + engineRule.getProcessEngineConfiguration().getProcessEnginePlugins(); + + // then + assertThat(pluginList).hasOnlyElementsOfType(SpinProcessEnginePlugin.class).hasSize(1); + SpinProcessEnginePlugin spinProcessEnginePlugin = (SpinProcessEnginePlugin) pluginList.get(0); + assertThat(spinProcessEnginePlugin.isEnableXxeProcessing()).isTrue(); + assertThat(spinProcessEnginePlugin.isEnableSecureXmlProcessing()).isFalse(); + + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/SpinProcessEnginePluginTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/SpinProcessEnginePluginTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3cafc05ba0d8398a8e4bfd335039880c0a5436ca --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/SpinProcessEnginePluginTest.java @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl; + +import java.io.IOException; +import java.net.URL; +import java.util.Collections; + +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.impl.variable.serializer.DefaultVariableSerializers; +import org.camunda.spin.DataFormats; +import org.camunda.spin.plugin.variable.type.JsonValueType; +import org.camunda.spin.plugin.variable.type.XmlValueType; +import org.mockito.Mockito; + +/** + * @author Ronny Bräunlich + * + */ +public class SpinProcessEnginePluginTest extends PluggableProcessEngineTestCase { + + public void testPluginDoesNotRegisterXmlSerializerIfNotPresentInClasspath() throws IOException { + ClassLoader mockClassloader = Mockito.mock(ClassLoader.class); + Mockito.when(mockClassloader.getResources(Mockito.anyString())).thenReturn(Collections.enumeration(Collections.emptyList())); + DataFormats.loadDataFormats(mockClassloader); + ProcessEngineConfigurationImpl mockConfig = Mockito.mock(ProcessEngineConfigurationImpl.class); + DefaultVariableSerializers serializers = new DefaultVariableSerializers(); + Mockito.when(mockConfig.getVariableSerializers()).thenReturn(serializers); + new SpinProcessEnginePlugin().registerSerializers(mockConfig); + + assertTrue(serializers.getSerializerByName(XmlValueType.TYPE_NAME) == null); + } + + public void testPluginDoesNotRegisterJsonSerializerIfNotPresentInClasspath() throws IOException { + ClassLoader mockClassloader = Mockito.mock(ClassLoader.class); + Mockito.when(mockClassloader.getResources(Mockito.anyString())).thenReturn(Collections.enumeration(Collections.emptyList())); + DataFormats.loadDataFormats(mockClassloader); + ProcessEngineConfigurationImpl mockConfig = Mockito.mock(ProcessEngineConfigurationImpl.class); + DefaultVariableSerializers serializers = new DefaultVariableSerializers(); + Mockito.when(mockConfig.getVariableSerializers()).thenReturn(serializers); + new SpinProcessEnginePlugin().registerSerializers(mockConfig); + + assertTrue(serializers.getSerializerByName(JsonValueType.TYPE_NAME) == null); + } + + public void testPluginRegistersXmlSerializerIfPresentInClasspath(){ + DataFormats.loadDataFormats(null); + ProcessEngineConfigurationImpl mockConfig = Mockito.mock(ProcessEngineConfigurationImpl.class); + Mockito.when(mockConfig.getVariableSerializers()).thenReturn(processEngineConfiguration.getVariableSerializers()); + new SpinProcessEnginePlugin().registerSerializers(mockConfig); + + assertTrue(processEngineConfiguration.getVariableSerializers().getSerializerByName(XmlValueType.TYPE_NAME) instanceof XmlValueSerializer); + } + + public void testPluginRegistersJsonSerializerIfPresentInClasspath(){ + DataFormats.loadDataFormats(null); + ProcessEngineConfigurationImpl mockConfig = Mockito.mock(ProcessEngineConfigurationImpl.class); + Mockito.when(mockConfig.getVariableSerializers()).thenReturn(processEngineConfiguration.getVariableSerializers()); + new SpinProcessEnginePlugin().registerSerializers(mockConfig); + + assertTrue(processEngineConfiguration.getVariableSerializers().getSerializerByName(JsonValueType.TYPE_NAME) instanceof JsonValueSerializer); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/feel/integration/SpinValueMapperTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/feel/integration/SpinValueMapperTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8c17dbd0915b8d879641e633bada02b0a9ef350e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/impl/feel/integration/SpinValueMapperTest.java @@ -0,0 +1,278 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.impl.feel.integration; + +import static camundajar.impl.scala.jdk.CollectionConverters.ListHasAsScala; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.dmn.feel.impl.scala.ScalaFeelLogger; +import org.camunda.bpm.dmn.feel.impl.scala.spin.SpinValueMapperFactory; +import org.camunda.commons.testing.ProcessEngineLoggingRule; +import org.camunda.commons.testing.WatchLogger; +import org.camunda.feel.impl.DefaultValueMapper; +import org.camunda.feel.syntaxtree.Val; +import org.camunda.feel.syntaxtree.ValContext; +import org.camunda.feel.syntaxtree.ValList; +import org.camunda.feel.syntaxtree.ValString; +import org.camunda.feel.valuemapper.CustomValueMapper; +import org.camunda.feel.valuemapper.ValueMapper; +import org.camunda.spin.Spin; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.xml.SpinXmlElement; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; + +public class SpinValueMapperTest { + + protected static ValueMapper valueMapper; + + @Rule + public ProcessEngineLoggingRule loggingRule = new ProcessEngineLoggingRule(); + + @BeforeClass + public static void setUp() { + DefaultValueMapper defaultValueMapper = DefaultValueMapper.instance(); + SpinValueMapper spinValueMapper = new SpinValueMapper(); + List mapperList = Arrays.asList(defaultValueMapper, spinValueMapper); + valueMapper = new ValueMapper + .CompositeValueMapper(ListHasAsScala(mapperList).asScala().toList()); + } + + @Test + public void shouldMapCamundaSpinJSONObjectAsContext() { + // given + Map map = new HashMap<>(); + map.put("customer", new ValString("Kermit")); + map.put("language", new ValString("en")); + ValContext context = (ValContext) valueMapper.toVal(map); + SpinJsonNode json = Spin.JSON("{\"customer\": \"Kermit\", \"language\": \"en\"}"); + + // when + Val value = valueMapper.toVal(json); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapCamundaSpinJSONarrayAsList() { + // given + List list = Arrays.asList(new ValString("Kermit"), new ValString("Waldo")); + ValList feelList = (ValList) valueMapper.toVal(list); + ValContext context = (ValContext) valueMapper.toVal(Collections.singletonMap("customer", feelList)); + SpinJsonNode json = Spin.JSON("{\"customer\": [\"Kermit\", \"Waldo\"]}"); + + // when + Val value = valueMapper.toVal(json); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapNestedCamundaSpinJSONObjectAsContext() { + + // given + Map nestedMap = new HashMap<>(); + nestedMap.put("city", new ValString("Berlin")); + nestedMap.put("zipCode", valueMapper.toVal(10961)); + + Map contextMap = new HashMap<>(); + contextMap.put("customer", new ValString("Kermit")); + contextMap.put("address", valueMapper.toVal(nestedMap)); + + ValContext context = (ValContext) valueMapper.toVal(contextMap); + SpinJsonNode json = Spin.JSON("{" + + "\"customer\": \"Kermit\", " + + "\"address\": {\"" + + "city\": \"Berlin\", " + + "\"zipCode\": 10961}}"); + + // when + Val value = valueMapper.toVal(json); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapCamundaSpinXMLObjectWithAttributes() { + // given + Map xmlInnerMap = new HashMap(); + xmlInnerMap.put("@name", new ValString("Kermit")); + xmlInnerMap.put("@language", new ValString("en")); + Map xmlContextMap = new HashMap(); + xmlContextMap.put("customer", valueMapper.toVal(xmlInnerMap)); + + ValContext context = (ValContext) valueMapper.toVal(xmlContextMap); + SpinXmlElement xml = Spin.XML(" "); + + // when + Val value = valueMapper.toVal(xml); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapCamundaSpinXMLObjectWithChildObject() { + // given + Map xmlAttrMap = new HashMap(); + xmlAttrMap.put("@city", new ValString("Berlin")); + xmlAttrMap.put("@zipCode", new ValString("10961")); + Map xmlInnerMap = new HashMap(); + xmlInnerMap.put("address", valueMapper.toVal(xmlAttrMap)); + Map xmlContextMap = new HashMap(); + xmlContextMap.put("customer", valueMapper.toVal(xmlInnerMap)); + + ValContext context = (ValContext) valueMapper.toVal(xmlContextMap); + SpinXmlElement xml = Spin.XML("" + + "
" + + ""); + + // when + Val value = valueMapper.toVal(xml); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapCamundaSpinXMLObjectWithListOfChildObjects() { + // given + SpinXmlElement xml = Spin.XML("" + + "" + + "" + + "" + + ""); + + Map xmlProviderAttrMap = new HashMap(); + xmlProviderAttrMap.put("@name", new ValString("Foobar")); + + Map xmlCustomerAttrMap1 = new HashMap(); + xmlCustomerAttrMap1.put("@name", new ValString("Kermit")); + xmlCustomerAttrMap1.put("@language", new ValString("en")); + + Map xmlCustomerAttrMap2 = new HashMap(); + xmlCustomerAttrMap2.put("@name", new ValString("John")); + xmlCustomerAttrMap2.put("@language", new ValString("de")); + + Map xmlInnerMap = new HashMap(); + xmlInnerMap.put("provider", valueMapper.toVal(xmlProviderAttrMap)); + xmlInnerMap.put("customer", + valueMapper.toVal(Arrays.asList(xmlCustomerAttrMap1, xmlCustomerAttrMap2))); + + Map xmlContextMap = new HashMap(); + xmlContextMap.put("data", valueMapper.toVal(xmlInnerMap)); + + ValContext context = (ValContext) valueMapper.toVal(xmlContextMap); + + // when + Val value = valueMapper.toVal(xml); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapCamundaSpinXMLObjectWithContent() { + // given + SpinXmlElement xml = Spin.XML("Kermit"); + + Map xmlInnerMap = new HashMap(); + xmlInnerMap.put("$content", new ValString("Kermit")); + + Map xmlContextMap = new HashMap(); + xmlContextMap.put("customer", valueMapper.toVal(xmlInnerMap)); + + ValContext context = (ValContext) valueMapper.toVal(xmlContextMap); + + // when + Val value = valueMapper.toVal(xml); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapCamundaSpinXMLObjectWithoutContent() { + // given + SpinXmlElement xml = Spin.XML(""); + ValContext context = (ValContext) valueMapper + .toVal(Collections.singletonMap("customer", null)); + + // when + Val value = valueMapper.toVal(xml); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldMapCamundaSpinXMLObjectWithPrefix() { + // given + SpinXmlElement xml = Spin.XML("" + + "" + + ""); + + Map xmlAttrMap = new HashMap(); + xmlAttrMap.put("@p$name", new ValString("Kermit")); + xmlAttrMap.put("@language", new ValString("en")); + + Map xmlInnerMap = new HashMap(); + xmlInnerMap.put("p$customer", valueMapper.toVal(xmlAttrMap)); + xmlInnerMap.put("@xmlns$p", new ValString("http://www.example.org")); + + Map xmlContextMap = new HashMap(); + xmlContextMap.put("data", valueMapper.toVal(xmlInnerMap)); + + ValContext context = (ValContext) valueMapper.toVal(xmlContextMap); + + // when + Val value = valueMapper.toVal(xml); + + // then + assertThat(value).isEqualTo(context); + } + + @Test + public void shouldEqualClassNameForSpinValueMapper() { + assertThat(SpinValueMapper.class.getName()) + .isEqualTo(SpinValueMapperFactory.SPIN_VALUE_MAPPER_CLASS_NAME); + } + + @Test + @WatchLogger(loggerNames = {ScalaFeelLogger.PROJECT_LOGGER}, level = "INFO") + public void shouldLogValueMapperDetection() { + // given + SpinValueMapperFactory mapperFactory = new SpinValueMapperFactory(); + + // when + mapperFactory.createInstance(); + + // then + assertThat(loggingRule.getFilteredLog("Spin value mapper detected").size()).isOne(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinJRubyScriptTaskTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinJRubyScriptTaskTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3bc5f70bef1c67898a978e678c744d806744cf76 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinJRubyScriptTaskTest.java @@ -0,0 +1,91 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.script; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; + +public class SpinJRubyScriptTaskTest { + + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(); + + private RuntimeService runtimeService; + private RepositoryService repositoryService; + + @Before + public void setUp() { + this.runtimeService = engineRule.getRuntimeService(); + this.repositoryService = engineRule.getRepositoryService(); + } + + @Test + @Ignore("CAM-11114") + public void shouldNotLeakVariables() { + // given + String varName = "var"; + String varValue = "val"; + + BpmnModelInstance model1 = Bpmn.createExecutableProcess("process1") + .startEvent() + .scriptTask() + .scriptFormat("ruby") + .scriptText("") // do nothing + .endEvent() + .done(); + + BpmnModelInstance model2 = Bpmn.createExecutableProcess("process2") + .startEvent() + .scriptTask() + .scriptFormat("ruby") + .scriptText("$execution.setVariable('" + varName + "', $" + varName + ")") + .userTask() + .endEvent() + .done(); + + Deployment deployment = repositoryService.createDeployment() + .addModelInstance("process1.bpmn", model1) + .addModelInstance("process2.bpmn", model2) + .deploy(); + engineRule.manageDeployment(deployment); + + VariableMap variables = Variables.createVariables().putValue(varName, varValue); + runtimeService.startProcessInstanceByKey("process1", variables); + + // when + ProcessInstance instance = runtimeService.startProcessInstanceByKey("process2"); + + // then + Object actualVarValue = runtimeService.getVariable(instance.getId(), varName); + // $var is not defined in the context of the second process instance, so the resulting value + // should be null + assertThat(actualVarValue).isNull(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinScriptTaskSupportTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinScriptTaskSupportTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9d5cd54e207ea8f4c859357fd5930539255e7b41 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinScriptTaskSupportTest.java @@ -0,0 +1,139 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.script; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; + +/** + * @author Daniel Meyer + * + */ +@RunWith(Parameterized.class) +public class SpinScriptTaskSupportTest { + + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(); + + @Parameters(name = "{index}: {0}") + public static Object[] data() { + return new Object[][] { + { "groovy", "" }, + { "javascript", "" }, + { "python", "" }, + { "ruby", "$" } + }; + } + + @Parameter(0) + public String language; + + @Parameter(1) + public String variablePrefix; + + private RuntimeService runtimeService; + private RepositoryService repositoryService; + + + @Before + public void setUp() { + this.runtimeService = engineRule.getRuntimeService(); + this.repositoryService = engineRule.getRepositoryService(); + } + + @Test + public void testSpinAvailable() { + deployProcess(language, setVariableScript("name", "S('').name()")); + ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); + + String var = (String) runtimeService.getVariable(pi.getId(), "name"); + assertThat(var).isEqualTo("test"); + } + + @Test + public void testTwoScriptTasks() { + // given + BpmnModelInstance modelInstance = Bpmn.createExecutableProcess("testProcess") + .startEvent() + .scriptTask() + .scriptFormat(language) + .scriptText(setVariableScript("task1Name", "S('').name()")) + .scriptTask() + .scriptFormat(language) + .scriptText(setVariableScript("task2Name", "S('').name()")) + .userTask() + .endEvent() + .done(); + + Deployment deployment = repositoryService.createDeployment().addModelInstance("process.bpmn", modelInstance).deploy(); + engineRule.manageDeployment(deployment); + + // when + ProcessInstance pi = runtimeService.startProcessInstanceByKey("testProcess"); + + // then + Object task1Name = runtimeService.getVariable(pi.getId(), "task1Name"); + assertThat(task1Name).isEqualTo("task1"); + + Object task2Name = runtimeService.getVariable(pi.getId(), "task2Name"); + assertThat(task2Name).isEqualTo("task2"); + } + + protected String setVariableScript(String name, String valueExpression) { + return scriptVariableName("execution") + ".setVariable('" + name + "', " + valueExpression + ")"; + } + + protected String scriptVariableName(String name) { + return variablePrefix + name; + } + + protected void deployProcess(String scriptFormat, String scriptText) { + BpmnModelInstance process = createProcess(scriptFormat, scriptText); + Deployment deployment = repositoryService.createDeployment() + .addModelInstance("testProcess.bpmn", process) + .deploy(); + + engineRule.manageDeployment(deployment); + } + + protected BpmnModelInstance createProcess(String scriptFormat, String scriptText) { + + return Bpmn.createExecutableProcess("testProcess") + .startEvent() + .scriptTask() + .scriptFormat(scriptFormat) + .scriptText(scriptText) + .userTask() + .endEvent() + .done(); + + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinScriptTaskSupportWithAutoStoreScriptVariablesTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinScriptTaskSupportWithAutoStoreScriptVariablesTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f442c21958779cc14d8c072145bc9d42910e127d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/SpinScriptTaskSupportWithAutoStoreScriptVariablesTest.java @@ -0,0 +1,168 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.script; + +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import java.util.Map; + +/** + * @author Daniel Meyer + * + */ +public class SpinScriptTaskSupportWithAutoStoreScriptVariablesTest extends PluggableProcessEngineTestCase { + + protected static String TEST_SCRIPT = "var_s = S('{}')\n" + + "var_xml = XML('')\n" + + "var_json = JSON('{}')\n"; + + protected ProcessInstance processInstance; + + public void setUp() { + processEngineConfiguration.setAutoStoreScriptVariables(true); + } + + public void tearDown() { + processEngineConfiguration.setAutoStoreScriptVariables(false); + } + + public void testSpinInternalVariablesNotExportedGroovyScriptTask() { + String importXML = "XML = org.camunda.spin.Spin.&XML\n"; + String importJSON = "JSON = org.camunda.spin.Spin.&JSON\n"; + + String script = importXML + importJSON + TEST_SCRIPT; + + deployProcess("groovy", script); + + startProcess(); + checkVariables("foo", "var_s", "var_xml", "var_json"); + continueProcess(); + checkVariables("foo", "var_s", "var_xml", "var_json"); + } + + // Check https://jira.camunda.com/browse/CAM-5869 + public void FAILING_testSpinInternalVariablesNotExportedByJavascriptScriptTask() { + String importXML = "var XML = org.camunda.spin.Spin.XML;\n"; + String importJSON = "var JSON = org.camunda.spin.Spin.JSON;\n"; + + String script = importXML + importJSON + TEST_SCRIPT; + + deployProcess("javascript", script); + + startProcess(); + checkVariables("foo", "var_s", "var_xml", "var_json"); + continueProcess(); + checkVariables("foo", "var_s", "var_xml", "var_json"); + } + + public void testSpinInternalVariablesNotExportedByPythonScriptTask() { + String importXML = "import org.camunda.spin.Spin.XML as XML;\n"; + String importJSON = "import org.camunda.spin.Spin.JSON as JSON;\n"; + + String script = importXML + importJSON + TEST_SCRIPT; + + deployProcess("python", script); + + startProcess(); + checkVariables("foo", "var_s", "var_xml", "var_json"); + continueProcess(); + checkVariables("foo", "var_s", "var_xml", "var_json"); + } + + public void testSpinInternalVariablesNotExportedByRubyScriptTask() { + String importXML = "def XML(*args)\n\torg.camunda.spin.Spin.XML(*args)\nend\n"; + String importJSON = "def JSON(*args)\n\torg.camunda.spin.Spin.JSON(*args)\nend\n"; + + String script = importXML + importJSON + TEST_SCRIPT; + + deployProcess("ruby", script); + + startProcess(); + checkVariablesJRuby("foo"); + continueProcess(); + checkVariablesJRuby("foo"); + } + + protected void startProcess() { + VariableMap variables = Variables.putValue("foo", "bar"); + processInstance = runtimeService.startProcessInstanceByKey("testProcess", variables); + } + + protected void continueProcess() { + Task task = taskService.createTaskQuery().singleResult(); + assertNotNull(task); + taskService.complete(task.getId()); + } + + protected void checkVariables(String... expectedVariables) { + Map variables = runtimeService.getVariables(processInstance.getId()); + checkVariablesValues(expectedVariables, variables); + + assertEquals(expectedVariables.length, variables.size()); + } + + protected void checkVariablesJRuby(String... expectedVariables) { + + Map variables = runtimeService.getVariables(processInstance.getId()); + checkVariablesValues(expectedVariables, variables); + + // do not assert number of actual variables here, because JRuby leaks variables (see CAM-11114) + } + + protected void checkVariablesValues(String[] expectedVariables, Map actualVariables) { + + assertFalse(actualVariables.containsKey("S")); + assertFalse(actualVariables.containsKey("XML")); + assertFalse(actualVariables.containsKey("JSON")); + + for (String expectedVariable : expectedVariables) { + assertTrue(actualVariables.containsKey(expectedVariable)); + } + } + + protected void deployProcess(String scriptFormat, String scriptText) { + BpmnModelInstance process = createProcess(scriptFormat, scriptText); + Deployment deployment = repositoryService.createDeployment() + .addModelInstance("testProcess.bpmn", process) + .addString("testScript.txt", scriptText) + .deploy(); + deploymentId = deployment.getId(); + } + + protected BpmnModelInstance createProcess(String scriptFormat, String scriptText) { + + return Bpmn.createExecutableProcess("testProcess") + .startEvent() + .scriptTask() + .scriptFormat(scriptFormat) + .scriptText(scriptText) + .userTask() + .scriptTask() + .scriptFormat(scriptFormat) + .camundaResource("deployment://testScript.txt") + .userTask() + .endEvent() + .done(); + + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/TestVariableScope.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/TestVariableScope.java new file mode 100644 index 0000000000000000000000000000000000000000..75fbeaf8014f34a5d77161b28225ba1b1264af0e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/script/TestVariableScope.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.script; + +import java.util.Collections; +import java.util.List; + +import org.camunda.bpm.engine.impl.core.variable.CoreVariableInstance; +import org.camunda.bpm.engine.impl.core.variable.scope.AbstractVariableScope; +import org.camunda.bpm.engine.impl.core.variable.scope.SimpleVariableInstance; +import org.camunda.bpm.engine.impl.core.variable.scope.VariableInstanceFactory; +import org.camunda.bpm.engine.impl.core.variable.scope.VariableInstanceLifecycleListener; +import org.camunda.bpm.engine.impl.core.variable.scope.VariableStore; +import org.camunda.bpm.engine.impl.core.variable.scope.SimpleVariableInstance.SimpleVariableInstanceFactory; + +/** + * Simple standalone variable scope which can be used in testcases. + * + * @author Daniel Meyer + * + */ +public class TestVariableScope extends AbstractVariableScope { + + protected VariableStore variableStore = new VariableStore(); + + protected VariableStore getVariableStore() { + return (VariableStore) variableStore; + } + + public AbstractVariableScope getParentVariableScope() { + return null; + } + + @Override + protected VariableInstanceFactory getVariableInstanceFactory() { + return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE; + } + + @Override + protected List> getVariableInstanceLifecycleListeners() { + return Collections.emptyList(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/DmnBusinessRuleTaskResultMappingTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/DmnBusinessRuleTaskResultMappingTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1bdb80b273848b1c890213fbe1144117a38745e4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/DmnBusinessRuleTaskResultMappingTest.java @@ -0,0 +1,85 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import java.util.Collections; + +import org.camunda.bpm.engine.impl.test.ResourceProcessEngineTestCase; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.Variables; + +/** + * The test is copied from the engine to check how JSON serialization will behave with DMN result object. + * + * @author Svetlana Dorokhova + */ +public class DmnBusinessRuleTaskResultMappingTest extends ResourceProcessEngineTestCase { + + protected static final String TEST_DECISION = "org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.dmn11.xml"; + protected static final String CUSTOM_MAPPING_BPMN = "org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testCustomOutputMapping.bpmn20.xml"; + protected static final String SINGLE_ENTRY_BPMN = "org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testSingleEntry.bpmn20.xml"; + protected static final String DEFAULT_MAPPING_BPMN = "org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testDefaultMapping.bpmn20.xml"; + protected static final String STORE_DECISION_RESULT_BPMN = "org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testStoreDecisionResult.bpmn20.xml"; + + public DmnBusinessRuleTaskResultMappingTest() { + super("org/camunda/spin/plugin/json.camunda.cfg.xml"); + } + + @Deployment(resources = {STORE_DECISION_RESULT_BPMN, TEST_DECISION }) + public void testStoreDecisionResult() { + ProcessInstance processInstance = startTestProcess("multiple entries"); + + //deserialization is not working for this type of object -> deserializeValue parameter is false + assertNotNull(runtimeService.getVariableTyped(processInstance.getId(), "result", false)); + } + + @Deployment(resources = {CUSTOM_MAPPING_BPMN, TEST_DECISION }) + public void testCustomOutputMapping() { + ProcessInstance processInstance = startTestProcess("multiple entries"); + + assertEquals("foo", runtimeService.getVariable(processInstance.getId(), "result1")); + assertEquals(Variables.stringValue("foo"), runtimeService.getVariableTyped(processInstance.getId(), "result1")); + + assertEquals("bar", runtimeService.getVariable(processInstance.getId(), "result2")); + assertEquals(Variables.stringValue("bar"), runtimeService.getVariableTyped(processInstance.getId(), "result2")); + } + + @Deployment(resources = { SINGLE_ENTRY_BPMN, TEST_DECISION}) + public void testSingleEntryMapping() { + ProcessInstance processInstance = startTestProcess("single entry"); + + assertEquals("foo", runtimeService.getVariable(processInstance.getId(), "result")); + assertEquals(Variables.stringValue("foo"), runtimeService.getVariableTyped(processInstance.getId(), "result")); + } + + @Deployment(resources = { DEFAULT_MAPPING_BPMN, TEST_DECISION }) + public void testTransientDecisionResult() { + // when a decision is evaluated and the result is stored in a transient variable "decisionResult" + ProcessInstance processInstance = startTestProcess("single entry"); + + // then the variable should not be available outside the business rule task + assertNull(runtimeService.getVariable(processInstance.getId(), "decisionResult")); + // and should not create an entry in history since it is not persistent + assertNull(historyService.createHistoricVariableInstanceQuery().variableName("decisionResult").singleResult()); + } + + protected ProcessInstance startTestProcess(String input) { + return runtimeService.startProcessInstanceByKey("testProcess", Collections.singletonMap("input", input)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingDeserializationBean.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingDeserializationBean.java new file mode 100644 index 0000000000000000000000000000000000000000..379ae5d065f76d99863acdf014d072f29150fe55 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingDeserializationBean.java @@ -0,0 +1,28 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +public class FailingDeserializationBean extends JsonSerializable { + + public FailingDeserializationBean() { + throw new RuntimeException("I am failing"); + } + + public FailingDeserializationBean(String stringProperty, int intProperty, boolean booleanProperty) { + super(stringProperty, intProperty, booleanProperty); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingSerializationBean.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingSerializationBean.java new file mode 100644 index 0000000000000000000000000000000000000000..9995a6a47dd32ac65c0034770999ddb5590172bf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingSerializationBean.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +public class FailingSerializationBean extends JsonSerializable { + + public FailingSerializationBean() { + } + + public FailingSerializationBean(String stringProperty, int intProperty, boolean booleanProperty) { + super(stringProperty, intProperty, booleanProperty); + } + + public String getStringProperty() { + throw new RuntimeException("I am failing"); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingXmlDeserializationBean.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingXmlDeserializationBean.java new file mode 100644 index 0000000000000000000000000000000000000000..ca01b57a95ed9fd3648abc1c27b461dae2b47f1b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingXmlDeserializationBean.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class FailingXmlDeserializationBean extends JsonSerializable { + + public FailingXmlDeserializationBean() { + throw new RuntimeException("I am failing"); + } + + public FailingXmlDeserializationBean(String stringProperty, int intProperty, boolean booleanProperty) { + super(stringProperty, intProperty, booleanProperty); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingXmlSerializable.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingXmlSerializable.java new file mode 100644 index 0000000000000000000000000000000000000000..db06c06322a85f7f501ee4543e280bc7eb1ffb0d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FailingXmlSerializable.java @@ -0,0 +1,34 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class FailingXmlSerializable extends XmlSerializable { + + public FailingXmlSerializable() { + } + + public FailingXmlSerializable(String stringProperty, int intProperty, boolean booleanProperty) { + super(stringProperty, intProperty, booleanProperty); + } + + public String getStringProperty() { + throw new RuntimeException("I am failing"); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FallbackSerializationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FallbackSerializationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a578bf20020e49281428791d18e97287b1efb91f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/FallbackSerializationTest.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.impl.variable.serializer.VariableSerializerFactory; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.junit.Test; + +/** + * @author Thorben Lindhauer + * + */ +public class FallbackSerializationTest extends PluggableProcessEngineTestCase { + + protected static final String ONE_TASK_PROCESS = "org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml"; + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSerializationOfUnknownFormat() { + // given + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // when + ObjectValue objectValue = Variables.serializedObjectValue("foo") + .serializationDataFormat("application/foo") + .objectTypeName("org.camunda.Foo") + .create(); + + runtimeService.setVariable(instance.getId(), "var", objectValue); + + // then + try { + runtimeService.getVariable(instance.getId(), "var"); + fail(); + } catch (ProcessEngineException e) { + assertTextPresent("Fallback serializer cannot handle deserialized objects", e.getMessage()); + } + + ObjectValue returnedValue = runtimeService.getVariableTyped(instance.getId(), "var", false); + assertFalse(returnedValue.isDeserialized()); + assertEquals("application/foo", returnedValue.getSerializationDataFormat()); + assertEquals("foo", returnedValue.getValueSerialized()); + assertEquals("org.camunda.Foo", returnedValue.getObjectTypeName()); + + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricDecisionInstanceSerializationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricDecisionInstanceSerializationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c8aa231037d1ba1344719740cb301757be35600e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricDecisionInstanceSerializationTest.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import java.util.List; + +import org.camunda.bpm.engine.history.HistoricDecisionInputInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricDecisionOutputInstance; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.spin.DataFormats; + +public class HistoricDecisionInstanceSerializationTest extends PluggableProcessEngineTestCase { + + @Deployment(resources = {"org/camunda/spin/plugin/DecisionSingleOutput.dmn11.xml"}) + public void testListJsonProperty() { + JsonListSerializable list = new JsonListSerializable(); + list.addElement("foo"); + + ObjectValue objectValue = Variables.objectValue(list).serializationDataFormat(DataFormats.JSON_DATAFORMAT_NAME).create(); + + VariableMap variables = Variables.createVariables() + .putValueTyped("input1", objectValue); + + decisionService.evaluateDecisionTableByKey("testDecision", variables); + + HistoricDecisionInstance testDecision = historyService.createHistoricDecisionInstanceQuery().decisionDefinitionKey("testDecision").includeInputs().includeOutputs().singleResult(); + assertNotNull(testDecision); + + List inputs = testDecision.getInputs(); + assertEquals(1, inputs.size()); + + HistoricDecisionInputInstance inputInstance = inputs.get(0); + assertEquals(list.getListProperty(), inputInstance.getValue()); + + List outputs = testDecision.getOutputs(); + assertEquals(1, outputs.size()); + + HistoricDecisionOutputInstance outputInstance = outputs.get(0); + assertEquals(list.getListProperty(), outputInstance.getValue()); + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricVariableJsonSerializationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricVariableJsonSerializationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4a25aabeb6af987d21b13c5964b623dc07cc05a0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricVariableJsonSerializationTest.java @@ -0,0 +1,142 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.camunda.bpm.engine.variable.Variables.objectValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.history.HistoryLevel; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.spin.DataFormats; +import org.json.JSONException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +public class HistoricVariableJsonSerializationTest { + + protected static final String ONE_TASK_PROCESS = "org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml"; + + protected static final String JSON_FORMAT_NAME = DataFormats.json().getName(); + + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(true); + + protected HistoryService historyService; + protected ProcessEngineConfigurationImpl processEngineConfiguration; + protected RuntimeService runtimeService; + + @Before + public void setUp() { + historyService = engineRule.getHistoryService(); + processEngineConfiguration = engineRule.getProcessEngineConfiguration(); + runtimeService = engineRule.getRuntimeService(); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSelectHistoricVariableInstances() throws JSONException { + if (processEngineConfiguration.getHistoryLevel().getId() >= + HistoryLevel.HISTORY_LEVEL_AUDIT.getId()) { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + JsonSerializable bean = new JsonSerializable("a String", 42, false); + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(JSON_FORMAT_NAME).create()); + + HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery().singleResult(); + assertNotNull(historicVariable.getValue()); + assertNull(historicVariable.getErrorMessage()); + + assertEquals(ValueType.OBJECT.getName(), historicVariable.getTypeName()); + assertEquals(ValueType.OBJECT.getName(), historicVariable.getVariableTypeName()); + + JsonSerializable historyValue = (JsonSerializable) historicVariable.getValue(); + assertEquals(bean.getStringProperty(), historyValue.getStringProperty()); + assertEquals(bean.getIntProperty(), historyValue.getIntProperty()); + assertEquals(bean.getBooleanProperty(), historyValue.getBooleanProperty()); + } + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSelectHistoricSerializedValues() throws JSONException { + if (processEngineConfiguration.getHistoryLevel().getId() >= + HistoryLevel.HISTORY_LEVEL_AUDIT.getId()) { + + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + JsonSerializable bean = new JsonSerializable("a String", 42, false); + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(JSON_FORMAT_NAME)); + + HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery().singleResult(); + assertNotNull(historicVariable.getValue()); + assertNull(historicVariable.getErrorMessage()); + + ObjectValue typedValue = (ObjectValue) historicVariable.getTypedValue(); + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + JSONAssert.assertEquals(bean.toExpectedJsonString(),new String(typedValue.getValueSerialized()), true); + assertEquals(JsonSerializable.class.getName(), typedValue.getObjectTypeName()); + } + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSelectHistoricSerializedValuesUpdate() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + JsonSerializable bean = new JsonSerializable("a String", 42, false); + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(JSON_FORMAT_NAME)); + + if (ProcessEngineConfiguration.HISTORY_FULL.equals(processEngineConfiguration.getHistory())) { + + HistoricVariableUpdate historicUpdate = (HistoricVariableUpdate) + historyService.createHistoricDetailQuery().variableUpdates().singleResult(); + + assertNotNull(historicUpdate.getValue()); + assertNull(historicUpdate.getErrorMessage()); + + assertEquals(ValueType.OBJECT.getName(), historicUpdate.getTypeName()); + assertEquals(ValueType.OBJECT.getName(), historicUpdate.getVariableTypeName()); + + JsonSerializable historyValue = (JsonSerializable) historicUpdate.getValue(); + assertEquals(bean.getStringProperty(), historyValue.getStringProperty()); + assertEquals(bean.getIntProperty(), historyValue.getIntProperty()); + assertEquals(bean.getBooleanProperty(), historyValue.getBooleanProperty()); + + ObjectValue typedValue = (ObjectValue) historicUpdate.getTypedValue(); + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + JSONAssert.assertEquals(bean.toExpectedJsonString(),new String(typedValue.getValueSerialized()), true); + assertEquals(JsonSerializable.class.getName(), typedValue.getObjectTypeName()); + + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricVariableJsonSerializationWithValidationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricVariableJsonSerializationWithValidationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d0b21d043b9a2b74321a5419a9cda48398d7632c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/HistoricVariableJsonSerializationWithValidationTest.java @@ -0,0 +1,36 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.runtime.DeserializationTypeValidator; +import org.junit.Before; + +public class HistoricVariableJsonSerializationWithValidationTest extends HistoricVariableJsonSerializationTest { + + @Before + public void setUpValidator() { + DeserializationTypeValidator validatorMock = mock(DeserializationTypeValidator.class); + when(validatorMock.validate(anyString())).thenReturn(true); + processEngineConfiguration.setDeserializationTypeValidationEnabled(true); + processEngineConfiguration.setDeserializationTypeValidator(validatorMock); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JavaSerializable.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JavaSerializable.java new file mode 100644 index 0000000000000000000000000000000000000000..89a1b9e44a844e17bf89eb0719fcfdbe006de199 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JavaSerializable.java @@ -0,0 +1,94 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import java.io.Serializable; + +public class JavaSerializable implements Serializable { + + private String stringProperty; + + private int intProperty; + + private boolean booleanProperty; + + public JavaSerializable() { + + } + + public JavaSerializable(String stringProperty, int intProperty, boolean booleanProperty) { + this.stringProperty = stringProperty; + this.intProperty = intProperty; + this.booleanProperty = booleanProperty; + } + + public String getStringProperty() { + return stringProperty; + } + + public void setStringProperty(String stringProperty) { + this.stringProperty = stringProperty; + } + + public int getIntProperty() { + return intProperty; + } + + public void setIntProperty(int intProperty) { + this.intProperty = intProperty; + } + + public boolean getBooleanProperty() { + return booleanProperty; + } + + public void setBooleanProperty(boolean booleanProperty) { + this.booleanProperty = booleanProperty; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (booleanProperty ? 1231 : 1237); + result = prime * result + intProperty; + result = prime * result + ((stringProperty == null) ? 0 : stringProperty.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JavaSerializable other = (JavaSerializable) obj; + if (booleanProperty != other.booleanProperty) + return false; + if (intProperty != other.intProperty) + return false; + if (stringProperty == null) { + if (other.stringProperty != null) + return false; + } else if (!stringProperty.equals(other.stringProperty)) + return false; + return true; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JavaSerializationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JavaSerializationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d44c73dfe7da69ba74a16dc03a5e3afe36751f34 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JavaSerializationTest.java @@ -0,0 +1,137 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.json.JSONException; +import static org.camunda.bpm.engine.variable.Variables.objectValue; +import static org.camunda.bpm.engine.variable.Variables.serializedObjectValue; + +/** + * Here we test how the engine behaves, when more than one object serializers are available. + * + * @author Svetlana Dorokhova + */ +public class JavaSerializationTest extends PluggableProcessEngineTestCase { + + protected static final String ONE_TASK_PROCESS = "org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml"; + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSerializationAsJava() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + JavaSerializable bean = new JavaSerializable("a String", 42, true); + // request object to be serialized as Java + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(Variables.SerializationDataFormats.JAVA).create()); + + // validate untyped value + Object value = runtimeService.getVariable(instance.getId(), "simpleBean"); + assertEquals(bean, value); + + // validate typed value + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertEquals(ValueType.OBJECT, typedValue.getType()); + + assertTrue(typedValue.isDeserialized()); + + assertEquals(bean, typedValue.getValue()); + assertEquals(bean, typedValue.getValue(JavaSerializable.class)); + assertEquals(JavaSerializable.class, typedValue.getObjectType()); + + assertEquals(Variables.SerializationDataFormats.JAVA.getName(), typedValue.getSerializationDataFormat()); + assertEquals(JavaSerializable.class.getName(), typedValue.getObjectTypeName()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testJavaSerializedValuesAreProhibited() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + try { + // request object to be serialized as Java + runtimeService + .setVariable(instance.getId(), "simpleBean", serializedObjectValue("").serializationDataFormat(Variables.SerializationDataFormats.JAVA).create()); + fail("Exception is expected."); + } catch (ProcessEngineException ex) { + assertEquals("ENGINE-17007 Cannot set variable with name simpleBean. Java serialization format is prohibited", ex.getMessage()); + } + + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testJavaSerializedValuesAreProhibitedForTransient() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + try { + // request object to be serialized as Java + runtimeService + .setVariable(instance.getId(), "simpleBean", serializedObjectValue("").serializationDataFormat(Variables.SerializationDataFormats.JAVA).create()); + fail("Exception is expected."); + } catch (ProcessEngineException ex) { + assertEquals("ENGINE-17007 Cannot set variable with name simpleBean. Java serialization format is prohibited", ex.getMessage()); + } + + } + + public void testStandaloneTaskVariable() { + Task task = taskService.newTask(); + task.setName("gonzoTask"); + taskService.saveTask(task); + + String taskId = task.getId(); + + try { + taskService + .setVariable(taskId, "instrument", Variables.serializedObjectValue("trumpet").serializationDataFormat(Variables.SerializationDataFormats.JAVA).create()); + fail("Exception is expected."); + } catch (ProcessEngineException ex) { + assertEquals("ENGINE-17007 Cannot set variable with name instrument. Java serialization format is prohibited", ex.getMessage()); + } finally { + taskService.deleteTask(taskId, true); + } + + } + + public void testStandaloneTaskTransientVariable() { + Task task = taskService.newTask(); + task.setName("gonzoTask"); + taskService.saveTask(task); + + String taskId = task.getId(); + + try { + taskService + .setVariable(taskId, "instrument", Variables.serializedObjectValue("trumpet") + .serializationDataFormat(Variables.SerializationDataFormats.JAVA) + .setTransient(true) + .create()); + fail("Exception is expected."); + } catch (ProcessEngineException ex) { + assertEquals("ENGINE-17007 Cannot set variable with name instrument. Java serialization format is prohibited", ex.getMessage()); + } finally { + taskService.deleteTask(taskId, true); + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonDelegate.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..36dbfcf65593745754b3cd6c4f0862dcd8492c97 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonDelegate.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.camunda.spin.plugin.variable.SpinValues.jsonValue; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Tassilo Weidner + */ +public class JsonDelegate implements JavaDelegate { + + public void execute(DelegateExecution execution) { + execution.setVariable("jsonVariable", Variables.untypedValue(jsonValue("{}"),true)); + + // when + TypedValue typedValue = execution.getVariableTyped("jsonVariable"); + + // then + assertThat(typedValue.isTransient(), is(true)); + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonListSerializable.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonListSerializable.java new file mode 100644 index 0000000000000000000000000000000000000000..8dd426ba77ce152a579d772521ab8dbcc480f302 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonListSerializable.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import java.util.ArrayList; +import java.util.List; + +public class JsonListSerializable { + + private List listProperty; + + public JsonListSerializable() { + this.listProperty = new ArrayList(); + } + + public void addElement(T element) { + this.listProperty.add(element); + } + + public List getListProperty() { + return listProperty; + } + + public void setListProperty(List listProperty) { + this.listProperty = listProperty; + } + + public String toExpectedJsonString() { + StringBuilder jsonBuilder = new StringBuilder(); + + jsonBuilder.append("{\"listProperty\":["); + for (int i = 0; i < listProperty.size(); i++) { + jsonBuilder.append(listProperty.get(i)); + if (i < listProperty.size() - 1) { + jsonBuilder.append(","); + } + } + jsonBuilder.append("]}"); + + return jsonBuilder.toString(); + } + + public String toString() { + return toExpectedJsonString(); + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializable.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializable.java new file mode 100644 index 0000000000000000000000000000000000000000..523251dc871e4d8702af1a9ae58bd3787ca3cbb4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializable.java @@ -0,0 +1,111 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + + +public class JsonSerializable { + + private String stringProperty; + + private int intProperty; + + private boolean booleanProperty; + + public JsonSerializable() { + + } + + public JsonSerializable(String stringProperty, int intProperty, boolean booleanProperty) { + this.stringProperty = stringProperty; + this.intProperty = intProperty; + this.booleanProperty = booleanProperty; + } + + public String getStringProperty() { + return stringProperty; + } + + public void setStringProperty(String stringProperty) { + this.stringProperty = stringProperty; + } + + public int getIntProperty() { + return intProperty; + } + + public void setIntProperty(int intProperty) { + this.intProperty = intProperty; + } + + public boolean getBooleanProperty() { + return booleanProperty; + } + + public void setBooleanProperty(boolean booleanProperty) { + this.booleanProperty = booleanProperty; + } + + public String toExpectedJsonString() { + StringBuilder jsonBuilder = new StringBuilder(); + + jsonBuilder.append("{\"stringProperty\":\""); + jsonBuilder.append(stringProperty); + jsonBuilder.append("\",\"intProperty\":"); + jsonBuilder.append(intProperty); + jsonBuilder.append(",\"booleanProperty\":"); + jsonBuilder.append(booleanProperty); + jsonBuilder.append("}"); + + return jsonBuilder.toString(); + } + + public String toString() { + return toExpectedJsonString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (booleanProperty ? 1231 : 1237); + result = prime * result + intProperty; + result = prime * result + ((stringProperty == null) ? 0 : stringProperty.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + JsonSerializable other = (JsonSerializable) obj; + if (booleanProperty != other.booleanProperty) + return false; + if (intProperty != other.intProperty) + return false; + if (stringProperty == null) { + if (other.stringProperty != null) + return false; + } else if (!stringProperty.equals(other.stringProperty)) + return false; + return true; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7b6a9442fad543f729d0240c7a2ac193890a6cdd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationTest.java @@ -0,0 +1,624 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.camunda.bpm.engine.variable.Variables.objectValue; +import static org.camunda.bpm.engine.variable.Variables.serializedObjectValue; +import static org.camunda.spin.plugin.variables.TypedValueAssert.assertObjectValueDeserializedNull; +import static org.camunda.spin.plugin.variables.TypedValueAssert.assertObjectValueSerializedNull; +import static org.camunda.spin.plugin.variables.TypedValueAssert.assertUntypedNullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.impl.interceptor.Command; +import org.camunda.bpm.engine.impl.interceptor.CommandContext; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.engine.test.util.ProcessEngineTestRule; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.camunda.bpm.engine.variable.value.builder.SerializedObjectValueBuilder; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.camunda.spin.DataFormats; +import org.json.JSONException; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.skyscreamer.jsonassert.JSONAssert; + +public class JsonSerializationTest { + + protected static final String ONE_TASK_PROCESS = "org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml"; + protected static final String SERVICE_TASK_PROCESS = "org/camunda/spin/plugin/serviceTaskProcess.bpmn20.xml"; + + protected static final String JSON_FORMAT_NAME = DataFormats.JSON_DATAFORMAT_NAME; + + @Rule + public ProcessEngineRule engineRule = new ProcessEngineRule(true); + + @Rule + public ProcessEngineTestRule testRule = new ProcessEngineTestRule(engineRule); + + protected RuntimeService runtimeService; + + protected String originalSerializationFormat; + + @Before + public void setUp() { + runtimeService = engineRule.getRuntimeService(); + } + + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSerializationAsJson() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + JsonSerializable bean = new JsonSerializable("a String", 42, true); + // request object to be serialized as JSON + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(JSON_FORMAT_NAME).create()); + + // validate untyped value + Object value = runtimeService.getVariable(instance.getId(), "simpleBean"); + assertEquals(bean, value); + + // validate typed value + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertEquals(ValueType.OBJECT, typedValue.getType()); + + assertTrue(typedValue.isDeserialized()); + + assertEquals(bean, typedValue.getValue()); + assertEquals(bean, typedValue.getValue(JsonSerializable.class)); + assertEquals(JsonSerializable.class, typedValue.getObjectType()); + + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertEquals(JsonSerializable.class.getName(), typedValue.getObjectTypeName()); + JSONAssert.assertEquals(bean.toExpectedJsonString(), new String(typedValue.getValueSerialized()), true); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testListSerializationAsJson() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + List beans = new ArrayList<>(); + for (int i = 0; i < 20; i++) { + beans.add(new JsonSerializable("a String" + i, 42 + i, true)); + } + + runtimeService.setVariable(instance.getId(), "simpleBeans", objectValue(beans).serializationDataFormat(JSON_FORMAT_NAME).create()); + + // validate untyped value + Object value = runtimeService.getVariable(instance.getId(), "simpleBeans"); + assertEquals(beans, value); + + // validate typed value + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBeans"); + assertEquals(ValueType.OBJECT, typedValue.getType()); + assertEquals(beans, typedValue.getValue()); + assertTrue(typedValue.isDeserialized()); + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertNotNull(typedValue.getObjectTypeName()); + JSONAssert.assertEquals(toExpectedJsonArray(beans), new String(typedValue.getValueSerialized()), true); + + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailingSerialization() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + FailingSerializationBean failingBean = new FailingSerializationBean("a String", 42, true); + + try { + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(failingBean).serializationDataFormat(JSON_FORMAT_NAME)); + fail("exception expected"); + } catch (ProcessEngineException e) { + // happy path + } + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailingDeserialization() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + FailingDeserializationBean failingBean = new FailingDeserializationBean("a String", 42, true); + + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(failingBean).serializationDataFormat(JSON_FORMAT_NAME)); + + try { + runtimeService.getVariable(instance.getId(), "simpleBean"); + fail("exception expected"); + } + catch(ProcessEngineException e) { + // happy path + } + + try { + runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + fail("exception expected"); + } + catch(ProcessEngineException e) { + // happy path + } + + // However, I can access the serialized value + ObjectValue objectValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean", false); + assertFalse(objectValue.isDeserialized()); + assertNotNull(objectValue.getObjectTypeName()); + assertNotNull(objectValue.getValueSerialized()); + // but not the deserialized properties + try { + objectValue.getValue(); + fail("exception expected"); + } + catch(IllegalStateException e) { + testRule.assertTextPresent("Object is not deserialized", e.getMessage()); + } + + try { + objectValue.getValue(JsonSerializable.class); + fail("exception expected"); + } + catch(IllegalStateException e) { + testRule.assertTextPresent("Object is not deserialized", e.getMessage()); + } + + try { + objectValue.getObjectType(); + fail("exception expected"); + } + catch(IllegalStateException e) { + testRule.assertTextPresent("Object is not deserialized", e.getMessage()); + } + + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailForNonExistingSerializationFormat() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + JsonSerializable jsonSerializable = new JsonSerializable(); + + try { + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(jsonSerializable).serializationDataFormat("non existing data format")); + fail("Exception expected"); + } catch (ProcessEngineException e) { + testRule.assertTextPresent("Cannot find serializer for value", e.getMessage()); + // happy path + } + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testVariableValueCaching() { + final ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + engineRule.getProcessEngineConfiguration().getCommandExecutorTxRequired().execute(new Command() { + + @Override + public Void execute(CommandContext commandContext) { + JsonSerializable bean = new JsonSerializable("a String", 42, true); + runtimeService.setVariable(instance.getId(), "simpleBean", bean); + + Object returnedBean = runtimeService.getVariable(instance.getId(), "simpleBean"); + assertSame(bean, returnedBean); + + return null; + } + }); + + VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult(); + + Object returnedBean = variableInstance.getValue(); + Object theSameReturnedBean = variableInstance.getValue(); + assertSame(returnedBean, theSameReturnedBean); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testGetSerializedVariableValue() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + JsonSerializable bean = new JsonSerializable("a String", 42, true); + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(JSON_FORMAT_NAME).create()); + + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean", false); + + String serializedValue = typedValue.getValueSerialized(); + JSONAssert.assertEquals(bean.toExpectedJsonString(), serializedValue, true); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValue() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + JsonSerializable bean = new JsonSerializable("a String", 42, true); + String beanAsJson = bean.toExpectedJsonString(); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue(beanAsJson) + .serializationDataFormat(JSON_FORMAT_NAME) + .objectTypeName(bean.getClass().getCanonicalName()); + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + // java object can be retrieved + JsonSerializable returnedBean = (JsonSerializable) runtimeService.getVariable(instance.getId(), "simpleBean"); + assertEquals(bean, returnedBean); + + // validate typed value metadata + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertEquals(bean, typedValue.getValue()); + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertEquals(bean.getClass().getCanonicalName(), typedValue.getObjectTypeName()); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueNoTypeName() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + JsonSerializable bean = new JsonSerializable("a String", 42, true); + String beanAsJson = bean.toExpectedJsonString(); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue(beanAsJson) + .serializationDataFormat(JSON_FORMAT_NAME); + // no type name + + try { + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + fail("Exception expected."); + } + catch(Exception e) { + testRule.assertTextPresent("no 'objectTypeName' provided for non-null value", e.getMessage()); + } + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueMismatchingTypeName() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + JsonSerializable bean = new JsonSerializable("a String", 42, true); + String beanAsJson = bean.toExpectedJsonString(); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue(beanAsJson) + .serializationDataFormat(JSON_FORMAT_NAME) + .objectTypeName("Insensible type name."); // < not a valid type name + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + try { + runtimeService.getVariable(instance.getId(), "simpleBean"); + fail("Exception expected."); + } + catch(Exception e) { + // happy path + } + + serializedValue = serializedObjectValue(beanAsJson) + .serializationDataFormat(JSON_FORMAT_NAME) + .objectTypeName(JsonSerializationTest.class.getName()); // < not the right type name + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + try { + runtimeService.getVariable(instance.getId(), "simpleBean"); + fail("Exception expected."); + } + catch(Exception e) { + // happy path + } + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueNull() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue() + .serializationDataFormat(JSON_FORMAT_NAME) + .objectTypeName(JsonSerializable.class.getCanonicalName()); + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + // null can be retrieved + JsonSerializable returnedBean = (JsonSerializable) runtimeService.getVariable(instance.getId(), "simpleBean"); + assertNull(returnedBean); + + // validate typed value metadata + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertNull(typedValue.getValue()); + assertNull(typedValue.getValueSerialized()); + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertEquals(JsonSerializable.class.getCanonicalName(), typedValue.getObjectTypeName()); + + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueNullNoTypeName() throws JSONException { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue() + .serializationDataFormat(JSON_FORMAT_NAME); + // no objectTypeName specified + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + // null can be retrieved + JsonSerializable returnedBean = (JsonSerializable) runtimeService.getVariable(instance.getId(), "simpleBean"); + assertNull(returnedBean); + + // validate typed value metadata + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertNull(typedValue.getValue()); + assertNull(typedValue.getValueSerialized()); + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertNull(typedValue.getObjectTypeName()); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetJavaOjectNullDeserialized() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // set null value as "deserialized" object + runtimeService.setVariable(instance.getId(), "nullObject", + objectValue(null) + .serializationDataFormat(JSON_FORMAT_NAME) + .create()); + + // get null value via untyped api + assertNull(runtimeService.getVariable(instance.getId(), "nullObject")); + + // get null via typed api + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject"); + assertObjectValueDeserializedNull(typedValue); + + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetJavaOjectNullSerialized() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // set null value as "serialized" object + runtimeService.setVariable(instance.getId(), "nullObject", + serializedObjectValue() + .serializationDataFormat(JSON_FORMAT_NAME) + .create()); // Note: no object type name provided + + // get null value via untyped api + assertNull(runtimeService.getVariable(instance.getId(), "nullObject")); + + // get null via typed api + ObjectValue deserializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject"); + assertObjectValueDeserializedNull(deserializedTypedValue); + + ObjectValue serializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject", false); + assertObjectValueSerializedNull(serializedTypedValue); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetJavaOjectNullSerializedObjectTypeName() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + String typeName = "some.type.Name"; + + // set null value as "serialized" object + runtimeService.setVariable(instance.getId(), "nullObject", + serializedObjectValue() + .serializationDataFormat(JSON_FORMAT_NAME) + .objectTypeName(typeName) // This time an objectTypeName is provided + .create()); + + // get null value via untyped api + assertNull(runtimeService.getVariable(instance.getId(), "nullObject")); + + // get null via typed api + ObjectValue deserializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject"); + assertNotNull(deserializedTypedValue); + assertTrue(deserializedTypedValue.isDeserialized()); + assertEquals(JSON_FORMAT_NAME, deserializedTypedValue.getSerializationDataFormat()); + assertNull(deserializedTypedValue.getValue()); + assertNull(deserializedTypedValue.getValueSerialized()); + assertNull(deserializedTypedValue.getObjectType()); + assertEquals(typeName, deserializedTypedValue.getObjectTypeName()); + + ObjectValue serializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject", false); + assertNotNull(serializedTypedValue); + assertFalse(serializedTypedValue.isDeserialized()); + assertEquals(JSON_FORMAT_NAME, serializedTypedValue.getSerializationDataFormat()); + assertNull(serializedTypedValue.getValueSerialized()); + assertEquals(typeName, serializedTypedValue.getObjectTypeName()); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetUntypedNullForExistingVariable() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // initially the variable has a value + JsonSerializable object = new JsonSerializable(); + + runtimeService.setVariable(instance.getId(), "varName", + objectValue(object) + .serializationDataFormat(JSON_FORMAT_NAME) + .create()); + + // get value via untyped api + assertEquals(object, runtimeService.getVariable(instance.getId(), "varName")); + + // set the variable to null via untyped Api + runtimeService.setVariable(instance.getId(), "varName", null); + + // variable is now untyped null + TypedValue nullValue = runtimeService.getVariableTyped(instance.getId(), "varName"); + assertUntypedNullValue(nullValue); + + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetTypedNullForExistingVariable() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // initially the variable has a value + JsonSerializable javaSerializable = new JsonSerializable(); + + runtimeService.setVariable(instance.getId(), "varName", + objectValue(javaSerializable) + .serializationDataFormat(JSON_FORMAT_NAME) + .create()); + + // get value via untyped api + assertEquals(javaSerializable, runtimeService.getVariable(instance.getId(), "varName")); + + // set the variable to null via typed Api + runtimeService.setVariable(instance.getId(), "varName", objectValue(null)); + + // variable is still of type object + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "varName"); + assertObjectValueDeserializedNull(typedValue); + } + + @Test + @Deployment(resources = ONE_TASK_PROCESS) + public void testRemoveVariable() throws JSONException { + // given a serialized json variable + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + JsonSerializable bean = new JsonSerializable("a String", 42, true); + String beanAsJson = bean.toExpectedJsonString(); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue(beanAsJson) + .serializationDataFormat(JSON_FORMAT_NAME) + .objectTypeName(bean.getClass().getCanonicalName()); + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + // when + runtimeService.removeVariable(instance.getId(), "simpleBean"); + + // then + assertNull(runtimeService.getVariable(instance.getId(), "simpleBean")); + assertNull(runtimeService.getVariableTyped(instance.getId(), "simpleBean")); + assertNull(runtimeService.getVariableTyped(instance.getId(), "simpleBean", false)); + } + + /** + * CAM-3222 + */ + @Test + @Deployment(resources = SERVICE_TASK_PROCESS) + public void testImplicitlyUpdateEmptyList() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("serviceTaskProcess", + Variables.createVariables() + .putValueTyped("listVar", + Variables.objectValue(new ArrayList()) + .serializationDataFormat("application/json").create()) + .putValue("delegate", new UpdateValueDelegate())); + + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "listVar"); + // this should match Jackson's format + String expectedTypeName = ArrayList.class.getName() + "<" + JsonSerializable.class.getName() + ">"; + assertEquals(expectedTypeName, typedValue.getObjectTypeName()); + + List list = (List) typedValue.getValue(); + assertEquals(1, list.size()); + assertTrue(list.get(0) instanceof JsonSerializable); + assertEquals(UpdateValueDelegate.STRING_PROPERTY, list.get(0).getStringProperty()); + } + + @Test + public void testTransientJsonValue() { + // given + BpmnModelInstance modelInstance = Bpmn.createExecutableProcess("foo") + .startEvent() + .exclusiveGateway("gtw") + .sequenceFlowId("flow1") + .condition("cond", "${x.stringProperty == \"bar\"}") + .userTask("userTask1") + .endEvent() + .moveToLastGateway() + .sequenceFlowId("flow2") + .userTask("userTask2") + .endEvent() + .done(); + + testRule.deploy(modelInstance); + + JsonSerializable bean = new JsonSerializable("bar", 42, true); + ObjectValue jsonValue = serializedObjectValue(bean.toExpectedJsonString(), true) + .serializationDataFormat(JSON_FORMAT_NAME) + .objectTypeName(JsonSerializable.class.getName()) + .create(); + VariableMap variables = Variables.createVariables().putValueTyped("x", jsonValue); + + // when + runtimeService.startProcessInstanceByKey("foo", variables); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + + Task task = engineRule.getTaskService().createTaskQuery().singleResult(); + assertNotNull(task); + assertEquals("userTask1", task.getTaskDefinitionKey()); + } + + protected String toExpectedJsonArray(List beans) { + StringBuilder jsonBuilder = new StringBuilder(); + + jsonBuilder.append("["); + for (int i = 0; i < beans.size(); i++) { + jsonBuilder.append(beans.get(i).toExpectedJsonString()); + + if (i != beans.size() - 1) { + jsonBuilder.append(", "); + } + } + jsonBuilder.append("]"); + + return jsonBuilder.toString(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationWithValidationOnMultipleEnginesTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationWithValidationOnMultipleEnginesTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d9c1769e32953dc2d22e979f280a628d4123b101 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationWithValidationOnMultipleEnginesTest.java @@ -0,0 +1,129 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.camunda.bpm.engine.variable.Variables.objectValue; +import static org.hamcrest.CoreMatchers.isA; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.runtime.DeserializationTypeValidator; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.test.ProcessEngineRule; +import org.camunda.bpm.engine.test.util.ProcessEngineBootstrapRule; +import org.camunda.bpm.engine.test.util.ProvidedProcessEngineRule; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.camunda.spin.DataFormats; +import org.camunda.spin.json.SpinJsonException; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +/** + * Test cases for multiple engines defining different validators that do not + * override each other although Spin makes heavy use of the {@link DataFormats} + * class that holds static references regardless of the number of Spin plugins + * (data formats are overridden for example because they are held once in the + * DataFormats class) + */ +public class JsonSerializationWithValidationOnMultipleEnginesTest { + + @ClassRule + public static ProcessEngineBootstrapRule bootstrapRulePositive = new ProcessEngineBootstrapRule(configuration -> { + DeserializationTypeValidator validatorMock = mock(DeserializationTypeValidator.class); + when(validatorMock.validate(anyString())).thenReturn(true); + configuration + .setDeserializationTypeValidator(validatorMock) + .setDeserializationTypeValidationEnabled(true) + .setJdbcUrl("jdbc:h2:mem:positive"); + }); + + @ClassRule + public static ProcessEngineBootstrapRule bootstrapRuleNegative = new ProcessEngineBootstrapRule(configuration -> { + DeserializationTypeValidator validatorMock = mock(DeserializationTypeValidator.class); + when(validatorMock.validate(anyString())).thenReturn(false); + configuration + .setDeserializationTypeValidator(validatorMock) + .setDeserializationTypeValidationEnabled(true) + .setJdbcUrl("jdbc:h2:mem:negative"); + }); + + @Rule + public ProcessEngineRule engineRulePositive = new ProvidedProcessEngineRule(bootstrapRulePositive); + + @Rule + public ProcessEngineRule engineRuleNegative = new ProvidedProcessEngineRule(bootstrapRuleNegative); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void shouldUsePositiveValidator() { + // given + engineRulePositive.manageDeployment(engineRulePositive.getRepositoryService().createDeployment() + .addModelInstance("foo.bpmn", getOneTaskModel()) + .deploy()); + ProcessInstance instance = engineRulePositive.getRuntimeService().startProcessInstanceByKey("oneTaskProcess"); + + // add serialized value + JsonSerializable bean = new JsonSerializable("a String", 42, true); + engineRulePositive.getRuntimeService().setVariable(instance.getId(), "simpleBean", + objectValue(bean).serializationDataFormat(DataFormats.JSON_DATAFORMAT_NAME).create()); + + // when + Object value = engineRulePositive.getRuntimeService().getVariable(instance.getId(), "simpleBean"); + + // then + assertEquals(bean, value); + } + + @Test + public void shouldUseNegativeValidator() { + // given + engineRuleNegative.manageDeployment(engineRuleNegative.getRepositoryService().createDeployment() + .addModelInstance("foo.bpmn", getOneTaskModel()) + .deploy()); + ProcessInstance instance = engineRuleNegative.getRuntimeService().startProcessInstanceByKey("oneTaskProcess"); + + // add serialized value + JsonSerializable bean = new JsonSerializable("a String", 42, true); + engineRuleNegative.getRuntimeService().setVariable(instance.getId(), "simpleBean", + objectValue(bean).serializationDataFormat(DataFormats.JSON_DATAFORMAT_NAME).create()); + + // then + thrown.expect(ProcessEngineException.class); + thrown.expectMessage("Cannot deserialize"); + thrown.expectCause(isA(SpinJsonException.class)); + + // when + engineRuleNegative.getRuntimeService().getVariable(instance.getId(), "simpleBean"); + } + + protected BpmnModelInstance getOneTaskModel() { + BpmnModelInstance oneTaskProcess = Bpmn.createExecutableProcess("oneTaskProcess") + .startEvent() + .userTask() + .endEvent() + .done(); + return oneTaskProcess; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationWithValidationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationWithValidationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..55200e624f7ebeb4c2fbd1d39b8349191d88536b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonSerializationWithValidationTest.java @@ -0,0 +1,33 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import org.camunda.bpm.engine.runtime.DeserializationTypeValidator; +import org.junit.Before; +import org.mockito.Mockito; + +public class JsonSerializationWithValidationTest extends JsonSerializationTest { + + @Before + public void setUpValidator() { + DeserializationTypeValidator validatorMock = Mockito.mock(DeserializationTypeValidator.class); + Mockito.when(validatorMock.validate(Mockito.anyString())).thenReturn(true); + engineRule.getProcessEngineConfiguration().setDeserializationTypeValidator(validatorMock); + engineRule.getProcessEngineConfiguration().setDeserializationTypeValidationEnabled(true); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonValueTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonValueTest.java new file mode 100644 index 0000000000000000000000000000000000000000..50cc9a292b1e748581edf10062c0281df62e1655 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/JsonValueTest.java @@ -0,0 +1,304 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.spin.DataFormats.json; +import static org.camunda.spin.plugin.variable.SpinValues.jsonValue; +import static org.camunda.spin.plugin.variable.type.SpinValueType.JSON; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.camunda.spin.DataFormats; +import org.camunda.spin.SpinRuntimeException; +import org.camunda.spin.json.SpinJsonNode; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.value.JsonValue; +import org.camunda.spin.plugin.variable.value.builder.JsonValueBuilder; +import org.json.JSONException; +import org.skyscreamer.jsonassert.JSONAssert; + +/** + * @author Roman Smirnov + * + */ +public class JsonValueTest extends PluggableProcessEngineTestCase { + + protected static final String ONE_TASK_PROCESS = "org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml"; + protected static final String JSON_FORMAT_NAME = DataFormats.JSON_DATAFORMAT_NAME; + + protected static final String ONE_TASK_PROCESS_KEY = "oneTaskProcess"; + + protected String jsonString = "{\"foo\": \"bar\"}"; + protected String brokenJsonString = "{\"foo: \"bar\"}"; + + protected String variableName = "x"; + + @Deployment(resources = ONE_TASK_PROCESS) + public void testGetUntypedJsonValue() throws JSONException { + // given + JsonValue jsonValue = jsonValue(jsonString).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // when + SpinJsonNode value = (SpinJsonNode) runtimeService.getVariable(processInstanceId, variableName); + + // then + JSONAssert.assertEquals(jsonString, value.toString(), true); + assertEquals(json().getName(), value.getDataFormatName()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testGetNullJsonValue() { + // given + JsonValue jsonValue = jsonValue((String) null).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // when + SpinJsonNode value = (SpinJsonNode) runtimeService.getVariable(processInstanceId, variableName); + + // then + assertThat(value).isNull(); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testGetTypedJsonValue() throws JSONException { + // given + JsonValue jsonValue = jsonValue(jsonString).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // when + JsonValue typedValue = runtimeService.getVariableTyped(processInstanceId, variableName); + + // then + SpinJsonNode value = typedValue.getValue(); + JSONAssert.assertEquals(jsonString, value.toString(), true); + + assertTrue(typedValue.isDeserialized()); + assertEquals(JSON, typedValue.getType()); + assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat()); + JSONAssert.assertEquals(jsonString, typedValue.getValueSerialized(), true); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testBrokenJsonSerialization() { + // given + JsonValue value = jsonValue(brokenJsonString).create(); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY).getId(); + + try { + // when + runtimeService.setVariable(processInstanceId, variableName, value); + } catch (Exception e) { + fail("no exception expected"); + } + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailingDeserialization() { + // given + JsonValue value = jsonValue(brokenJsonString).create(); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY).getId(); + runtimeService.setVariable(processInstanceId, variableName, value); + + try { + // when + runtimeService.getVariable(processInstanceId, variableName); + fail("exception expected"); + } catch (ProcessEngineException e) { + // happy path + } + + try { + runtimeService.getVariableTyped(processInstanceId, variableName); + fail("exception expected"); + } catch(ProcessEngineException e) { + // happy path + } + + // However, I can access the serialized value + JsonValue jsonValue = runtimeService.getVariableTyped(processInstanceId, variableName, false); + assertFalse(jsonValue.isDeserialized()); + assertEquals(brokenJsonString, jsonValue.getValueSerialized()); + + // but not the deserialized properties + try { + jsonValue.getValue(); + fail("exception expected"); + } catch(SpinRuntimeException e) { + } + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailForNonExistingSerializationFormat() { + // given + JsonValueBuilder builder = jsonValue(jsonString).serializationDataFormat("non existing data format"); + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY).getId(); + + try { + // when (1) + runtimeService.setVariable(processInstanceId, variableName, builder); + fail("Exception expected"); + } catch (ProcessEngineException e) { + // then (1) + assertTextPresent("Cannot find serializer for value", e.getMessage()); + // happy path + } + + try { + // when (2) + runtimeService.setVariable(processInstanceId, variableName, builder.create()); + fail("Exception expected"); + } catch (ProcessEngineException e) { + // then (2) + assertTextPresent("Cannot find serializer for value", e.getMessage()); + // happy path + } + } + + @Deployment(resources = "org/camunda/spin/plugin/jsonConditionProcess.bpmn20.xml") + public void testJsonValueInCondition() { + // given + String jsonString = "{\"age\": 22 }"; + JsonValue value = jsonValue(jsonString).create(); + VariableMap variables = Variables.createVariables().putValueTyped("customer", value); + + // when + runtimeService.startProcessInstanceByKey("process", variables); + + // then + Task task = taskService.createTaskQuery().singleResult(); + assertEquals("task1", task.getTaskDefinitionKey()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testTransientJsonValueFluent() { + // given + JsonValue jsonValue = jsonValue(jsonString).setTransient(true).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue); + + // when + runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testTransientJsonValue() { + // given + JsonValue jsonValue = jsonValue(jsonString, true).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue); + + // when + runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + } + + public void testApplyValueInfoFromSerializedValue() { + // given + Map valueInfo = new HashMap<>(); + valueInfo.put(ValueType.VALUE_INFO_TRANSIENT, true); + + // when + JsonValue jsonValue = (JsonValue) SpinValueType.JSON.createValueFromSerialized(jsonString, valueInfo); + + // then + assertEquals(true, jsonValue.isTransient()); + Map returnedValueInfo = SpinValueType.JSON.getValueInfo(jsonValue); + assertEquals(true, returnedValueInfo.get(ValueType.VALUE_INFO_TRANSIENT)); + } + + /** + * See https://app.camunda.com/jira/browse/CAM-9932 + */ + public void testTransientJsonSpinVariables() { + // given + BpmnModelInstance modelInstance = Bpmn.createExecutableProcess("aProcess") + .startEvent() + .serviceTask() + .camundaClass(JsonDelegate.class) + .userTask() + .endEvent() + .done(); + deployment(modelInstance); + + // when + String processInstanceId = runtimeService.startProcessInstanceByKey("aProcess").getId(); + + // then + Object value = runtimeService.getVariable(processInstanceId, "jsonVariable"); + assertThat(value).isNull(); + } + + public void testDeserializeTransientJsonValue() { + // given + BpmnModelInstance modelInstance = Bpmn.createExecutableProcess("foo") + .startEvent() + .exclusiveGateway("gtw") + .sequenceFlowId("flow1") + .condition("cond", "${S(" + variableName + ").prop(\"foo\").stringValue() == \"bar\"}") + .userTask("userTask1") + .endEvent() + .moveToLastGateway() + .sequenceFlowId("flow2") + .userTask("userTask2") + .endEvent() + .done(); + + deployment(modelInstance); + + JsonValue jsonValue = jsonValue(jsonString, true).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue); + + // when + runtimeService.startProcessInstanceByKey("foo", variables); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + + Task task = taskService.createTaskQuery().singleResult(); + assertNotNull(task); + assertEquals("userTask1", task.getTaskDefinitionKey()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/TypedValueAssert.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/TypedValueAssert.java new file mode 100644 index 0000000000000000000000000000000000000000..54a4c17bc2d8e871aa866db7af5f6524b383f890 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/TypedValueAssert.java @@ -0,0 +1,94 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.junit.Assert.*; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.nio.charset.Charset; + +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Daniel Meyer + * + */ +public class TypedValueAssert { + + public static void assertObjectValueDeserializedNull(ObjectValue typedValue) { + assertNotNull(typedValue); + assertTrue(typedValue.isDeserialized()); + assertNotNull(typedValue.getSerializationDataFormat()); + assertNull(typedValue.getValue()); + assertNull(typedValue.getValueSerialized()); + assertNull(typedValue.getObjectType()); + assertNull(typedValue.getObjectTypeName()); + } + + public static void assertObjectValueSerializedNull(ObjectValue typedValue) { + assertNotNull(typedValue); + assertFalse(typedValue.isDeserialized()); + assertNotNull(typedValue.getSerializationDataFormat()); + assertNull(typedValue.getValueSerialized()); + assertNull(typedValue.getObjectTypeName()); + } + + public static void assertObjectValueDeserialized(ObjectValue typedValue, Object value) { + Class expectedObjectType = value.getClass(); + assertTrue(typedValue.isDeserialized()); + + assertEquals(ValueType.OBJECT, typedValue.getType()); + + assertEquals(value, typedValue.getValue()); + assertEquals(value, typedValue.getValue(expectedObjectType)); + + assertEquals(expectedObjectType, typedValue.getObjectType()); + assertEquals(expectedObjectType.getName(), typedValue.getObjectTypeName()); + } + + public static void assertObjectValueSerializedJava(ObjectValue typedValue, Object value) { + assertEquals(Variables.SerializationDataFormats.JAVA.getName(), typedValue.getSerializationDataFormat()); + + try { + // validate this is the base 64 encoded string representation of the serialized value of the java object + String valueSerialized = typedValue.getValueSerialized(); + byte[] decodedObject = Base64.decodeBase64(valueSerialized.getBytes(Charset.forName("UTF-8"))); + ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(decodedObject)); + assertEquals(value, objectInputStream.readObject()); + } + catch(IOException e) { + throw new RuntimeException(e); + } + catch(ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + public static void assertUntypedNullValue(TypedValue nullValue) { + assertNotNull(nullValue); + assertNull(nullValue.getValue()); + assertEquals(ValueType.NULL, nullValue.getType()); + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/UpdateValueDelegate.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/UpdateValueDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..c9c3c8348d57481534a6033a5ab62e91d8ae7f81 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/UpdateValueDelegate.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Thorben Lindhauer + * + */ +public class UpdateValueDelegate implements JavaDelegate, Serializable { + + private static final long serialVersionUID = 1L; + + public static final String STRING_PROPERTY = "a string value"; + + public void execute(DelegateExecution execution) throws Exception { + TypedValue typedValue = execution.getVariableTyped("listVar"); + List var = (List) typedValue.getValue(); + JsonSerializable newElement = new JsonSerializable(); + newElement.setStringProperty(STRING_PROPERTY); + // implicit update of the list, so no execution.setVariable call + var.add(newElement); + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlDelegate.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlDelegate.java new file mode 100644 index 0000000000000000000000000000000000000000..fd47d322d7965773c3441ed6716e6036d68c1d12 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlDelegate.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import static org.camunda.spin.plugin.variable.SpinValues.xmlValue; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +/** + * @author Tassilo Weidner + */ +public class XmlDelegate implements JavaDelegate { + + public void execute(DelegateExecution execution) { + execution.setVariable("xmlVariable", Variables.untypedValue(xmlValue(""),true)); + + // when + TypedValue typedValue = execution.getVariableTyped("xmlVariable"); + + // then + assertThat(typedValue.isTransient(), is(true)); + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlListSerializable.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlListSerializable.java new file mode 100644 index 0000000000000000000000000000000000000000..667bcf1dea56c1502fd98d1ef118cea7ce222239 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlListSerializable.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import java.util.ArrayList; +import java.util.List; + +public class XmlListSerializable { + + private List listProperty; + + public XmlListSerializable() { + this.listProperty = new ArrayList(); + } + + public void addElement(T element) { + this.listProperty.add(element); + } + + public List getListProperty() { + return listProperty; + } + + public void setListProperty(List listProperty) { + this.listProperty = listProperty; + } + + public String toExpectedXmlString() { + StringBuilder jsonBuilder = new StringBuilder(); + + jsonBuilder.append(""); + for (int i = 0; i < listProperty.size(); i++) { + jsonBuilder.append("" + listProperty.get(i) + ""); + } + jsonBuilder.append(""); + + return jsonBuilder.toString(); + } + + public String toString() { + return toExpectedXmlString(); + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlSerializable.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlSerializable.java new file mode 100644 index 0000000000000000000000000000000000000000..447912bd75d62e9caed642cc5b36baa2267f0aa2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlSerializable.java @@ -0,0 +1,113 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class XmlSerializable { + + private String stringProperty; + + private int intProperty; + + private boolean booleanProperty; + + public XmlSerializable() { + + } + + public XmlSerializable(String stringProperty, int intProperty, boolean booleanProperty) { + this.stringProperty = stringProperty; + this.intProperty = intProperty; + this.booleanProperty = booleanProperty; + } + + public String getStringProperty() { + return stringProperty; + } + + public void setStringProperty(String stringProperty) { + this.stringProperty = stringProperty; + } + + public int getIntProperty() { + return intProperty; + } + + public void setIntProperty(int intProperty) { + this.intProperty = intProperty; + } + + public boolean getBooleanProperty() { + return booleanProperty; + } + + public void setBooleanProperty(boolean booleanProperty) { + this.booleanProperty = booleanProperty; + } + + public String toExpectedXmlString() { + StringBuilder jsonBuilder = new StringBuilder(); + + jsonBuilder.append(""); + jsonBuilder.append(booleanProperty); + jsonBuilder.append(""); + jsonBuilder.append(intProperty); + jsonBuilder.append(""); + jsonBuilder.append(stringProperty); + jsonBuilder.append(""); + + return jsonBuilder.toString(); + } + + public String toString() { + return toExpectedXmlString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (booleanProperty ? 1231 : 1237); + result = prime * result + intProperty; + result = prime * result + ((stringProperty == null) ? 0 : stringProperty.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + XmlSerializable other = (XmlSerializable) obj; + if (booleanProperty != other.booleanProperty) + return false; + if (intProperty != other.intProperty) + return false; + if (stringProperty == null) { + if (other.stringProperty != null) + return false; + } else if (!stringProperty.equals(other.stringProperty)) + return false; + return true; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlSerializationTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlSerializationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6967fd8f2e47b584d1483b010c0b21e599057ca4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlSerializationTest.java @@ -0,0 +1,504 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.variable.Variables.objectValue; +import static org.camunda.bpm.engine.variable.Variables.serializedObjectValue; +import static org.camunda.spin.plugin.variables.TypedValueAssert.assertObjectValueDeserializedNull; +import static org.camunda.spin.plugin.variables.TypedValueAssert.assertObjectValueSerializedNull; +import static org.camunda.spin.plugin.variables.TypedValueAssert.assertUntypedNullValue; + +import java.io.Reader; +import java.util.List; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.interceptor.Command; +import org.camunda.bpm.engine.impl.interceptor.CommandContext; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.camunda.bpm.engine.variable.value.builder.SerializedObjectValueBuilder; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.camunda.spin.DataFormats; +import org.camunda.spin.Spin; +import org.camunda.spin.impl.util.SpinIoUtil; +import org.camunda.spin.xml.SpinXmlElement; + +public class XmlSerializationTest extends PluggableProcessEngineTestCase { + + protected static final String ONE_TASK_PROCESS = "org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml"; + + protected static final String XML_FORMAT_NAME = DataFormats.XML_DATAFORMAT_NAME; + + protected String originalSerializationFormat; + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSerializationAsXml() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + XmlSerializable bean = new XmlSerializable("a String", 42, true); + // request object to be serialized as XML + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(XML_FORMAT_NAME).create()); + + // validate untyped value + Object value = runtimeService.getVariable(instance.getId(), "simpleBean"); + assertEquals(bean, value); + + // validate typed value + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertEquals(ValueType.OBJECT, typedValue.getType()); + + assertTrue(typedValue.isDeserialized()); + + assertEquals(bean, typedValue.getValue()); + assertEquals(bean, typedValue.getValue(XmlSerializable.class)); + assertEquals(XmlSerializable.class, typedValue.getObjectType()); + + assertEquals(XML_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertEquals(XmlSerializable.class.getName(), typedValue.getObjectTypeName()); + SpinXmlElement serializedValue = Spin.XML(typedValue.getValueSerialized()); + assertEquals(bean.getStringProperty(), serializedValue.childElement("stringProperty").textContent()); + assertEquals(bean.getBooleanProperty(), Boolean.parseBoolean(serializedValue.childElement("booleanProperty").textContent())); + assertEquals(bean.getIntProperty(), Integer.parseInt(serializedValue.childElement("intProperty").textContent())); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailingSerialization() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + FailingXmlSerializable failingBean = new FailingXmlSerializable("a String", 42, true); + + try { + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(failingBean).serializationDataFormat(XML_FORMAT_NAME)); + fail("exception expected"); + } catch (ProcessEngineException e) { + // happy path + assertTextPresent("I am failing", e.getMessage()); + } + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailingDeserialization() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + FailingXmlDeserializationBean failingBean = new FailingXmlDeserializationBean("a String", 42, true); + + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(failingBean).serializationDataFormat(XML_FORMAT_NAME)); + + try { + runtimeService.getVariable(instance.getId(), "simpleBean"); + fail("exception expected"); + } + catch(ProcessEngineException e) { + assertTextPresent("Cannot deserialize object in variable 'simpleBean'", e.getMessage()); + } + + try { + runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + fail("exception expected"); + } + catch(ProcessEngineException e) { + // happy path + } + + // However, I can access the serialized value + ObjectValue objectValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean", false); + assertFalse(objectValue.isDeserialized()); + assertNotNull(objectValue.getObjectTypeName()); + assertNotNull(objectValue.getValueSerialized()); + // but not the deserialized properties + try { + objectValue.getValue(); + fail("exception expected"); + } + catch(IllegalStateException e) { + assertTextPresent("Object is not deserialized", e.getMessage()); + } + + try { + objectValue.getValue(XmlSerializable.class); + fail("exception expected"); + } + catch(IllegalStateException e) { + assertTextPresent("Object is not deserialized", e.getMessage()); + } + + try { + objectValue.getObjectType(); + fail("exception expected"); + } + catch(IllegalStateException e) { + assertTextPresent("Object is not deserialized", e.getMessage()); + } + + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailForNonExistingSerializationFormat() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + XmlSerializable XmlSerializable = new XmlSerializable(); + + try { + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(XmlSerializable).serializationDataFormat("non existing data format")); + fail("Exception expected"); + } catch (ProcessEngineException e) { + assertTextPresent("Cannot find serializer for value", e.getMessage()); + // happy path + } + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testVariableValueCaching() { + final ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + processEngineConfiguration.getCommandExecutorTxRequired().execute(new Command() { + + @Override + public Void execute(CommandContext commandContext) { + XmlSerializable bean = new XmlSerializable("a String", 42, true); + runtimeService.setVariable(instance.getId(), "simpleBean", bean); + + Object returnedBean = runtimeService.getVariable(instance.getId(), "simpleBean"); + assertSame(bean, returnedBean); + + return null; + } + }); + + VariableInstance variableInstance = runtimeService.createVariableInstanceQuery().singleResult(); + + Object returnedBean = variableInstance.getValue(); + Object theSameReturnedBean = variableInstance.getValue(); + assertSame(returnedBean, theSameReturnedBean); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testGetSerializedVariableValue() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + XmlSerializable bean = new XmlSerializable("a String", 42, true); + runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(XML_FORMAT_NAME).create()); + + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean", false); + + SpinXmlElement serializedValue = Spin.XML(typedValue.getValueSerialized()); + assertEquals(bean.getStringProperty(), serializedValue.childElement("stringProperty").textContent()); + assertEquals(bean.getBooleanProperty(), Boolean.parseBoolean(serializedValue.childElement("booleanProperty").textContent())); + assertEquals(bean.getIntProperty(), Integer.parseInt(serializedValue.childElement("intProperty").textContent())); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValue() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + XmlSerializable bean = new XmlSerializable("a String", 42, true); + String beanAsXml = bean.toExpectedXmlString(); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue(beanAsXml) + .serializationDataFormat(XML_FORMAT_NAME) + .objectTypeName(bean.getClass().getCanonicalName()); + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + // java object can be retrieved + XmlSerializable returnedBean = (XmlSerializable) runtimeService.getVariable(instance.getId(), "simpleBean"); + assertEquals(bean, returnedBean); + + // validate typed value metadata + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertEquals(bean, typedValue.getValue()); + assertEquals(XML_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertEquals(bean.getClass().getCanonicalName(), typedValue.getObjectTypeName()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueNoTypeName() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + XmlSerializable bean = new XmlSerializable("a String", 42, true); + String beanAsXml = bean.toExpectedXmlString(); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue(beanAsXml) + .serializationDataFormat(XML_FORMAT_NAME); + // no type name + + try { + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + fail("Exception expected."); + } + catch(Exception e) { + assertTextPresent("no 'objectTypeName' provided for non-null value", e.getMessage()); + } + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueMismatchingTypeName() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + XmlSerializable bean = new XmlSerializable("a String", 42, true); + String beanAsXml = bean.toExpectedXmlString(); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue(beanAsXml) + .serializationDataFormat(XML_FORMAT_NAME) + .objectTypeName("Insensible type name."); // < not a valid type name + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + try { + runtimeService.getVariable(instance.getId(), "simpleBean"); + fail("Exception expected."); + } + catch(ProcessEngineException e) { + // happy path + } + } + + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueNull() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue() + .serializationDataFormat(XML_FORMAT_NAME) + .objectTypeName(XmlSerializable.class.getCanonicalName()); + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + // null can be retrieved + XmlSerializable returnedBean = (XmlSerializable) runtimeService.getVariable(instance.getId(), "simpleBean"); + assertNull(returnedBean); + + // validate typed value metadata + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertNull(typedValue.getValue()); + assertNull(typedValue.getValueSerialized()); + assertEquals(XML_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertEquals(XmlSerializable.class.getCanonicalName(), typedValue.getObjectTypeName()); + + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetSerializedVariableValueNullNoTypeName() { + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + SerializedObjectValueBuilder serializedValue = serializedObjectValue() + .serializationDataFormat(XML_FORMAT_NAME); + // no objectTypeName specified + + runtimeService.setVariable(instance.getId(), "simpleBean", serializedValue); + + // null can be retrieved + XmlSerializable returnedBean = (XmlSerializable) runtimeService.getVariable(instance.getId(), "simpleBean"); + assertNull(returnedBean); + + // validate typed value metadata + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean"); + assertNull(typedValue.getValue()); + assertNull(typedValue.getValueSerialized()); + assertEquals(XML_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertNull(typedValue.getObjectTypeName()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetJavaOjectNullDeserialized() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // set null value as "deserialized" object + runtimeService.setVariable(instance.getId(), "nullObject", + objectValue(null) + .serializationDataFormat(XML_FORMAT_NAME) + .create()); + + // get null value via untyped api + assertNull(runtimeService.getVariable(instance.getId(), "nullObject")); + + // get null via typed api + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject"); + assertObjectValueDeserializedNull(typedValue); + + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetJavaOjectNullSerialized() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // set null value as "serialized" object + runtimeService.setVariable(instance.getId(), "nullObject", + serializedObjectValue() + .serializationDataFormat(XML_FORMAT_NAME) + .create()); // Note: no object type name provided + + // get null value via untyped api + assertNull(runtimeService.getVariable(instance.getId(), "nullObject")); + + // get null via typed api + ObjectValue deserializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject"); + assertObjectValueDeserializedNull(deserializedTypedValue); + + ObjectValue serializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject", false); + assertObjectValueSerializedNull(serializedTypedValue); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetJavaOjectNullSerializedObjectTypeName() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + String typeName = "some.type.Name"; + + // set null value as "serialized" object + runtimeService.setVariable(instance.getId(), "nullObject", + serializedObjectValue() + .serializationDataFormat(XML_FORMAT_NAME) + .objectTypeName(typeName) // This time an objectTypeName is provided + .create()); + + // get null value via untyped api + assertNull(runtimeService.getVariable(instance.getId(), "nullObject")); + + // get null via typed api + ObjectValue deserializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject"); + assertNotNull(deserializedTypedValue); + assertTrue(deserializedTypedValue.isDeserialized()); + assertEquals(XML_FORMAT_NAME, deserializedTypedValue.getSerializationDataFormat()); + assertNull(deserializedTypedValue.getValue()); + assertNull(deserializedTypedValue.getValueSerialized()); + assertNull(deserializedTypedValue.getObjectType()); + assertEquals(typeName, deserializedTypedValue.getObjectTypeName()); + + ObjectValue serializedTypedValue = runtimeService.getVariableTyped(instance.getId(), "nullObject", false); + assertNotNull(serializedTypedValue); + assertFalse(serializedTypedValue.isDeserialized()); + assertEquals(XML_FORMAT_NAME, serializedTypedValue.getSerializationDataFormat()); + assertNull(serializedTypedValue.getValueSerialized()); + assertEquals(typeName, serializedTypedValue.getObjectTypeName()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetUntypedNullForExistingVariable() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // initially the variable has a value + XmlSerializable object = new XmlSerializable(); + + runtimeService.setVariable(instance.getId(), "varName", + objectValue(object) + .serializationDataFormat(XML_FORMAT_NAME) + .create()); + + // get value via untyped api + assertEquals(object, runtimeService.getVariable(instance.getId(), "varName")); + + // set the variable to null via untyped Api + runtimeService.setVariable(instance.getId(), "varName", null); + + // variable is now untyped null + TypedValue nullValue = runtimeService.getVariableTyped(instance.getId(), "varName"); + assertUntypedNullValue(nullValue); + + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testSetTypedNullForExistingVariable() throws Exception { + + ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); + + // initially the variable has a value + XmlSerializable javaSerializable = new XmlSerializable(); + + runtimeService.setVariable(instance.getId(), "varName", + objectValue(javaSerializable) + .serializationDataFormat(XML_FORMAT_NAME) + .create()); + + // get value via untyped api + assertEquals(javaSerializable, runtimeService.getVariable(instance.getId(), "varName")); + + // set the variable to null via typed Api + runtimeService.setVariable(instance.getId(), "varName", objectValue(null)); + + // variable is still of type object + ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "varName"); + assertObjectValueDeserializedNull(typedValue); + } + + public void testTransientXmlValue() { + // given + BpmnModelInstance modelInstance = Bpmn.createExecutableProcess("foo") + .startEvent() + .exclusiveGateway("gtw") + .sequenceFlowId("flow1") + .condition("cond", "${x.stringProperty == \"bar\"}") + .userTask("userTask1") + .endEvent() + .moveToLastGateway() + .sequenceFlowId("flow2") + .userTask("userTask2") + .endEvent() + .done(); + + deployment(modelInstance); + + XmlSerializable bean = new XmlSerializable("bar", 42, true); + ObjectValue xmlValue = serializedObjectValue(bean.toExpectedXmlString(), true) + .serializationDataFormat(XML_FORMAT_NAME) + .objectTypeName(XmlSerializable.class.getName()) + .create(); + VariableMap variables = Variables.createVariables().putValueTyped("x", xmlValue); + + // when + runtimeService.startProcessInstanceByKey("foo", variables); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + + Task task = taskService.createTaskQuery().singleResult(); + assertNotNull(task); + assertEquals("userTask1", task.getTaskDefinitionKey()); + } + + public void testOverloadedAppendMethod() { + // given + deployment(Bpmn.createExecutableProcess("spin-xml-issue") + .startEvent() + .serviceTask() + .camundaExpression("${XML(\"\").append(xmlInput.xPath(\"//cosigner/*\").elementList()).toString()}") + .camundaResultVariable("output") + .userTask() + .endEvent() + .done()); + + Reader xmlInput = SpinIoUtil.classpathResourceAsReader("org/camunda/spin/plugin/XmlSerializationTest-input.xml"); + String expectedOutput = SpinIoUtil.fileAsString("org/camunda/spin/plugin/XmlSerializationTest-output.xml"); + VariableMap variables = Variables.putValue("xmlInput", Spin.XML(xmlInput)); + // when + runtimeService.startProcessInstanceByKey("spin-xml-issue", variables); + // then + VariableInstance output = runtimeService.createVariableInstanceQuery().variableName("output").singleResult(); + assertThat((String) output.getValue()).isEqualToIgnoringWhitespace(expectedOutput); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlValueTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlValueTest.java new file mode 100644 index 0000000000000000000000000000000000000000..98b0d843879cd9c9ff830a9d2cdd40217659e174 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/java/org/camunda/spin/plugin/variables/XmlValueTest.java @@ -0,0 +1,290 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.spin.plugin.variables; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.spin.DataFormats.xml; +import static org.camunda.spin.plugin.variable.SpinValues.xmlValue; +import static org.camunda.spin.plugin.variable.type.SpinValueType.XML; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.test.PluggableProcessEngineTestCase; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.test.Deployment; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.camunda.bpm.model.bpmn.BpmnModelInstance; +import org.camunda.spin.DataFormats; +import org.camunda.spin.SpinRuntimeException; +import org.camunda.spin.plugin.variable.type.SpinValueType; +import org.camunda.spin.plugin.variable.value.XmlValue; +import org.camunda.spin.plugin.variable.value.builder.XmlValueBuilder; +import org.camunda.spin.xml.SpinXmlElement; + +/** + * @author Roman Smirnov + * + */ +public class XmlValueTest extends PluggableProcessEngineTestCase { + + protected static final String ONE_TASK_PROCESS = "org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml"; + protected static final String XML_FORMAT_NAME = DataFormats.XML_DATAFORMAT_NAME; + + protected static final String ONE_TASK_PROCESS_KEY = "oneTaskProcess"; + + protected String xmlString = ""; + protected String brokenXmlString = ""; + + protected String variableName = "x"; + + @Deployment(resources = ONE_TASK_PROCESS) + public void testGetUntypedXmlValue() { + // given + XmlValue xmlValue = xmlValue(xmlString).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, xmlValue); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // when + SpinXmlElement value = (SpinXmlElement) runtimeService.getVariable(processInstanceId, variableName); + + // then + assertTrue(value.hasAttr("attrName")); + assertEquals("attrValue", value.attr("attrName").value()); + assertTrue(value.childElements().isEmpty()); + assertEquals(xml().getName(), value.getDataFormatName()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testGetTypedXmlValue() { + // given + XmlValue xmlValue = xmlValue(xmlString).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, xmlValue); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // when + XmlValue typedValue = runtimeService.getVariableTyped(processInstanceId, variableName); + + // then + SpinXmlElement value = typedValue.getValue(); + assertTrue(value.hasAttr("attrName")); + assertEquals("attrValue", value.attr("attrName").value()); + assertTrue(value.childElements().isEmpty()); + + assertTrue(typedValue.isDeserialized()); + assertEquals(XML, typedValue.getType()); + assertEquals(XML_FORMAT_NAME, typedValue.getSerializationDataFormat()); + assertEquals(xmlString, typedValue.getValueSerialized()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testBrokenXmlSerialization() { + // given + XmlValue value = xmlValue(brokenXmlString).create(); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY).getId(); + + try { + // when + runtimeService.setVariable(processInstanceId, variableName, value); + } catch (Exception e) { + fail("no exception expected"); + } + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailingDeserialization() { + // given + XmlValue value = xmlValue(brokenXmlString).create(); + + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY).getId(); + runtimeService.setVariable(processInstanceId, variableName, value); + + try { + // when + runtimeService.getVariable(processInstanceId, variableName); + fail("exception expected"); + } catch (ProcessEngineException e) { + // happy path + } + + try { + runtimeService.getVariableTyped(processInstanceId, variableName); + fail("exception expected"); + } catch(ProcessEngineException e) { + // happy path + } + + // However, I can access the serialized value + XmlValue xmlValue = runtimeService.getVariableTyped(processInstanceId, variableName, false); + assertFalse(xmlValue.isDeserialized()); + assertEquals(brokenXmlString, xmlValue.getValueSerialized()); + + // but not the deserialized properties + try { + xmlValue.getValue(); + fail("exception expected"); + } catch(SpinRuntimeException e) { + } + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testFailForNonExistingSerializationFormat() { + // given + XmlValueBuilder builder = xmlValue(xmlString).serializationDataFormat("non existing data format"); + String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY).getId(); + + try { + // when (1) + runtimeService.setVariable(processInstanceId, variableName, builder); + fail("Exception expected"); + } catch (ProcessEngineException e) { + // then (1) + assertTextPresent("Cannot find serializer for value", e.getMessage()); + // happy path + } + + try { + // when (2) + runtimeService.setVariable(processInstanceId, variableName, builder.create()); + fail("Exception expected"); + } catch (ProcessEngineException e) { + // then (2) + assertTextPresent("Cannot find serializer for value", e.getMessage()); + // happy path + } + } + + @Deployment(resources = "org/camunda/spin/plugin/xmlConditionProcess.bpmn20.xml") + public void testXmlValueInCondition() { + // given + String xmlString = ""; + XmlValue value = xmlValue(xmlString).create(); + VariableMap variables = Variables.createVariables().putValueTyped("customer", value); + + // when + runtimeService.startProcessInstanceByKey("process", variables); + + // then + Task task = taskService.createTaskQuery().singleResult(); + assertEquals("task1", task.getTaskDefinitionKey()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testTransientXmlValueFluent() { + // given + XmlValue xmlValue = xmlValue(xmlString).setTransient(true).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, xmlValue); + + // when + runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + } + + @Deployment(resources = ONE_TASK_PROCESS) + public void testTransientXmlValue() { + // given + XmlValue xmlValue = xmlValue(xmlString, true).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, xmlValue); + + // when + runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId(); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + } + + /** + * See https://app.camunda.com/jira/browse/CAM-9932 + */ + public void testTransientXmlSpinVariables() { + // given + BpmnModelInstance modelInstance = Bpmn.createExecutableProcess("aProcess") + .startEvent() + .serviceTask() + .camundaClass(XmlDelegate.class) + .userTask() + .endEvent() + .done(); + deployment(modelInstance); + + // when + String processInstanceId = runtimeService.startProcessInstanceByKey("aProcess").getId(); + + // then + Object value = runtimeService.getVariable(processInstanceId, "xmlVariable"); + assertThat(value).isNull(); + } + + public void testApplyValueInfoFromSerializedValue() { + // given + Map valueInfo = new HashMap(); + valueInfo.put(ValueType.VALUE_INFO_TRANSIENT, true); + + // when + XmlValue xmlValue = (XmlValue) SpinValueType.XML.createValueFromSerialized(xmlString, valueInfo); + + // then + assertEquals(true, xmlValue.isTransient()); + Map returnedValueInfo = SpinValueType.XML.getValueInfo(xmlValue); + assertEquals(true, returnedValueInfo.get(ValueType.VALUE_INFO_TRANSIENT)); + } + + public void testDeserializeTransientXmlValue() { + // given + BpmnModelInstance modelInstance = Bpmn.createExecutableProcess("foo") + .startEvent() + .exclusiveGateway("gtw") + .sequenceFlowId("flow1") + .condition("cond", "${XML(" + variableName + ").attr('attrName').value() == 'attrValue'}") + .userTask("userTask1") + .endEvent() + .moveToLastGateway() + .sequenceFlowId("flow2") + .userTask("userTask2") + .endEvent() + .done(); + + deployment(modelInstance); + + XmlValue xmlValue = xmlValue(xmlString, true).create(); + VariableMap variables = Variables.createVariables().putValueTyped(variableName, xmlValue); + + // when + runtimeService.startProcessInstanceByKey("foo", variables); + + // then + List variableInstances = runtimeService.createVariableInstanceQuery().list(); + assertEquals(0, variableInstances.size()); + + Task task = taskService.createTaskQuery().singleResult(); + assertNotNull(task); + assertEquals("userTask1", task.getTaskDefinitionKey()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/camunda.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/camunda.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..e781b65fa5552e5f2e7228487a8582d6a98e66a1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/camunda.cfg.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/custom.camunda.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/custom.camunda.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..071458e5a918e6a2f2c0592730ae539e28a1c8fe --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/custom.camunda.cfg.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/logback-test.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/logback-test.xml new file mode 100644 index 0000000000000000000000000000000000000000..402fac89b2e36e22722e1c8bd7dd1ad09c4af65f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/logback-test.xml @@ -0,0 +1,27 @@ + + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/logging.properties b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/logging.properties new file mode 100644 index 0000000000000000000000000000000000000000..4941c55971f365781be2c0903a6f00af84a1a74f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/logging.properties @@ -0,0 +1,2 @@ +#register SLF4JBridgeHandler as handler for the j.u.l. root logger +handlers = org.slf4j.bridge.SLF4JBridgeHandler diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DecisionSingleOutput.dmn11.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DecisionSingleOutput.dmn11.xml new file mode 100644 index 0000000000000000000000000000000000000000..ae3a51f4b20f8deceb516d5bd375d01da175ea8e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DecisionSingleOutput.dmn11.xml @@ -0,0 +1,26 @@ + + + + + + + input1.listProperty + + + + + + + + + + input1.listProperty + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.dmn11.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.dmn11.xml new file mode 100644 index 0000000000000000000000000000000000000000..b8903016cf2b28136ac0ba8f0cfeea8cc40501ec --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.dmn11.xml @@ -0,0 +1,100 @@ + + + + + + + + input + + + + + + + "empty output" + + + + + + + "empty map" + + + + + + + "empty map" + + + + + + + "single entry" + + + "foo" + + + + + + "multiple entries" + + + "foo" + + + "bar" + + + + + "single entry list" + + + "foo" + + + + + + "single entry list" + + + "foo" + + + + + + "multiple entries list" + + + "foo" + + + "bar" + + + + + "multiple entries list" + + + "foo" + + + "bar" + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testCustomOutputMapping.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testCustomOutputMapping.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..b2527510b79c3ea7cb51b76baf7fcc138e077af6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testCustomOutputMapping.bpmn20.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + ${decisionResult.getSingleResult().result1} + ${decisionResult.getSingleResult().result2} + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testDefaultMapping.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testDefaultMapping.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..93437381a0c8ae5ad04045acc01b5eb47a36d7fb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testDefaultMapping.bpmn20.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testSingleEntry.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testSingleEntry.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..ab0ee1eacc7250963f7a5702733ca65f3d391d81 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testSingleEntry.bpmn20.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testStoreDecisionResult.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testStoreDecisionResult.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..57223cc456c78034aa0ec14cb1087bff517b1708 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/DmnBusinessRuleTaskResultMappingTest.testStoreDecisionResult.bpmn20.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + ${decisionResult} + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/XmlSerializationTest-input.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/XmlSerializationTest-input.xml new file mode 100644 index 0000000000000000000000000000000000000000..8eec1773ab1954a95ab1f11630193a006781aaa8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/XmlSerializationTest-input.xml @@ -0,0 +1,16 @@ + + + + John + Doe + 7605794440 + 122 Main St + Secondary St + San Diego + CA + 12345 + MBR000123 + true + aa@test.com + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/XmlSerializationTest-output.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/XmlSerializationTest-output.xml new file mode 100644 index 0000000000000000000000000000000000000000..634a57319c59af2e6c68c84e1bac5dcc4a3ddc6f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/XmlSerializationTest-output.xml @@ -0,0 +1,14 @@ + + + John + Doe + 7605794440 + 122 Main St + Secondary St + San Diego + CA + 12345 + MBR000123 + true + aa@test.com + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/json.camunda.cfg.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/json.camunda.cfg.xml new file mode 100644 index 0000000000000000000000000000000000000000..d83df54235af9d709e92cdff09075bf341191fbc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/json.camunda.cfg.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/jsonConditionProcess.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/jsonConditionProcess.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..49af4d52a492e1fe381fb5013cca3bcccf021bfc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/jsonConditionProcess.bpmn20.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + = 21 } + ]]> + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..c8c9c5d2a21769aae7fc4b7b6d624061051db08b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/oneTaskProcess.bpmn20.xml @@ -0,0 +1,18 @@ + + + + + This is a process for testing purposes + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/serviceTaskProcess.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/serviceTaskProcess.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..8517da8e90b36b9674cdc9de5f58bf7e6cfb7a3d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/serviceTaskProcess.bpmn20.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/xmlConditionProcess.bpmn20.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/xmlConditionProcess.bpmn20.xml new file mode 100644 index 0000000000000000000000000000000000000000..63be6cfe595ca151f7e6deb11809a31dad31f9fc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-plugins/spin-plugin/src/test/resources/org/camunda/spin/plugin/xmlConditionProcess.bpmn20.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + = 21 } + ]]> + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-classes.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-classes.xml new file mode 100644 index 0000000000000000000000000000000000000000..753a8fcae55fa35370f0c474657e52db2cd17f79 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-classes.xml @@ -0,0 +1,13 @@ + + + + classes + + + jar + + + false + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-sources.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-sources.xml new file mode 100644 index 0000000000000000000000000000000000000000..14cd09cba025e2959b909cd3fd09544926429947 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-sources.xml @@ -0,0 +1,23 @@ + + + + sources + + + jar + + + false + + + + / + true + provided + + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar:sources:* + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-tests.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-tests.xml new file mode 100644 index 0000000000000000000000000000000000000000..e43f67b9f2e1ce548417a9a0d51d587903b6b491 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-tests.xml @@ -0,0 +1,23 @@ + + + + tests + + + jar + + + false + + + + / + true + provided + + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar:tests:* + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-war-tomcat.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-war-tomcat.xml new file mode 100644 index 0000000000000000000000000000000000000000..f869ccbf53101410577dbe4712d247e6beeb6f43 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-war-tomcat.xml @@ -0,0 +1,72 @@ + + + + tomcat + + + war + + + false + + + + + + WEB-INF/lib + true + true + + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar + + + + + + WEB-INF/lib + true + true + provided + + + + jakarta.servlet:jakarta.servlet-api:jar + jakarta.activation:jakarta.activation-api:jar + jakarta.ws.rs:jakarta.ws.rs-api:jar + jakarta.xml.bind:jakarta.xml.bind-api:jar + + + org.jboss.resteasy:resteasy-core + + + + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar:tests + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar:sources + + + + + + / + + org.camunda.bpm:camunda-engine-rest-jakarta:war:* + + true + + + **/web.xml + + + + + + + + + src/main/runtime/tomcat/webapp + / + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-war-wildfly.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-war-wildfly.xml new file mode 100644 index 0000000000000000000000000000000000000000..eedb26cda4c925faa895e9dff594f57f745e6044 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/assembly-war-wildfly.xml @@ -0,0 +1,50 @@ + + + + wildfly + + + war + + + false + + + + src/main/runtime/wildfly/webapp + / + + + + + + WEB-INF/lib + true + true + provided + + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar + + + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar:tests + org.camunda.bpm:camunda-engine-rest-core-jakarta:jar:sources + + + + + / + + org.camunda.bpm:camunda-engine-rest-jakarta:war:* + + true + + + **/jboss-deployment-structure.xml + **/web.xml + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..840713d3c27b274bec6878a210c6c8e29508a27e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/pom.xml @@ -0,0 +1,201 @@ + + + 4.0.0 + camunda-engine-rest-jakarta + Camunda Platform - engine - REST - Assembly Jakarta + war + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + org.camunda.bpm + camunda-engine-rest-root + 7.24.0-SNAPSHOT + + + + + false + compile|provided + + 6.2.3.Final + + + + + + jakarta.platform + jakarta.jakartaee-bom + ${version.jakarta-ee-spec} + import + pom + + + + org.jboss.resteasy + resteasy-bom + ${version.resteasy} + import + pom + + + + + + + + org.camunda.bpm + camunda-engine-rest-core-jakarta + ${project.version} + + + + + org.camunda.bpm + camunda-engine-rest-core-jakarta + ${project.version} + sources + provided + + + + org.camunda.bpm + camunda-engine-rest-core-jakarta + ${project.version} + tests + provided + + + + + + jakarta.ws.rs + jakarta.ws.rs-api + provided + + + + jakarta.servlet + jakarta.servlet-api + provided + + + + + + org.jboss.resteasy + resteasy-core + provided + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + wildfly + package + + single + + + + + + org.camunda.bpm.camunda-engine,org.camunda.bpm.dmn.camunda-engine-dmn,org.camunda.commons.camunda-commons-logging,org.camunda.spin.camunda-spin-core,org.camunda.bpm.juel.camunda-juel services,org.graalvm.js.js-scriptengine services + + + + assembly-war-wildfly.xml + + camunda-engine-rest-jakarta-${project.version} + true + wildfly + target/ + target/assembly/work + + + + + tomcat + package + + single + + + + assembly-war-tomcat.xml + + camunda-engine-rest-jakarta-${project.version} + true + tomcat + target/ + target/assembly/work + + + + + classes + package + + single + + + + assembly-classes.xml + + camunda-engine-rest-jakarta-${project.version} + true + target/ + target/assembly/work + + + + + sources + package + + single + + + + assembly-sources.xml + + camunda-engine-rest-jakarta-${project.version} + true + target/ + target/assembly/work + + + + + tests + package + + single + + + + assembly-tests.xml + + camunda-engine-rest-jakarta-${project.version} + true + target/ + target/assembly/work + + + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/java/org/camunda/bpm/engine/rest/impl/application/DefaultApplication.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/java/org/camunda/bpm/engine/rest/impl/application/DefaultApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..02f27a49687220d199c4837060ae610a98ae4642 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/java/org/camunda/bpm/engine/rest/impl/application/DefaultApplication.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.application; + +import jakarta.ws.rs.ApplicationPath; +import jakarta.ws.rs.core.Application; +import org.camunda.bpm.engine.rest.impl.CamundaRestResources; + +import java.util.HashSet; +import java.util.Set; + +/** + *

Default {@link Application} registering all resources.

+ * + *

NOTE This class is excluded from the classes-jar, + * such that users that want to embed the REST API as a JAR file into a + * custom JAX-RS application are able to build a deployment based on their + * requirements.

+ * + * @author Daniel Meyer + * + */ +@ApplicationPath("/") +public class DefaultApplication extends Application { + + @Override + public Set> getClasses() { + Set> classes = new HashSet>(); + + classes.addAll(CamundaRestResources.getResourceClasses()); + classes.addAll(CamundaRestResources.getConfigurationClasses()); + + return classes; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/tomcat/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/tomcat/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..c2007f793e5193b9954ac4b2598f7fd913936472 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/tomcat/webapp/WEB-INF/web.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + true + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + true + + + CacheControlFilter + /* + + + + + + + Resteasy + org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher + + jakarta.ws.rs.Application + org.camunda.bpm.engine.rest.impl.application.DefaultApplication + + true + + + + Resteasy + /* + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/wildfly/webapp/WEB-INF/jboss-deployment-structure.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/wildfly/webapp/WEB-INF/jboss-deployment-structure.xml new file mode 100644 index 0000000000000000000000000000000000000000..0bfd3c720b3f4f6883f2999a3e7059d548a517ec --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/wildfly/webapp/WEB-INF/jboss-deployment-structure.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/wildfly/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/wildfly/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..98aec2f8c1e6a26f2860eb6ec0cd7e3cf0766aa8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/runtime/wildfly/webapp/WEB-INF/web.xml @@ -0,0 +1,71 @@ + + + + Camunda Platform rest api + + + + + + + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + true + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + true + + + CacheControlFilter + /* + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.PermissionProvider b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.PermissionProvider new file mode 100644 index 0000000000000000000000000000000000000000..c45c3cc926ebbb1348f1974e44363cef25c7e923 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.PermissionProvider @@ -0,0 +1 @@ +org.camunda.bpm.engine.rest.spi.impl.DefaultPermissionProvider \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider new file mode 100644 index 0000000000000000000000000000000000000000..c52f72c1266582bf7316c8584a1290b3d7d5ac13 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider @@ -0,0 +1 @@ +org.camunda.bpm.engine.rest.impl.application.ContainerManagedProcessEngineProvider \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/jboss-deployment-structure.xml new file mode 100644 index 0000000000000000000000000000000000000000..8742e0c2602e40a2be4e15cde4424e2f5a35a78a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/jboss-web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000000000000000000000000000000000000..ddfd71eec232440c62113b6b0f22f920b771e62a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,6 @@ + + + + other + /engine-rest + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..6c7ccf6b85ec42092469d22772689435fe6ade9b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly-jakarta/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,49 @@ + + + + Camunda Platform rest api + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + + + CacheControlFilter + /* + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-classes.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-classes.xml new file mode 100644 index 0000000000000000000000000000000000000000..753a8fcae55fa35370f0c474657e52db2cd17f79 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-classes.xml @@ -0,0 +1,13 @@ + + + + classes + + + jar + + + false + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-sources.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-sources.xml new file mode 100644 index 0000000000000000000000000000000000000000..377d153f8e15da13a08f600acbf7895399040ac0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-sources.xml @@ -0,0 +1,23 @@ + + + + sources + + + jar + + + false + + + + / + true + provided + + org.camunda.bpm:camunda-engine-rest-core:jar:sources:* + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-tests.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-tests.xml new file mode 100644 index 0000000000000000000000000000000000000000..3e394e9f335d649bc689f6de8755da8b6a27c149 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-tests.xml @@ -0,0 +1,23 @@ + + + + tests + + + jar + + + false + + + + / + true + provided + + org.camunda.bpm:camunda-engine-rest-core:jar:tests:* + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-tomcat.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-tomcat.xml new file mode 100644 index 0000000000000000000000000000000000000000..b8bc00b3af5abdcf2db071752d7484e9114ba4d6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-tomcat.xml @@ -0,0 +1,52 @@ + + + + tomcat + + + war + + + false + + + + WEB-INF/lib + true + true + provided + + org.camunda.bpm:camunda-engine-rest-core:jar + org.jboss.resteasy:resteasy-jaxrs:jar:* + org.jboss.resteasy:async-http-servlet-3.0:jar:* + org.jboss.spec.javax.ws.rs:jboss-jaxrs-api_2.1_spec:jar:* + + + org.camunda.bpm:camunda-engine-rest-core:jar:tests + org.camunda.bpm:camunda-engine-rest-core:jar:sources + + + + + / + + org.camunda.bpm:camunda-engine-rest:war:* + + true + + + **/web.xml + + + + + + + + src/main/runtime/tomcat/webapp + / + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-wildfly.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-wildfly.xml new file mode 100644 index 0000000000000000000000000000000000000000..c66785c9e7eab4af65eb3a2451a06dfb3c479bed --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-wildfly.xml @@ -0,0 +1,50 @@ + + + + wildfly + + + war + + + false + + + + src/main/runtime/wildfly/webapp + / + + + + + + WEB-INF/lib + true + true + provided + + org.camunda.bpm:camunda-engine-rest-core:jar + + + org.camunda.bpm:camunda-engine-rest-core:jar:tests + org.camunda.bpm:camunda-engine-rest-core:jar:sources + + + + + / + + org.camunda.bpm:camunda-engine-rest:war:* + + true + + + **/jboss-deployment-structure.xml + **/web.xml + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-wls.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-wls.xml new file mode 100644 index 0000000000000000000000000000000000000000..3c87f567766e32ae602e2c7fc0e31331103001fe --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/assembly-war-wls.xml @@ -0,0 +1,50 @@ + + + + wls + + + war + + + false + + + + src/main/runtime/wls/webapp + / + + + + + + WEB-INF/lib + true + true + provided + + org.camunda.bpm:camunda-engine-rest-core:jar + org.glassfish.jersey.containers:jersey-container-servlet:* + org.glassfish.jersey.inject:jersey-hk2:* + + + org.camunda.bpm:camunda-engine-rest-core:jar:tests + org.camunda.bpm:camunda-engine-rest-core:jar:sources + + + + + / + true + + + **/web.xml + + + + org.camunda.bpm:camunda-engine-rest:war:* + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..3b247510e3e08be4f4216e1a95ab496eef21ae72 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/pom.xml @@ -0,0 +1,194 @@ + + 4.0.0 + camunda-engine-rest + Camunda Platform - engine - REST - Assembly + war + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + org.camunda.bpm + camunda-engine-rest-root + ../ + 7.24.0-SNAPSHOT + + + + + false + compile|provided + + + + + org.camunda.bpm + camunda-engine-rest-core + ${project.version} + + + + + org.camunda.bpm + camunda-engine-rest-core + ${project.version} + sources + provided + + + + org.camunda.bpm + camunda-engine-rest-core + ${project.version} + tests + provided + + + + org.jboss.resteasy + resteasy-jaxrs + ${version.resteasy} + provided + + + + org.glassfish.jersey.containers + jersey-container-servlet + ${version.jersey2} + provided + + + org.glassfish.jersey.inject + jersey-hk2 + ${version.jersey2} + provided + + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + wildfly + package + + single + + + + + + org.camunda.bpm.camunda-engine,org.camunda.bpm.dmn.camunda-engine-dmn,org.camunda.commons.camunda-commons-logging,org.camunda.spin.camunda-spin-core,org.camunda.bpm.juel.camunda-juel services,org.graalvm.js.js-scriptengine services + + + + assembly-war-wildfly.xml + + camunda-engine-rest-${project.version} + true + wildfly + target/ + target/assembly/work + + + + + tomcat + package + + single + + + + assembly-war-tomcat.xml + + camunda-engine-rest-${project.version} + true + tomcat + target/ + target/assembly/work + + + + + wls + package + + single + + + + assembly-war-wls.xml + + camunda-engine-rest-${project.version} + true + wls + target/ + target/assembly/work + + + + + classes + package + + single + + + + assembly-classes.xml + + camunda-engine-rest-${project.version} + true + target/ + target/assembly/work + + + + + sources + package + + single + + + + assembly-sources.xml + + camunda-engine-rest-${project.version} + true + target/ + target/assembly/work + + + + + tests + package + + single + + + + assembly-tests.xml + + camunda-engine-rest-${project.version} + true + target/ + target/assembly/work + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/java/org/camunda/bpm/engine/rest/impl/application/DefaultApplication.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/java/org/camunda/bpm/engine/rest/impl/application/DefaultApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..8b478ff50b13867900e0da88e198c2f4cf9f046d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/java/org/camunda/bpm/engine/rest/impl/application/DefaultApplication.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.application; + +import org.camunda.bpm.engine.rest.impl.CamundaRestResources; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.HashSet; +import java.util.Set; + +/** + *

Default {@link Application} registering all resources.

+ * + *

NOTE This class is excluded from the classes-jar, + * such that users that want to embed the REST API as a JAR file into a + * custom JAX-RS application are able to build a deployment based on their + * requirements.

+ * + * @author Daniel Meyer + * + */ +@ApplicationPath("/") +public class DefaultApplication extends Application { + + @Override + public Set> getClasses() { + Set> classes = new HashSet>(); + + classes.addAll(CamundaRestResources.getResourceClasses()); + classes.addAll(CamundaRestResources.getConfigurationClasses()); + + return classes; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/jbossas7/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/jbossas7/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..804f187341933271308e393c966354d5baf1542a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/jbossas7/webapp/WEB-INF/web.xml @@ -0,0 +1,87 @@ + + + + + + + + + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + true + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + true + + + CacheControlFilter + /* + + + + + + + Resteasy + org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher + + javax.ws.rs.Application + org.camunda.bpm.engine.rest.impl.application.DefaultApplication + + true + + + + Resteasy + /* + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/tomcat/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/tomcat/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..2f43fe8b4272d3af977c3747b3e8ec895c61b7a4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/tomcat/webapp/WEB-INF/web.xml @@ -0,0 +1,88 @@ + + + + + + + + + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + true + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + true + + + CacheControlFilter + /* + + + + + + + Resteasy + org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher + + javax.ws.rs.Application + org.camunda.bpm.engine.rest.impl.application.DefaultApplication + + true + + + + Resteasy + /* + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/was/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/was/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..b1c2214baf2a97ed6f1de8387f937bdc8cbe248a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/was/webapp/WEB-INF/web.xml @@ -0,0 +1,85 @@ + + + + Camunda Platform REST API + + + + + + + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + true + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + true + + + CacheControlFilter + /* + + + + + + + Engine API + org.glassfish.jersey.servlet.ServletContainer + + javax.ws.rs.Application + org.camunda.bpm.engine.rest.impl.application.DefaultApplication + + true + + + + Engine API + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wildfly/webapp/WEB-INF/jboss-deployment-structure.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wildfly/webapp/WEB-INF/jboss-deployment-structure.xml new file mode 100644 index 0000000000000000000000000000000000000000..0bfd3c720b3f4f6883f2999a3e7059d548a517ec --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wildfly/webapp/WEB-INF/jboss-deployment-structure.xml @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wildfly/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wildfly/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..98aec2f8c1e6a26f2860eb6ec0cd7e3cf0766aa8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wildfly/webapp/WEB-INF/web.xml @@ -0,0 +1,71 @@ + + + + Camunda Platform rest api + + + + + + + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + true + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + true + + + CacheControlFilter + /* + + + + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wls/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wls/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..cddf114aa4183b607bf37467460a319bb51ce78a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/runtime/wls/webapp/WEB-INF/web.xml @@ -0,0 +1,99 @@ + + + + Camunda Platform rest api + + + + + + + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + true + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + true + + + CacheControlFilter + /* + + + + + + + org.camunda.bpm.engine.rest.impl.application.DefaultApplication + + + jersey.config.server.disableMoxyJson + true + + + + jersey.config.server.provider.classnames + + org.glassfish.jersey.jackson.JacksonFeature + + + + + true + + + + org.camunda.bpm.engine.rest.impl.application.DefaultApplication + /* + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.PermissionProvider b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.PermissionProvider new file mode 100644 index 0000000000000000000000000000000000000000..c45c3cc926ebbb1348f1974e44363cef25c7e923 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.PermissionProvider @@ -0,0 +1 @@ +org.camunda.bpm.engine.rest.spi.impl.DefaultPermissionProvider \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider new file mode 100644 index 0000000000000000000000000000000000000000..c52f72c1266582bf7316c8584a1290b3d7d5ac13 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/classes/META-INF/services/org.camunda.bpm.engine.rest.spi.ProcessEngineProvider @@ -0,0 +1 @@ +org.camunda.bpm.engine.rest.impl.application.ContainerManagedProcessEngineProvider \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/glassfish-web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/glassfish-web.xml new file mode 100644 index 0000000000000000000000000000000000000000..6394408fcf7397a08cfd6b2ae183fa357599c227 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/glassfish-web.xml @@ -0,0 +1,6 @@ + + + + /engine-rest + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/jboss-deployment-structure.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/jboss-deployment-structure.xml new file mode 100644 index 0000000000000000000000000000000000000000..0a55b19ec0852445c02bd598a051d5ffcbdcc147 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/jboss-deployment-structure.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/jboss-web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/jboss-web.xml new file mode 100644 index 0000000000000000000000000000000000000000..ddfd71eec232440c62113b6b0f22f920b771e62a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/jboss-web.xml @@ -0,0 +1,6 @@ + + + + other + /engine-rest + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/web.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000000000000000000000000000000000..6c7ccf6b85ec42092469d22772689435fe6ade9b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,49 @@ + + + + Camunda Platform rest api + + + + org.camunda.bpm.engine.rest.impl.web.bootstrap.RestContainerBootstrap + + + + EmptyBodyFilter + org.camunda.bpm.engine.rest.filter.EmptyBodyFilter + + + EmptyBodyFilter + /* + + + + CacheControlFilter + org.camunda.bpm.engine.rest.filter.CacheControlFilter + + + CacheControlFilter + /* + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/weblogic.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/weblogic.xml new file mode 100644 index 0000000000000000000000000000000000000000..2dbdf0e4b77f9efd3471ab79e6cd58e81a54fa52 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/assembly/src/main/webapp/WEB-INF/weblogic.xml @@ -0,0 +1,32 @@ + + + + + /* + UTF-8 + + + /engine-rest + + + com.fasterxml.jackson.* + org.apache.commons.fileupload.* + + javax.ws.rs.* + org.glassfish.jersey.* + org.glassfish.hk2.* + org.jvnet.hk2.* + jersey.repackaged.* + com.sun.research.ws.wadl.* + + + + META-INF/services/javax.servlet.ServletContainerInitializer + META-INF/services/javax.ws.rs.ext.RuntimeDelegate + META-INF/services/org.glassfish.jersey.* + org.glassfish.jersey.* + jersey.repackaged.* + META-INF/services/org.glassfish.hk2.* + + + \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/.gitignore b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9c7e64d37722d8d724d5fe13eb592a2efe49e530 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +node/ +target/ \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/build.js b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/build.js new file mode 100644 index 0000000000000000000000000000000000000000..cd9c3448c444c749d99342f3e53e3366b6dc0300 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/build.js @@ -0,0 +1,83 @@ +#!/usr/bin/env node + +const {createElement} = require("react"); +const {renderToString} = require("react-dom/server"); + +const {ServerStyleSheet} = require("styled-components"); +const {dirname, join} = require("path"); + +const { + readFileSync, + writeFileSync +} = require("fs"); + +const {Redoc, createStore, loadAndBundleSpec} = require("redoc"); + +const SPEC_PATH = "docs/target/dependency/openapi.json"; + +async function generateDocs() { + const spec = await loadAndBundleSpec(SPEC_PATH); + const store = await createStore(spec, null, {}); + + const styleSheet = new ServerStyleSheet(); + const html = renderToString( + styleSheet.collectStyles(createElement(Redoc, {store})) + ); + + const redocJs = readFileSync( + join(dirname(require.resolve("redoc")), "redoc.standalone.js") + ); + + const state = await store.toJS() + + const camundaVersion = require('./package.json').version; + + const page = ` + + + + + + + + Camunda Automation Platform ${camundaVersion} REST API + + + + + + ${styleSheet.getStyleTags()} + + + + + +
${html}
+ + +` + + writeFileSync('./target/index.html', page); +} + +generateDocs(); diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/package-lock.json b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..b5ae5b3be5132538f4cf504cc7edc454de4b375f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/package-lock.json @@ -0,0 +1,1128 @@ +{ + "name": "docs", + "version": "7.23.0-SNAPSHOT", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "docs", + "version": "7.23.0-SNAPSHOT", + "dependencies": { + "react": "19.1.0", + "react-dom": "19.1.0", + "redoc": "2.5.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.0.tgz", + "integrity": "sha512-VtPOkrdPHZsKc/clNqyi9WUA8TINkZ4cGk63UUE3u4pmB2k+ZMQRDuIOagv8UVd6j7k0T3+RRIb7beKTebNbcw==", + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emotion/is-prop-valid": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.2.2.tgz", + "integrity": "sha512-uNsoYd37AFmaCdXlg6EYD1KaPOaRWRByMCYzbKUX4+hhMfrxdVSelShywL4JVaAeM/eHUOSprYBQls+/neX3pw==", + "peer": true, + "dependencies": { + "@emotion/memoize": "^0.8.1" + } + }, + "node_modules/@emotion/memoize": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@emotion/memoize/-/memoize-0.8.1.tgz", + "integrity": "sha512-W2P2c/VRW1/1tLox0mVUalvnWXxavmv/Oum2aPsRcoDJuob75FC3Y8FbpfLwUegRcxINtGUMPq0tFCvYNTBXNA==", + "peer": true + }, + "node_modules/@emotion/unitless": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@emotion/unitless/-/unitless-0.8.1.tgz", + "integrity": "sha512-KOEGMu6dmJZtpadb476IsZBclKvILjopjUii3V+7MnXIQCYh8W3NgNcgwo21n9LXZX6EDIKvqfjYxXebDwxKmQ==", + "peer": true + }, + "node_modules/@exodus/schemasafe": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@exodus/schemasafe/-/schemasafe-1.3.0.tgz", + "integrity": "sha512-5Aap/GaRupgNx/feGBwLLTVv8OQFfv3pq2lPRzPg9R+IOBnDgghTGW7l7EuVXOvg5cc/xSAlRW8rBrjIC3Nvqw==" + }, + "node_modules/@redocly/ajv": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/@redocly/ajv/-/ajv-8.11.2.tgz", + "integrity": "sha512-io1JpnwtIcvojV7QKDUSIuMN/ikdOUd1ReEnUnMKGfDVridQZ31J0MmIuqwuRjWDZfmvr+Q0MqCcfHM2gTivOg==", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2", + "uri-js-replace": "^1.0.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@redocly/config": { + "version": "0.22.2", + "resolved": "https://registry.npmjs.org/@redocly/config/-/config-0.22.2.tgz", + "integrity": "sha512-roRDai8/zr2S9YfmzUfNhKjOF0NdcOIqF7bhf4MVC5UxpjIysDjyudvlAiVbpPHp3eDRWbdzUgtkK1a7YiDNyQ==" + }, + "node_modules/@redocly/openapi-core": { + "version": "1.34.2", + "resolved": "https://registry.npmjs.org/@redocly/openapi-core/-/openapi-core-1.34.2.tgz", + "integrity": "sha512-glfkQFJizLdq2fBkNvc2FJW0sxDb5exd0wIXhFk+WHaFLMREBC3CxRo2Zq7uJIdfV9U3YTceMbXJklpDfmmwFQ==", + "dependencies": { + "@redocly/ajv": "^8.11.2", + "@redocly/config": "^0.22.0", + "colorette": "^1.2.0", + "https-proxy-agent": "^7.0.5", + "js-levenshtein": "^1.1.6", + "js-yaml": "^4.1.0", + "minimatch": "^5.0.1", + "pluralize": "^8.0.0", + "yaml-ast-parser": "0.0.43" + }, + "engines": { + "node": ">=18.17.0", + "npm": ">=9.5.0" + } + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==" + }, + "node_modules/@types/stylis": { + "version": "4.2.5", + "resolved": "https://registry.npmjs.org/@types/stylis/-/stylis-4.2.5.tgz", + "integrity": "sha512-1Xve+NMN7FWjY14vLoY5tL3BVEQ/n42YLwaqJIPYhotZ9uBHt87VceMwWQpzmdEt2TNXIorIFG+YeCUUW7RInw==", + "peer": true + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "optional": true + }, + "node_modules/agent-base": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz", + "integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/call-me-maybe": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-me-maybe/-/call-me-maybe-1.0.2.tgz", + "integrity": "sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==" + }, + "node_modules/camelize": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/camelize/-/camelize-1.0.1.tgz", + "integrity": "sha512-dU+Tx2fsypxTgtLoE36npi3UqcjSSMNYfkqgmoEhtZrraP5VWq0K7FkWVTYa8eMPtnU/G2txVsfdCJTn9uzpuQ==", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/classnames": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/classnames/-/classnames-2.5.1.tgz", + "integrity": "sha512-saHYOzhIQs6wy2sVxTM6bUDsQO4F50V9RQ22qBpEdCW+I+/Wmke2HOl6lS6dTpdxVhb88/I6+Hs+438c3lfUow==" + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/colorette": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-1.4.0.tgz", + "integrity": "sha512-Y2oEozpomLn7Q3HFP7dpww7AtMJplbM9lGZP6RDfHqmbeRjiwRg4n6VM6j4KLmRke85uWEI7JqF17f3pqdRA0g==" + }, + "node_modules/core-js": { + "version": "3.41.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.41.0.tgz", + "integrity": "sha512-SJ4/EHwS36QMJd6h/Rg+GyR4A5xE0FSI3eZ+iBVpfqf1x0eTSg1smWLHrA+2jQThZSh97fmSgFSU8B61nxosxA==", + "hasInstallScript": true, + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/css-color-keywords": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/css-color-keywords/-/css-color-keywords-1.0.0.tgz", + "integrity": "sha512-FyyrDHZKEjXDpNJYvVsV960FiqQyXc/LlYmsxl2BcdMb2WPx0OGRVgTg55rPSyLSNMqP52R9r8geSp7apN3Ofg==", + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/css-to-react-native": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/css-to-react-native/-/css-to-react-native-3.2.0.tgz", + "integrity": "sha512-e8RKaLXMOFii+02mOlqwjbD00KSEKqblnpO9e++1aXS1fPQOpS1YoqdVHBqPjHNoxeF2mimzVqawm2KCbEdtHQ==", + "peer": true, + "dependencies": { + "camelize": "^1.0.0", + "css-color-keywords": "^1.0.0", + "postcss-value-parser": "^4.0.2" + } + }, + "node_modules/csstype": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", + "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", + "peer": true + }, + "node_modules/debug": { + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", + "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decko": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decko/-/decko-1.2.0.tgz", + "integrity": "sha512-m8FnyHXV1QX+S1cl+KPFDIl6NMkxtKsy6+U/aYyjrOqWMuwAwYWu7ePqrsUHtDR5Y8Yk2pi/KIDSgF+vT4cPOQ==" + }, + "node_modules/dompurify": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.5.tgz", + "integrity": "sha512-mLPd29uoRe9HpvwP2TxClGQBzGXeEC/we/q+bFlmPPmj2p2Ugl3r6ATu/UU1v77DXNcehiBg9zsr1dREyA/dJQ==", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/es6-promise": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-3.3.1.tgz", + "integrity": "sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==" + }, + "node_modules/fast-xml-parser": { + "version": "4.5.3", + "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-4.5.3.tgz", + "integrity": "sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ], + "dependencies": { + "strnum": "^1.1.1" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/foreach": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/foreach/-/foreach-2.0.6.tgz", + "integrity": "sha512-k6GAGDyqLe9JaebCsFCoudPPWfihKu8pylYXRlqP1J7ms39iPoTtk2fviNglIeQEwdh0bQeKJ01ZPyuyQvKzwg==" + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/http2-client": { + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/http2-client/-/http2-client-1.3.5.tgz", + "integrity": "sha512-EC2utToWl4RKfs5zd36Mxq7nzHHBuomZboI0yYL6Y0RmBgT7Sgkq4rQ0ezFTYoIsSs7Tm9SJe+o2FcAg6GBhGA==" + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/js-levenshtein": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/js-levenshtein/-/js-levenshtein-1.1.6.tgz", + "integrity": "sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-pointer": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/json-pointer/-/json-pointer-0.6.2.tgz", + "integrity": "sha512-vLWcKbOaXlO+jvRy4qNd+TI1QUPZzfJj1tpJ3vAXDych5XJf93ftpUKe5pKCrzyIIwgBJcOcCVRUfqQP25afBw==", + "dependencies": { + "foreach": "^2.0.4" + } + }, + "node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lunr": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", + "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==" + }, + "node_modules/mark.js": { + "version": "8.11.1", + "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz", + "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==" + }, + "node_modules/marked": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.3.0.tgz", + "integrity": "sha512-PRsaiG84bK+AMvxziE/lCFss8juXjNaWzVbN5tXAm4XjeaS9NAHhop+PjQxz2A9h8Q4M/xGmzP8vqNwy6JeK0A==", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mobx": { + "version": "6.13.7", + "resolved": "https://registry.npmjs.org/mobx/-/mobx-6.13.7.tgz", + "integrity": "sha512-aChaVU/DO5aRPmk1GX8L+whocagUUpBQqoPtJk+cm7UOXUk87J4PeWCh6nNmTTIfEhiR9DI/+FnA8dln/hTK7g==", + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mobx" + } + }, + "node_modules/mobx-react": { + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/mobx-react/-/mobx-react-9.2.0.tgz", + "integrity": "sha512-dkGWCx+S0/1mfiuFfHRH8D9cplmwhxOV5CkXMp38u6rQGG2Pv3FWYztS0M7ncR6TyPRQKaTG/pnitInoYE9Vrw==", + "dependencies": { + "mobx-react-lite": "^4.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mobx" + }, + "peerDependencies": { + "mobx": "^6.9.0", + "react": "^16.8.0 || ^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + }, + "react-native": { + "optional": true + } + } + }, + "node_modules/mobx-react-lite": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/mobx-react-lite/-/mobx-react-lite-4.1.0.tgz", + "integrity": "sha512-QEP10dpHHBeQNv1pks3WnHRCem2Zp636lq54M2nKO2Sarr13pL4u6diQXf65yzXUn0mkk18SyIDCm9UOJYTi1w==", + "dependencies": { + "use-sync-external-store": "^1.4.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mobx" + }, + "peerDependencies": { + "mobx": "^6.9.0", + "react": "^16.8.0 || ^17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + }, + "react-native": { + "optional": true + } + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-fetch-h2": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/node-fetch-h2/-/node-fetch-h2-2.3.0.tgz", + "integrity": "sha512-ofRW94Ab0T4AOh5Fk8t0h8OBWrmjb0SSB20xh1H8YnPV9EJ+f5AMoYSUQ2zgJ4Iq2HAK0I2l5/Nequ8YzFS3Hg==", + "dependencies": { + "http2-client": "^1.2.5" + }, + "engines": { + "node": "4.x || >=6.0.0" + } + }, + "node_modules/node-readfiles": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/node-readfiles/-/node-readfiles-0.2.0.tgz", + "integrity": "sha512-SU00ZarexNlE4Rjdm83vglt5Y9yiQ+XI1XpflWlb7q7UTN1JUItm69xMeiQCTxtTfnzt+83T8Cx+vI2ED++VDA==", + "dependencies": { + "es6-promise": "^3.2.1" + } + }, + "node_modules/oas-kit-common": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/oas-kit-common/-/oas-kit-common-1.0.8.tgz", + "integrity": "sha512-pJTS2+T0oGIwgjGpw7sIRU8RQMcUoKCDWFLdBqKB2BNmGpbBMH2sdqAaOXUg8OzonZHU0L7vfJu1mJFEiYDWOQ==", + "dependencies": { + "fast-safe-stringify": "^2.0.7" + } + }, + "node_modules/oas-linter": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/oas-linter/-/oas-linter-3.2.2.tgz", + "integrity": "sha512-KEGjPDVoU5K6swgo9hJVA/qYGlwfbFx+Kg2QB/kd7rzV5N8N5Mg6PlsoCMohVnQmo+pzJap/F610qTodKzecGQ==", + "dependencies": { + "@exodus/schemasafe": "^1.0.0-rc.2", + "should": "^13.2.1", + "yaml": "^1.10.0" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-resolver": { + "version": "2.5.6", + "resolved": "https://registry.npmjs.org/oas-resolver/-/oas-resolver-2.5.6.tgz", + "integrity": "sha512-Yx5PWQNZomfEhPPOphFbZKi9W93CocQj18NlD2Pa4GWZzdZpSJvYwoiuurRI7m3SpcChrnO08hkuQDL3FGsVFQ==", + "dependencies": { + "node-fetch-h2": "^2.3.0", + "oas-kit-common": "^1.0.8", + "reftools": "^1.1.9", + "yaml": "^1.10.0", + "yargs": "^17.0.1" + }, + "bin": { + "resolve": "resolve.js" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-schema-walker": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/oas-schema-walker/-/oas-schema-walker-1.1.5.tgz", + "integrity": "sha512-2yucenq1a9YPmeNExoUa9Qwrt9RFkjqaMAA1X+U7sbb0AqBeTIdMHky9SQQ6iN94bO5NW0W4TRYXerG+BdAvAQ==", + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/oas-validator": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/oas-validator/-/oas-validator-5.0.8.tgz", + "integrity": "sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==", + "dependencies": { + "call-me-maybe": "^1.0.1", + "oas-kit-common": "^1.0.8", + "oas-linter": "^3.2.2", + "oas-resolver": "^2.5.6", + "oas-schema-walker": "^1.1.5", + "reftools": "^1.1.9", + "should": "^13.2.1", + "yaml": "^1.10.0" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/openapi-sampler": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/openapi-sampler/-/openapi-sampler-1.6.1.tgz", + "integrity": "sha512-s1cIatOqrrhSj2tmJ4abFYZQK6l5v+V4toO5q1Pa0DyN8mtyqy2I+Qrj5W9vOELEtybIMQs/TBZGVO/DtTFK8w==", + "dependencies": { + "@types/json-schema": "^7.0.7", + "fast-xml-parser": "^4.5.0", + "json-pointer": "0.6.2" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==" + }, + "node_modules/perfect-scrollbar": { + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/perfect-scrollbar/-/perfect-scrollbar-1.5.6.tgz", + "integrity": "sha512-rixgxw3SxyJbCaSpo1n35A/fwI1r2rdwMKOTCg/AcG+xOEyZcE8UHVjpZMFCVImzsFoCZeJTT+M/rdEIQYO2nw==" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "peer": true + }, + "node_modules/pluralize": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", + "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", + "engines": { + "node": ">=4" + } + }, + "node_modules/polished": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/polished/-/polished-4.3.1.tgz", + "integrity": "sha512-OBatVyC/N7SCW/FaDHrSd+vn0o5cS855TOmYi4OkdWUMSJCET/xip//ch8xGUvtr3i44X9LVyWwQlRMTN3pwSA==", + "dependencies": { + "@babel/runtime": "^7.17.8" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/postcss": { + "version": "8.4.49", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.49.tgz", + "integrity": "sha512-OCVPnIObs4N29kxTjzLfUryOkvZEq+pf8jTF0lg8E7uETuWHA+v7j3c/xJmiqpX450191LlmZfUKkXxkTry7nA==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "peer": true, + "dependencies": { + "nanoid": "^3.3.7", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "peer": true + }, + "node_modules/prismjs": { + "version": "1.30.0", + "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz", + "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/react": { + "version": "19.1.0", + "resolved": "https://registry.npmjs.org/react/-/react-19.1.0.tgz", + "integrity": "sha512-FS+XFBNvn3GTAWq26joslQgWNoFu08F4kl0J4CgdNKADkdSGXQyTCnKteIAJy96Br6YbpEU1LSzV5dYtjMkMDg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.1.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.1.0.tgz", + "integrity": "sha512-Xs1hdnE+DyKgeHJeJznQmYMIBG3TKIHJJT95Q58nHLSrElKlGQqDTR2HQ9fx5CN/Gk6Vh/kupBTDLU11/nDk/g==", + "dependencies": { + "scheduler": "^0.26.0" + }, + "peerDependencies": { + "react": "^19.1.0" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + }, + "node_modules/react-tabs": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/react-tabs/-/react-tabs-6.1.0.tgz", + "integrity": "sha512-6QtbTRDKM+jA/MZTTefvigNxo0zz+gnBTVFw2CFVvq+f2BuH0nF0vDLNClL045nuTAdOoK/IL1vTP0ZLX0DAyQ==", + "dependencies": { + "clsx": "^2.0.0", + "prop-types": "^15.5.0" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0" + } + }, + "node_modules/redoc": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/redoc/-/redoc-2.5.0.tgz", + "integrity": "sha512-NpYsOZ1PD9qFdjbLVBZJWptqE+4Y6TkUuvEOqPUmoH7AKOmPcE+hYjotLxQNTqVoWL4z0T2uxILmcc8JGDci+Q==", + "dependencies": { + "@redocly/openapi-core": "^1.4.0", + "classnames": "^2.3.2", + "decko": "^1.2.0", + "dompurify": "^3.2.4", + "eventemitter3": "^5.0.1", + "json-pointer": "^0.6.2", + "lunr": "^2.3.9", + "mark.js": "^8.11.1", + "marked": "^4.3.0", + "mobx-react": "^9.1.1", + "openapi-sampler": "^1.5.0", + "path-browserify": "^1.0.1", + "perfect-scrollbar": "^1.5.5", + "polished": "^4.2.2", + "prismjs": "^1.29.0", + "prop-types": "^15.8.1", + "react-tabs": "^6.0.2", + "slugify": "~1.4.7", + "stickyfill": "^1.1.1", + "swagger2openapi": "^7.0.8", + "url-template": "^2.0.8" + }, + "engines": { + "node": ">=6.9", + "npm": ">=3.0.0" + }, + "peerDependencies": { + "core-js": "^3.1.4", + "mobx": "^6.0.4", + "react": "^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "styled-components": "^4.1.1 || ^5.1.1 || ^6.0.5" + } + }, + "node_modules/reftools": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/reftools/-/reftools-1.1.9.tgz", + "integrity": "sha512-OVede/NQE13xBQ+ob5CKd5KyeJYU2YInb1bmV4nRoOfquZPkAkxuOXicSe1PvqIuZZ4kD13sPKBbR7UFDmli6w==", + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz", + "integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/scheduler": { + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.26.0.tgz", + "integrity": "sha512-NlHwttCI/l5gCPR3D1nNXtWABUmBwvZpEQiD4IXSbIDq8BzLIK/7Ir5gTFSGZDUu37K5cMNp0hFtzO38sC7gWA==" + }, + "node_modules/shallowequal": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/shallowequal/-/shallowequal-1.1.0.tgz", + "integrity": "sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==", + "peer": true + }, + "node_modules/should": { + "version": "13.2.3", + "resolved": "https://registry.npmjs.org/should/-/should-13.2.3.tgz", + "integrity": "sha512-ggLesLtu2xp+ZxI+ysJTmNjh2U0TsC+rQ/pfED9bUZZ4DKefP27D+7YJVVTvKsmjLpIi9jAa7itwDGkDDmt1GQ==", + "dependencies": { + "should-equal": "^2.0.0", + "should-format": "^3.0.3", + "should-type": "^1.4.0", + "should-type-adaptors": "^1.0.1", + "should-util": "^1.0.0" + } + }, + "node_modules/should-equal": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/should-equal/-/should-equal-2.0.0.tgz", + "integrity": "sha512-ZP36TMrK9euEuWQYBig9W55WPC7uo37qzAEmbjHz4gfyuXrEUgF8cUvQVO+w+d3OMfPvSRQJ22lSm8MQJ43LTA==", + "dependencies": { + "should-type": "^1.4.0" + } + }, + "node_modules/should-format": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/should-format/-/should-format-3.0.3.tgz", + "integrity": "sha512-hZ58adtulAk0gKtua7QxevgUaXTTXxIi8t41L3zo9AHvjXO1/7sdLECuHeIN2SRtYXpNkmhoUP2pdeWgricQ+Q==", + "dependencies": { + "should-type": "^1.3.0", + "should-type-adaptors": "^1.0.1" + } + }, + "node_modules/should-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/should-type/-/should-type-1.4.0.tgz", + "integrity": "sha512-MdAsTu3n25yDbIe1NeN69G4n6mUnJGtSJHygX3+oN0ZbO3DTiATnf7XnYJdGT42JCXurTb1JI0qOBR65shvhPQ==" + }, + "node_modules/should-type-adaptors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/should-type-adaptors/-/should-type-adaptors-1.1.0.tgz", + "integrity": "sha512-JA4hdoLnN+kebEp2Vs8eBe9g7uy0zbRo+RMcU0EsNy+R+k049Ki+N5tT5Jagst2g7EAja+euFuoXFCa8vIklfA==", + "dependencies": { + "should-type": "^1.3.0", + "should-util": "^1.0.0" + } + }, + "node_modules/should-util": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/should-util/-/should-util-1.0.1.tgz", + "integrity": "sha512-oXF8tfxx5cDk8r2kYqlkUJzZpDBqVY/II2WhvU0n9Y3XYvAYRmeaf1PvvIvTgPnv4KJ+ES5M0PyDq5Jp+Ygy2g==" + }, + "node_modules/slugify": { + "version": "1.4.7", + "resolved": "https://registry.npmjs.org/slugify/-/slugify-1.4.7.tgz", + "integrity": "sha512-tf+h5W1IrjNm/9rKKj0JU2MDMruiopx0jjVA5zCdBtcGjfp0+c5rHw/zADLC3IeKlGHtVbHtpfzvYA0OYT+HKg==", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stickyfill": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/stickyfill/-/stickyfill-1.1.1.tgz", + "integrity": "sha512-GCp7vHAfpao+Qh/3Flh9DXEJ/qSi0KJwJw6zYlZOtRYXWUIpMM6mC2rIep/dK8RQqwW0KxGJIllmjPIBOGN8AA==" + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strnum": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/strnum/-/strnum-1.1.2.tgz", + "integrity": "sha512-vrN+B7DBIoTTZjnPNewwhx6cBA/H+IS7rfW68n7XxC1y7uoiGQBxaKzqucGUgavX15dJgiGztLJ8vxuEzwqBdA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + } + ] + }, + "node_modules/styled-components": { + "version": "6.1.17", + "resolved": "https://registry.npmjs.org/styled-components/-/styled-components-6.1.17.tgz", + "integrity": "sha512-97D7DwWanI7nN24v0D4SvbfjLE9656umNSJZkBkDIWL37aZqG/wRQ+Y9pWtXyBIM/NSfcBzHLErEsqHmJNSVUg==", + "peer": true, + "dependencies": { + "@emotion/is-prop-valid": "1.2.2", + "@emotion/unitless": "0.8.1", + "@types/stylis": "4.2.5", + "css-to-react-native": "3.2.0", + "csstype": "3.1.3", + "postcss": "8.4.49", + "shallowequal": "1.1.0", + "stylis": "4.3.2", + "tslib": "2.6.2" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/styled-components" + }, + "peerDependencies": { + "react": ">= 16.8.0", + "react-dom": ">= 16.8.0" + } + }, + "node_modules/stylis": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.2.tgz", + "integrity": "sha512-bhtUjWd/z6ltJiQwg0dUfxEJ+W+jdqQd8TbWLWyeIJHlnsqmGLRFFd8e5mA0AZi/zx90smXRlN66YMTcaSFifg==", + "peer": true + }, + "node_modules/swagger2openapi": { + "version": "7.0.8", + "resolved": "https://registry.npmjs.org/swagger2openapi/-/swagger2openapi-7.0.8.tgz", + "integrity": "sha512-upi/0ZGkYgEcLeGieoz8gT74oWHA0E7JivX7aN9mAf+Tc7BQoRBvnIGHoPDw+f9TXTW4s6kGYCZJtauP6OYp7g==", + "dependencies": { + "call-me-maybe": "^1.0.1", + "node-fetch": "^2.6.1", + "node-fetch-h2": "^2.3.0", + "node-readfiles": "^0.2.0", + "oas-kit-common": "^1.0.8", + "oas-resolver": "^2.5.6", + "oas-schema-walker": "^1.1.5", + "oas-validator": "^5.0.8", + "reftools": "^1.1.9", + "yaml": "^1.10.0", + "yargs": "^17.0.1" + }, + "bin": { + "boast": "boast.js", + "oas-validate": "oas-validate.js", + "swagger2openapi": "swagger2openapi.js" + }, + "funding": { + "url": "https://github.com/Mermade/oas-kit?sponsor=1" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==", + "peer": true + }, + "node_modules/uri-js-replace": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/uri-js-replace/-/uri-js-replace-1.0.1.tgz", + "integrity": "sha512-W+C9NWNLFOoBI2QWDp4UT9pv65r2w5Cx+3sTYFvtMdDBxkKt1syCqsUdSFAChbEe1uK5TfS04wt/nGwmaeIQ0g==" + }, + "node_modules/url-template": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/url-template/-/url-template-2.0.8.tgz", + "integrity": "sha512-XdVKMF4SJ0nP/O7XIPB0JwAEuT9lDIYnNsK8yGVe43y0AWoKeJNdv3ZNWh7ksJ6KqQFjOO6ox/VEitLnaVNufw==" + }, + "node_modules/use-sync-external-store": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.5.0.tgz", + "integrity": "sha512-Rb46I4cGGVBmjamjphe8L/UnvJD+uPPtTkNvX5mZgqdbavhI4EbgIWJiIHXJ8bc/i9EQGPRh4DwEURJ552Do0A==", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yaml": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-1.10.2.tgz", + "integrity": "sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg==", + "engines": { + "node": ">= 6" + } + }, + "node_modules/yaml-ast-parser": { + "version": "0.0.43", + "resolved": "https://registry.npmjs.org/yaml-ast-parser/-/yaml-ast-parser-0.0.43.tgz", + "integrity": "sha512-2PTINUwsRqSd+s8XxKaJWQlUuEMHJQyEuh2edBbW8KNJz0SJPwUSD2zRWqezFEdN7IzAgeuYHFUCF7o8zRdZ0A==" + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "engines": { + "node": ">=12" + } + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/package.json b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1d7a68aa6991a0b5d4f745b239fe5c629210ac84 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/package.json @@ -0,0 +1,13 @@ +{ + "name": "docs", + "version": "7.24.0-SNAPSHOT", + "private": true, + "scripts": { + "build": "node build" + }, + "dependencies": { + "redoc": "2.5.0", + "react": "19.1.0", + "react-dom": "19.1.0" + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..cc6287f060566fe344dcf268306fcefe121dda40 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/docs/pom.xml @@ -0,0 +1,94 @@ + + + + camunda-engine-rest-root + org.camunda.bpm + 7.24.0-SNAPSHOT + + 4.0.0 + + docs + Camunda Platform - engine - REST - Docs + pom + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + true + + + + + org.camunda.bpm + camunda-engine-rest-openapi + ${project.version} + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + unpack + generate-resources + + unpack + + + + + org.camunda.bpm + camunda-engine-rest-openapi + ${project.version} + jar + + + + + + + + com.github.eirslett + frontend-maven-plugin + + ${project.build.directory} + ${skip.frontend.build} + + + + install node and npm + + install-node-and-npm + + + + npm install + + npm + + generate-resources + + ci + + + + npm run build + + npm + + generate-resources + + run build + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/README.md b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cbf99077201d0e8ed9a351f4259a100a3f2e5532 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/README.md @@ -0,0 +1,23 @@ +REST API +======== + +A JAX-RS-based REST API for Camunda Platform. + +Running Tests +------------- + +The REST API is tested against three JAX-RS runtimes: + +* Jersey +* Resteasy +* Wink + +In order to run the tests against any of these, execute `mvn clean install -P${runtime}` where `${runtime}` is either `jersey`, `resteasy`, or `wink`. `jersey` is active by default. + +Writing Tests +------------- + +For a test case that tests the implementation of a JAX-RS resource, do the following: + +* Subclass `org.camunda.bpm.engine.rest.AbstractRestServiceTest` +* Declare an instance of `org.camunda.bpm.engine.rest.util.container.TestContainerRule` as a JUnit `@ClassRule` diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/pom.xml b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..1ea33454bf1adca6c63d65155b41a6854082d6bb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/pom.xml @@ -0,0 +1,645 @@ + + 4.0.0 + camunda-engine-rest-core + Camunda Platform - engine - REST + jar + + + Note: 7.24.0 is the last community edition release published on Maven Central. This library will not receive any new versions or releases. However, if you are interested in extended maintenance you could look into our enterprise edition. Get in touch with us: https://camunda.com/contact/ + + + + org.camunda.bpm + camunda-engine-rest-root + ../ + 7.24.0-SNAPSHOT + + + + + 7.0.50 + 38080 + 1.1.1 + + + + + commons-fileupload + commons-fileupload + + + commons-io + commons-io + + + + + + commons-io + commons-io + + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + + + + jakarta.activation + jakarta.activation-api + + + jakarta.xml.bind + jakarta.xml.bind-api + + + + + + com.fasterxml.jackson.core + jackson-databind + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + + org.jboss.spec.javax.servlet + jboss-servlet-api_3.0_spec + provided + + + + org.camunda.bpm + camunda-engine + provided + + + org.springframework + spring-jcl + + + + + + org.camunda.commons + camunda-commons-logging + provided + + + + javax.activation + activation + ${javax.activation.version} + provided + + + + com.sun.xml.bind + jaxb-impl + test + + + + + org.camunda.bpm + camunda-bom + ${project.version} + pom + test + + + + org.camunda.bpm + camunda-core-internal-dependencies + ${project.version} + pom + test + + + + + junit + junit + test + + + + + + org.apache.tomcat.embed + tomcat-embed-jasper + ${version.tomcat} + test + + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-depchain + ${version.shrinkwrap.resolvers} + test + pom + + + + org.mockito + mockito-core + test + + + org.hamcrest + hamcrest-core + + + + + + io.rest-assured + rest-assured + test + + + + org.apache.httpcomponents + httpcore + test + + + + commons-codec + commons-codec + test + + + + com.h2database + h2 + test + + + + org.springframework + spring-test + ${version.spring.framework} + test + + + org.springframework + spring-jcl + + + + + + + ch.qos.logback + logback-classic + test + + + + org.slf4j + jcl-over-slf4j + test + + + + org.slf4j + jul-to-slf4j + test + + + + org.camunda.commons + camunda-commons-testing + test + + + + org.apache.tomcat.embed + tomcat-embed-core + ${version.tomcat} + test + + + + org.apache.tomcat.embed + tomcat-embed-logging-juli + ${version.tomcat} + test + + + + org.assertj + assertj-core + test + + + + + + + + src/test/resources + true + + + + + + org.apache.maven.plugins + maven-source-plugin + + + + attach-sources + + jar + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + test-jar + + + + + + + org.apache.maven.plugins + maven-war-plugin + + false + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + ${version.resteasy} + + -Xmx2g + + + + + org.jboss.shrinkwrap.resolver + shrinkwrap-resolver-maven-plugin + ${version.shrinkwrap.resolvers} + + + + propagate-execution-context + + + + + + + + + + distro + + + org.jboss.spec.javax.ws.rs + jboss-jaxrs-api_2.1_spec + provided + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + + resteasy + + 4.1.42.Final + + + + org.jboss.spec.javax.ws.rs + jboss-jaxrs-api_2.1_spec + provided + + + org.jboss.resteasy + resteasy-jaxrs + ${version.resteasy} + test + + + httpclient + org.apache.httpcomponents + + + + + + io.netty + netty-all + ${version.netty} + test + + + + org.jboss.resteasy + resteasy-netty4 + ${version.resteasy} + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + encoding-test + test + + test + + + + -Dfile.encoding=ISO-8859-1 + + **/ProcessDefinitionRestServiceInteractionTest.java + **/TaskRestServiceInteractionTest.java + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-test-source + generate-test-sources + + add-test-source + + + + src/test/java-resteasy + + + + + add-test-resource + generate-test-resources + + add-test-resource + + + + + + src/test/resources-resteasy + + + + + + + + + + + + + jersey2 + + true + + + + javax.ws.rs + javax.ws.rs-api + 2.0.1 + provided + + + org.glassfish.jersey.containers + jersey-container-grizzly2-http + ${version.jersey2} + test + + + org.glassfish.jersey.containers + jersey-container-servlet + ${version.jersey2} + test + + + org.glassfish.jersey.inject + jersey-hk2 + ${version.jersey2} + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/rest/standalone/** + + true + + + + encoding-test + test + + test + + + + -Dfile.encoding=ISO-8859-1 + + **/ProcessDefinitionRestServiceInteractionTest.java + **/TaskRestServiceInteractionTest.java + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-test-source + generate-test-sources + + add-test-source + + + + src/test/java-jersey2 + + + + + add-test-resource + generate-test-resources + + add-test-resource + + + + + src/test/resources-jersey2 + + + + + + + + + + + + wildfly-compatibility + + + 3.6.1.SP2 + 4.1.42.Final + + + + + org.jboss.spec.javax.ws.rs + jboss-jaxrs-api_2.1_spec + provided + + + + org.jboss.resteasy + resteasy-jaxrs + ${version.resteasy} + test + + + httpclient + org.apache.httpcomponents + + + + + + io.netty + netty-all + ${version.netty} + test + + + + org.jboss.resteasy + resteasy-netty4 + ${version.resteasy} + test + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + encoding-test + test + + test + + + + -Dfile.encoding=ISO-8859-1 + + **/ProcessDefinitionRestServiceInteractionTest.java + **/TaskRestServiceInteractionTest.java + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-test-source + generate-test-sources + + add-test-source + + + + src/test/java-resteasy + + + + + add-test-resource + generate-test-resources + + add-test-resource + + + + + + src/test/resources-resteasy + + + + + + + + + + + + + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/AuthorizationRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/AuthorizationRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..a35cd7b2f220c3231e6a62acb753044c937b3ec5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/AuthorizationRestService.java @@ -0,0 +1,74 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCheckResultDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCreateDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationDto; +import org.camunda.bpm.engine.rest.sub.authorization.AuthorizationResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author Daniel Meyer + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface AuthorizationRestService { + + public static final String PATH = "/authorization"; + + @GET + @Path("/check") + @Produces(MediaType.APPLICATION_JSON) + AuthorizationCheckResultDto isUserAuthorized( + @QueryParam("permissionName") String permissionName, + @QueryParam("resourceName") String resourceName, + @QueryParam("resourceType") Integer resourceType, + @QueryParam("resourceId") String resourceId, + @QueryParam("userId") String userId); + + @Path("/{id}") + AuthorizationResource getAuthorization(@PathParam("id") String id); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List queryAuthorizations(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getAuthorizationCount(@Context UriInfo uriInfo); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + AuthorizationDto createAuthorization(@Context UriInfo context, AuthorizationCreateDto dto); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/BatchRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/BatchRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..b462bf61cebc703f5678b246da0a4f1183956426 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/BatchRestService.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchStatisticsDto; +import org.camunda.bpm.engine.rest.sub.batch.BatchResource; + +public interface BatchRestService { + + String PATH = "/batch"; + + @Path("/{id}") + BatchResource getBatch(@PathParam("id") String batchId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getBatches(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getBatchesCount(@Context UriInfo uriInfo); + + @GET + @Path("/statistics") + @Produces(MediaType.APPLICATION_JSON) + List getStatistics(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/statistics/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getStatisticsCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..c2191f7db13f3cd5fce0ccf40c65cbfebe33055c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseDefinitionRestService.java @@ -0,0 +1,74 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.CaseDefinitionDto; +import org.camunda.bpm.engine.rest.sub.repository.CaseDefinitionResource; + +/** + * + * @author Roman Smirnov + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface CaseDefinitionRestService { + + public static final String PATH = "/case-definition"; + + @Path("/{id}") + CaseDefinitionResource getCaseDefinitionById(@PathParam("id") String caseDefinitionId); + + @Path("/key/{key}") + CaseDefinitionResource getCaseDefinitionByKey(@PathParam("key") String caseDefinitionKey); + + @Path("/key/{key}/tenant-id/{tenantId}") + CaseDefinitionResource getCaseDefinitionByKeyAndTenantId(@PathParam("key") String caseDefinitionKey, + @PathParam("tenantId") String tenantId); + + /** + * Exposes the {@link CaseDefinitionQuery} interface as a REST service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getCaseDefinitions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getCaseDefinitionsCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseExecutionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseExecutionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..264181e78d5d6823b67c73b259226466f50f3dd9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseExecutionRestService.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionQueryDto; +import org.camunda.bpm.engine.rest.sub.runtime.CaseExecutionResource; +import org.camunda.bpm.engine.runtime.CaseExecutionQuery; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * + * @author Roman Smirnov + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface CaseExecutionRestService { + + public static final String PATH = "/case-execution"; + + @Path("/{id}") + CaseExecutionResource getCaseExecution(@PathParam("id") String caseExecutionId); + + /** + * Exposes the {@link CaseExecutionQuery} interface as a REST service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getCaseExecutions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + /** + * Expects the same parameters as + * {@link CaseExecutionRestService#getCaseExecutions(UriInfo, Integer, Integer)} (as a JSON message body) + * and allows for any number of variable checks. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryCaseExecutions(CaseExecutionQueryDto query, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getCaseExecutionsCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryCaseExecutionsCount(CaseExecutionQueryDto query); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..c93b1da3b84b0560957b54b34e78007c4e43e717 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CaseInstanceRestService.java @@ -0,0 +1,85 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceQueryDto; +import org.camunda.bpm.engine.rest.sub.runtime.CaseInstanceResource; +import org.camunda.bpm.engine.runtime.CaseInstanceQuery; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author Roman Smirnov + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface CaseInstanceRestService { + + public static final String PATH = "/case-instance"; + + @Path("/{id}") + CaseInstanceResource getCaseInstance(@PathParam("id") String caseInstanceId); + + /** + * Exposes the {@link CaseInstanceQuery} interface as a REST service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getCaseInstances(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + /** + * Expects the same parameters as + * {@link CaseInstanceRestService#getCaseInstances(UriInfo, Integer, Integer)} (as a JSON message body) + * and allows for any number of variable checks. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryCaseInstances(CaseInstanceQueryDto query, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getCaseInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryCaseInstancesCount(CaseInstanceQueryDto query); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ConditionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ConditionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..5c0a3cf1ba4158c608a258e4bd74ca2760d0d4be --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ConditionRestService.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.condition.EvaluationConditionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; + +@Produces(MediaType.APPLICATION_JSON) +public interface ConditionRestService { + + public static final String PATH = "/condition"; + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List evaluateCondition(EvaluationConditionDto conditionDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CustomJacksonDateFormatListener.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CustomJacksonDateFormatListener.java new file mode 100644 index 0000000000000000000000000000000000000000..b88099f60151b95556439cb2b32a1ca051b0b991 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/CustomJacksonDateFormatListener.java @@ -0,0 +1,40 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.camunda.bpm.engine.rest.mapper.JacksonConfigurator; + +public class CustomJacksonDateFormatListener implements ServletContextListener { + + public final static String CONTEXT_PARAM_NAME = "org.camunda.bpm.engine.rest.jackson.dateFormat"; + + public void contextInitialized(ServletContextEvent sce) { + String dateFormat = sce.getServletContext().getInitParameter(CONTEXT_PARAM_NAME); + if (dateFormat != null) { + JacksonConfigurator.setDateFormatString(dateFormat); + } + } + + public void contextDestroyed(ServletContextEvent sce) { + // reset to default format + JacksonConfigurator.setDateFormatString(JacksonConfigurator.DEFAULT_DATE_FORMAT); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..ddfc42251df45b19a67af88333cd4323ff25bef4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestService.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionDefinitionDto; +import org.camunda.bpm.engine.rest.sub.repository.DecisionDefinitionResource; + +@Produces(MediaType.APPLICATION_JSON) +public interface DecisionDefinitionRestService { + + public static final String PATH = "/decision-definition"; + + @Path("/{id}") + DecisionDefinitionResource getDecisionDefinitionById(@PathParam("id") String decisionDefinitionId); + + @Path("/key/{key}") + DecisionDefinitionResource getDecisionDefinitionByKey(@PathParam("key") String decisionDefinitionKey); + + @Path("/key/{key}/tenant-id/{tenantId}") + DecisionDefinitionResource getDecisionDefinitionByKeyAndTenantId(@PathParam("key") String decisionDefinitionKey, + @PathParam("tenantId") String tenantId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getDecisionDefinitions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getDecisionDefinitionsCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DecisionRequirementsDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DecisionRequirementsDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..02a925fb6def4d0929d2171b1fab10f7a81c65f1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DecisionRequirementsDefinitionRestService.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionRequirementsDefinitionDto; +import org.camunda.bpm.engine.rest.sub.repository.DecisionRequirementsDefinitionResource; + +@Produces(MediaType.APPLICATION_JSON) +public interface DecisionRequirementsDefinitionRestService { + + public static final String PATH = "/decision-requirements-definition"; + + @Path("/{id}") + DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionById(@PathParam("id") String decisionRequirementsDefinitionId); + + @Path("/key/{key}") + DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKey(@PathParam("key") String decisionRequirementsDefinitionKey); + + @Path("/key/{key}/tenant-id/{tenant-id}") + DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKeyAndTenantId(@PathParam("key") String decisionRequirementsDefinitionKey, + @PathParam("tenant-id") String tenantId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getDecisionRequirementsDefinitions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getDecisionRequirementsDefinitionsCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DeploymentRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DeploymentRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..c17578d0a9a5379ba1fb0c34edcadd29ea5bca2d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/DeploymentRestService.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.DeploymentDto; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData; +import org.camunda.bpm.engine.rest.sub.repository.DeploymentResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; +import java.util.Set; + +@Produces(MediaType.APPLICATION_JSON) +public interface DeploymentRestService { + + public static final String PATH = "/deployment"; + + @Path("/{id}") + DeploymentResource getDeployment(@PathParam("id") String deploymentId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getDeployments(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @POST + @Path("/create") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + DeploymentDto createDeployment(@Context UriInfo uriInfo, MultipartFormData multipartFormData); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getDeploymentsCount(@Context UriInfo uriInfo); + + @GET + @Path("/registered") + @Produces(MediaType.APPLICATION_JSON) + Set getRegisteredDeployments(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/EventSubscriptionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/EventSubscriptionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..a43ca0eab3c4f947146b2d5c5d19fa7521f57b0c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/EventSubscriptionRestService.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.EventSubscriptionDto; +import org.camunda.bpm.engine.runtime.EventSubscriptionQuery; + +@Produces(MediaType.APPLICATION_JSON) +public interface EventSubscriptionRestService { + + public static final String PATH = "/event-subscription"; + + /** + * Exposes the {@link EventSubscriptionQuery} interface as a REST service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getEventSubscriptions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + /** + * Number of event subscriptions + * + * @return + */ + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getEventSubscriptionsCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ExecutionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ExecutionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..35f8182aa76b09801d53d777089150b1713f6505 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ExecutionRestService.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionQueryDto; +import org.camunda.bpm.engine.rest.sub.runtime.ExecutionResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Produces(MediaType.APPLICATION_JSON) +public interface ExecutionRestService { + + public static final String PATH = "/execution"; + + @Path("/{id}") + ExecutionResource getExecution(@PathParam("id") String executionId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getExecutions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + List queryExecutions(ExecutionQueryDto query, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getExecutionsCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + CountResultDto queryExecutionsCount(ExecutionQueryDto query); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ExternalTaskRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ExternalTaskRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..312009d5088548430fae7260f2b4498944b7f7e9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ExternalTaskRestService.java @@ -0,0 +1,102 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.container.AsyncResponse; +import javax.ws.rs.container.Suspended; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskQueryDto; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto; +import org.camunda.bpm.engine.rest.dto.externaltask.SetRetriesForExternalTasksDto; +import org.camunda.bpm.engine.rest.sub.externaltask.ExternalTaskResource; + +/** + * @author Thorben Lindhauer + * + */ +public interface ExternalTaskRestService { + + public static final String PATH = "/external-task"; + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getExternalTasks(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryExternalTasks(ExternalTaskQueryDto query, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getExternalTasksCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryExternalTasksCount(ExternalTaskQueryDto query); + + @POST + @Path("/fetchAndLock") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + void fetchAndLock(FetchExternalTasksExtendedDto dto, @Suspended final AsyncResponse asyncResponse); + + @Path("/{id}") + ExternalTaskResource getExternalTask(@PathParam("id") String externalTaskId); + + @PUT + @Path("/retries") + @Consumes(MediaType.APPLICATION_JSON) + void setRetries(SetRetriesForExternalTasksDto retriesDto); + + @POST + @Path("/retries-async") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setRetriesAsync(SetRetriesForExternalTasksDto retriesDto); + + @GET + @Path("/topic-names") + @Produces(MediaType.APPLICATION_JSON) + List getTopicNames(@QueryParam("withLockedTasks") boolean withLockedTasks, + @QueryParam("withUnlockedTasks") boolean withUnlockedTasks, + @QueryParam("withRetriesLeft") boolean withRetriesLeft); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/FilterRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/FilterRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..5881b4276ad0fc723cefe2cc1da4585b72056262 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/FilterRestService.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.runtime.FilterDto; +import org.camunda.bpm.engine.rest.sub.runtime.FilterResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Produces(MediaType.APPLICATION_JSON) +public interface FilterRestService { + + static final String PATH = "/filter"; + + @Path("/{id}") + FilterResource getFilter(@PathParam("id") String filterId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getFilters(@Context UriInfo uriInfo, @QueryParam("itemCount") Boolean itemCount, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getFiltersCount(@Context UriInfo uriInfo); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + FilterDto createFilter(FilterDto filterDto); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/GroupRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/GroupRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..e9bbd5b8b32f00637144461e1d800de3ba16a3c3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/GroupRestService.java @@ -0,0 +1,82 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.OPTIONS; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.GroupDto; +import org.camunda.bpm.engine.rest.dto.identity.GroupQueryDto; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.rest.sub.identity.GroupResource; + +/** + * @author Daniel Meyer + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface GroupRestService { + + public static final String PATH = "/group"; + + @Path("/{id}") + GroupResource getGroup(@PathParam("id") String id); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List queryGroups(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getGroupCount(@Context UriInfo uriInfo); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryGroups(GroupQueryDto query, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryGroupCount(GroupQueryDto query); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + void createGroup(GroupDto GroupDto); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/IdentityRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/IdentityRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..4d31f97db32a61354ac37cf3a930036f6e977a4f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/IdentityRestService.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.identity.BasicUserCredentialsDto; +import org.camunda.bpm.engine.rest.dto.identity.PasswordPolicyRequestDto; +import org.camunda.bpm.engine.rest.dto.task.GroupInfoDto; +import org.camunda.bpm.engine.rest.security.auth.AuthenticationResult; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Produces(MediaType.APPLICATION_JSON) +public interface IdentityRestService { + + public static final String PATH = "/identity"; + + @GET + @Path("/groups") + @Produces(MediaType.APPLICATION_JSON) + GroupInfoDto getGroupInfo(@QueryParam("userId") String userId); + + @POST + @Path("/verify") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + AuthenticationResult verifyUser(BasicUserCredentialsDto credentialsDto); + + @GET + @Path("/password-policy") + @Produces(MediaType.APPLICATION_JSON) + Response getPasswordPolicy(); + + @POST + @Path("/password-policy") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Response checkPassword(PasswordPolicyRequestDto password); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/IncidentRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/IncidentRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..81d000b49a9ff8cbaf1121079ed49f8fd540aa2f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/IncidentRestService.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.IncidentDto; +import org.camunda.bpm.engine.rest.sub.runtime.IncidentResource; +import org.camunda.bpm.engine.runtime.IncidentQuery; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author Roman Smirnov + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface IncidentRestService { + + public static final String PATH = "/incident"; + + /** + * Exposes the {@link IncidentQuery} interface as a REST service. + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getIncidents(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getIncidentsCount(@Context UriInfo uriInfo); + + @Path("/{id}") + IncidentResource getIncident(@PathParam("id") String incidentId); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/JobDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/JobDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..e68ae792f9796741262d44bd78389b7607685073 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/JobDefinitionRestService.java @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.management.JobDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionQueryDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.sub.management.JobDefinitionResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author roman.smirnov + */ +@Produces(MediaType.APPLICATION_JSON) +public interface JobDefinitionRestService { + + public static final String PATH = "/job-definition"; + + @Path("/{id}") + JobDefinitionResource getJobDefinition(@PathParam("id") String jobDefinitionId); + + /** + * Exposes the {@link JobDefinitionQuery} interface as a REST service. + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getJobDefinitions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryJobDefinitions(JobDefinitionQueryDto queryDto, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getJobDefinitionsCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryJobDefinitionsCount(JobDefinitionQueryDto queryDto); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(JobDefinitionSuspensionStateDto dto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/JobRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/JobRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..40139ef1e027869bdda30ab656868006b011155a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/JobRestService.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.SetJobRetriesDto; +import org.camunda.bpm.engine.rest.sub.runtime.JobResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Produces(MediaType.APPLICATION_JSON) +public interface JobRestService { + + static final String PATH = "/job"; + + @Path("/{id}") + JobResource getJob(@PathParam("id") String jobId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getJobs(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryJobs(JobQueryDto queryDto, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getJobsCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryJobsCount(JobQueryDto queryDto); + + + @POST + @Path("/retries") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setRetries (SetJobRetriesDto setJobRetriesDto); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(JobSuspensionStateDto dto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MessageRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MessageRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..57cce155ccb02501a9a224a3b89473ce16b3bfb8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MessageRestService.java @@ -0,0 +1,36 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.message.CorrelationMessageDto; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +@Produces(MediaType.APPLICATION_JSON) +public interface MessageRestService { + + public static final String PATH = "/message"; + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Response deliverMessage(CorrelationMessageDto messageDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MetricsRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MetricsRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..d73b5255173048627253a9fa273f226dfb71ecfc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MetricsRestService.java @@ -0,0 +1,55 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.metrics.MetricsIntervalResultDto; + +import org.camunda.bpm.engine.rest.sub.metrics.MetricsResource; + +/** + * @author Daniel Meyer + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface MetricsRestService { + + public static final String PATH = "/metrics"; + + @Path("/{name}") + MetricsResource getMetrics(@PathParam("name") String name); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List interval(@Context UriInfo uriInfo); + + @DELETE + @Path("/task-worker") + Response deleteTaskMetrics(@QueryParam("date") String dateString); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MigrationRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MigrationRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..d29d2b9436880f493b324fb4b4ea2a5b79f80672 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/MigrationRestService.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationExecutionDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationPlanDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationPlanGenerationDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationPlanReportDto; + +public interface MigrationRestService { + + String PATH = "/migration"; + + @POST + @Path("/generate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + MigrationPlanDto generateMigrationPlan(MigrationPlanGenerationDto generationDto); + + @POST + @Path("/validate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + MigrationPlanReportDto validateMigrationPlan(MigrationPlanDto migrationPlanDto); + + @POST + @Path("/execute") + @Consumes(MediaType.APPLICATION_JSON) + void executeMigrationPlan(MigrationExecutionDto migrationPlan); + + @POST + @Path("/executeAsync") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto executeMigrationPlanAsync(MigrationExecutionDto migrationPlan); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ModificationRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ModificationRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..22fa6fbfe9871a671da008ff04591402cdd033cd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ModificationRestService.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.ModificationDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; + +@Produces(MediaType.APPLICATION_JSON) +public interface ModificationRestService { + + public static final String PATH = "/modification"; + + @POST + @Path("/execute") + @Consumes(MediaType.APPLICATION_JSON) + void executeModification(ModificationDto modificationExecutionDto); + + @POST + @Path("/executeAsync") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto executeModificationAsync(ModificationDto modificationExecutionDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..502bdda4bde9ecea1198c6de5162937aa98e97da --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestService.java @@ -0,0 +1,105 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.StatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.sub.repository.ProcessDefinitionResource; + +@Produces(MediaType.APPLICATION_JSON) +public interface ProcessDefinitionRestService { + + public static final String APPLICATION_BPMN20_XML = "application/bpmn20+xml"; + public static final MediaType APPLICATION_BPMN20_XML_TYPE = + new MediaType("application", "bpmn20+xml"); + + public static final String PATH = "/process-definition"; + + @Path("/{id}") + ProcessDefinitionResource getProcessDefinitionById(@PathParam("id") String processDefinitionId); + + @Path("/key/{key}") + ProcessDefinitionResource getProcessDefinitionByKey(@PathParam("key") String processDefinitionKey); + + @Path("/key/{key}/tenant-id/{tenantId}") + ProcessDefinitionResource getProcessDefinitionByKeyAndTenantId(@PathParam("key") String processDefinitionKey, + @PathParam("tenantId") String tenantId); + + /** + * Exposes the {@link ProcessDefinitionQuery} interface as a REST service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getProcessDefinitions(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getProcessDefinitionsCount(@Context UriInfo uriInfo); + + @GET + @Path("/statistics") + @Produces(MediaType.APPLICATION_JSON) + List getStatistics(@QueryParam("failedJobs") Boolean includeFailedJobs, + @QueryParam("rootIncidents") Boolean includeRootIncidents, + @QueryParam("incidents") Boolean includeIncidents, + @QueryParam("incidentsForType") String includeIncidentsForType); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(ProcessDefinitionSuspensionStateDto dto); + + @DELETE + @Path("/key/{key}/delete") + void deleteProcessDefinitionsByKey(@PathParam("key") String processDefinitionKey, + @QueryParam("cascade") boolean cascade, + @QueryParam("skipCustomListeners") boolean skipCustomListeners, + @QueryParam("skipIoMappings") boolean skipIoMappings); + + @DELETE + @Path("/key/{key}/tenant-id/{tenantId}/delete") + void deleteProcessDefinitionsByKeyAndTenantId(@PathParam("key") String processDefinitionKey, + @QueryParam("cascade") boolean cascade, + @QueryParam("skipCustomListeners") boolean skipCustomListeners, + @QueryParam("skipIoMappings") boolean skipIoMappings, + @PathParam("tenantId") String tenantId); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ProcessInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ProcessInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..a57894d39cac3d8f7879e6a037539192247c9a16 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/ProcessInstanceRestService.java @@ -0,0 +1,143 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceSuspensionStateAsyncDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.SetJobRetriesByProcessDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.SetVariablesAsyncDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.CorrelationMessageAsyncDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.DeleteProcessInstancesDto; +import org.camunda.bpm.engine.rest.sub.runtime.ProcessInstanceResource; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; + +@Produces(MediaType.APPLICATION_JSON) +public interface ProcessInstanceRestService { + + public static final String PATH = "/process-instance"; + + @Path("/{id}") + ProcessInstanceResource getProcessInstance(@PathParam("id") String processInstanceId); + + /** + * Exposes the {@link ProcessInstanceQuery} interface as a REST service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getProcessInstances(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + /** + * Expects the same parameters as + * {@link ProcessInstanceRestService#getProcessInstances(UriInfo, Integer, Integer)} (as a JSON message body) + * and allows for any number of variable checks. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryProcessInstances(ProcessInstanceQueryDto query, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getProcessInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryProcessInstancesCount(ProcessInstanceQueryDto query); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(ProcessInstanceSuspensionStateDto dto); + + @POST + @Path("/suspended-async") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto updateSuspensionStateAsync(ProcessInstanceSuspensionStateAsyncDto dto); + + @POST + @Path("/delete") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto deleteAsync(DeleteProcessInstancesDto dto); + + @POST + @Path("/delete-historic-query-based") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto deleteAsyncHistoricQueryBased(DeleteProcessInstancesDto dto); + + @POST + @Path("/job-retries") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setRetriesByProcess(SetJobRetriesByProcessDto setJobRetriesDto); + + @POST + @Path("/job-retries-historic-query-based") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setRetriesByProcessHistoricQueryBased(SetJobRetriesByProcessDto setJobRetriesDto); + + @POST + @Path("/variables-async") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setVariablesAsync(SetVariablesAsyncDto setVariablesAsyncDto); + + @POST + @Path("/message-async") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto correlateMessageAsync(CorrelationMessageAsyncDto correlationMessageAsyncDto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/SchemaLogRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/SchemaLogRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..b7f3b2123f0c38eeb236a595c9da6105498caabd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/SchemaLogRestService.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.SchemaLogEntryDto; +import org.camunda.bpm.engine.rest.dto.SchemaLogQueryDto; + +/** + * @author Miklas Boskamp + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface SchemaLogRestService { + + public static final String PATH = "/schema/log"; + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getSchemaLog(@Context Request request, @Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List querySchemaLog(SchemaLogQueryDto dto, @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/SignalRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/SignalRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..d749ff705e9719b89e1c624d14de9833bda84cb7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/SignalRestService.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.SignalDto; + +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + * @author Tassilo Weidner + */ +@Produces(MediaType.APPLICATION_JSON) +public interface SignalRestService { + + String PATH = "/signal"; + + @POST + @Consumes(MediaType.APPLICATION_JSON) + void throwSignal(SignalDto signalDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TaskRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TaskRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..78b2fec5cba3640db4ad2f392e5a1d2d33674701 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TaskRestService.java @@ -0,0 +1,83 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.task.TaskDto; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.sub.task.TaskReportResource; +import org.camunda.bpm.engine.rest.sub.task.TaskResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Produces(MediaType.APPLICATION_JSON) +public interface TaskRestService { + + public static final String PATH = "/task"; + + @Path("/{id}") + TaskResource getTask(@PathParam("id") String id, + @QueryParam("withCommentAttachmentInfo") boolean withCommentAttachmentInfo, + @QueryParam("withTaskVariablesInReturn") boolean withTaskVariablesInReturn, + @QueryParam("withTaskLocalVariablesInReturn") boolean withTaskLocalVariablesInReturn); + + @GET + @Produces({MediaType.APPLICATION_JSON, Hal.APPLICATION_HAL_JSON}) + Object getTasks(@Context Request request, @Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + /** + * Expects the same parameters as {@link TaskRestService#getTasks(UriInfo, Integer, Integer)} (as + * JSON message body) and allows more than one variable check. + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryTasks(TaskQueryDto query, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getTasksCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryTasksCount(TaskQueryDto query); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + void createTask(TaskDto taskDto); + + @Path("/report") + TaskReportResource getTaskReportResource(); + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TelemetryRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TelemetryRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..51ae64d81b943a4b48a438389a58d45d3d936c3c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TelemetryRestService.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.TelemetryConfigurationDto; +import org.camunda.bpm.engine.rest.dto.telemetry.TelemetryDataDto; + +@Produces(MediaType.APPLICATION_JSON) +public interface TelemetryRestService { + + String PATH = "/telemetry"; + + /** + * @deprecated The sending telemetry feature is removed. + * Please remove the endpoint usages as they are no longer needed. + */ + @Deprecated + @POST + @Path("/configuration") + @Consumes(MediaType.APPLICATION_JSON) + void configureTelemetry(TelemetryConfigurationDto dto); + + /** + * @deprecated The sending telemetry feature is removed. + * Please remove the endpoint usages as they are no longer needed. + */ + @Deprecated + @GET + @Path("/configuration") + @Produces(MediaType.APPLICATION_JSON) + TelemetryConfigurationDto getTelemetryConfiguration(); + + @GET + @Path("/data") + @Produces(MediaType.APPLICATION_JSON) + TelemetryDataDto getTelemetryData(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TenantRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TenantRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..8b841a97ccebd8eac1a772882e920bab9362c1b8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/TenantRestService.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.OPTIONS; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.TenantDto; +import org.camunda.bpm.engine.rest.sub.identity.TenantResource; + +@Produces(MediaType.APPLICATION_JSON) +public interface TenantRestService { + + public static final String PATH = "/tenant"; + + @Path("/{id}") + TenantResource getTenant(@PathParam("id") String id); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List queryTenants(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getTenantCount(@Context UriInfo uriInfo); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + void createTenant(TenantDto tenant); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/UserRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/UserRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..9b1584f0f762580be3094536aad90dab0956afbe --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/UserRestService.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.UserDto; +import org.camunda.bpm.engine.rest.dto.identity.UserProfileDto; +import org.camunda.bpm.engine.rest.sub.identity.UserResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author Daniel Meyer + * + */ +@Produces(MediaType.APPLICATION_JSON) +public interface UserRestService { + + public static final String PATH = "/user"; + + @Path("/{id}") + UserResource getUser(@PathParam("id") String id); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List queryUsers(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getUserCount(@Context UriInfo uriInfo); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + void createUser(UserDto userDto); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/VariableInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/VariableInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..6b57b15f31bc153f4514d8633a46964b59257598 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/VariableInstanceRestService.java @@ -0,0 +1,87 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.VariableInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.VariableInstanceQueryDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.runtime.VariableInstanceResource; +import org.camunda.bpm.engine.runtime.VariableInstanceQuery; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author roman.smirnov + */ +@Produces(MediaType.APPLICATION_JSON) +public interface VariableInstanceRestService { + + public static final String PATH = "/variable-instance"; + + @Path("/{id}") + VariableInstanceResource getVariableInstance(@PathParam("id") String id); + + /** + * Exposes the {@link VariableInstanceQuery} interface as a REST service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getVariableInstances(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValues); + + /** + * Expects the same parameters as + * {@link VariableInstanceRestService#getVariableInstances(UriInfo, Integer, Integer)} (as a JSON message body) + * and allows for any number of variable checks. + * + * @param queryDto + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryVariableInstances(VariableInstanceQueryDto queryDto, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValues); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getVariableInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryVariableInstancesCount(VariableInstanceQueryDto queryDto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/cache/Cache.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/cache/Cache.java new file mode 100644 index 0000000000000000000000000000000000000000..1246bd5a66da0bf9e69568dfc3e4b1cbcb1fc143 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/cache/Cache.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.cache; + +public interface Cache { + + /** + * Put a resource into the cache. + * + * @param id the id of the resource + * @param resource the resource to cache + */ + void put(String id, Object resource); + + /** + * Get a resource by id. + * + * @param id the id of the resource + * @return the resource or null if non is found or the resource time to live expired + */ + Object get(String id); + + /** + * Destroy cache. + */ + void destroy(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..01a3de38ba26beef8c4133a1f4dfcbae82c72f14 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractQueryDto.java @@ -0,0 +1,166 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.Direction; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Defines common query operations, such as sorting options and validation. + * Also allows to access its setter methods based on {@link CamundaQueryParam} annotations which is + * used for processing Http query parameters. + * + * @author Thorben Lindhauer + * + */ +public abstract class AbstractQueryDto> extends AbstractSearchQueryDto { + + public static final String SORT_ORDER_ASC_VALUE = "asc"; + public static final String SORT_ORDER_DESC_VALUE = "desc"; + + public static final List VALID_SORT_ORDER_VALUES; + static { + VALID_SORT_ORDER_VALUES = new ArrayList(); + VALID_SORT_ORDER_VALUES.add(SORT_ORDER_ASC_VALUE); + VALID_SORT_ORDER_VALUES.add(SORT_ORDER_DESC_VALUE); + } + + protected String sortBy; + protected String sortOrder; + + protected List sortings; + + protected Map expressions = new HashMap(); + + // required for populating via jackson + public AbstractQueryDto() { + + } + + public AbstractQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + + @CamundaQueryParam("sortBy") + public void setSortBy(String sortBy) { + if (!isValidSortByValue(sortBy)) { + throw new InvalidRequestException(Status.BAD_REQUEST, "sortBy parameter has invalid value: " + sortBy); + } + this.sortBy = sortBy; + } + + @CamundaQueryParam("sortOrder") + public void setSortOrder(String sortOrder) { + if (!VALID_SORT_ORDER_VALUES.contains(sortOrder)) { + throw new InvalidRequestException(Status.BAD_REQUEST, "sortOrder parameter has invalid value: " + sortOrder); + } + this.sortOrder = sortOrder; + } + + public void setSorting(List sorting) { + this.sortings = sorting; + } + + public List getSorting() { + return sortings; + } + + protected abstract boolean isValidSortByValue(String value); + + protected boolean sortOptionsValid() { + return (sortBy != null && sortOrder != null) || (sortBy == null && sortOrder == null); + } + + public T toQuery(ProcessEngine engine) { + T query = createNewQuery(engine); + applyFilters(query); + + if (!sortOptionsValid()) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Only a single sorting parameter specified. sortBy and sortOrder required"); + } + + applySortingOptions(query, engine); + + return query; + } + + protected abstract T createNewQuery(ProcessEngine engine); + + protected abstract void applyFilters(T query); + + protected void applySortingOptions(T query, ProcessEngine engine) { + if (sortBy != null) { + applySortBy(query, sortBy, null, engine); + } + if (sortOrder != null) { + applySortOrder(query, sortOrder); + } + + if (sortings != null) { + for (SortingDto sorting : sortings) { + String sortingOrder = sorting.getSortOrder(); + String sortingBy = sorting.getSortBy(); + + if (sortingBy != null) { + applySortBy(query, sortingBy, sorting.getParameters(), engine); + } + if (sortingOrder != null) { + applySortOrder(query, sortingOrder); + } + } + } + } + + protected abstract void applySortBy(T query, String sortBy, Map parameters, ProcessEngine engine); + + protected void applySortOrder(T query, String sortOrder) { + if (sortOrder != null) { + if (sortOrder.equals(SORT_ORDER_ASC_VALUE)) { + query.asc(); + } else if (sortOrder.equals(SORT_ORDER_DESC_VALUE)) { + query.desc(); + } + } + } + + public static String sortOrderValueForDirection(Direction direction) { + if (Direction.ASCENDING.equals(direction)) { + return SORT_ORDER_ASC_VALUE; + } + else if (Direction.DESCENDING.equals(direction)) { + return SORT_ORDER_DESC_VALUE; + } + else { + throw new RestException("Unknown query sorting direction " + direction); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..df99a30360e89c042c1f8e73f906cf2c69a5ba7a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractReportDto.java @@ -0,0 +1,104 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.history.ReportResult; +import org.camunda.bpm.engine.query.PeriodUnit; +import org.camunda.bpm.engine.query.Report; +import org.camunda.bpm.engine.rest.dto.converter.PeriodUnitConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Roman Smirnov + * @param + * + */ +public abstract class AbstractReportDto extends AbstractSearchQueryDto { + + protected PeriodUnit periodUnit; + protected String reportType; + + public static final String REPORT_TYPE_DURATION = "duration"; + public static final String REPORT_TYPE_COUNT = "count"; + + public static final List VALID_REPORT_TYPE_VALUES; + static { + VALID_REPORT_TYPE_VALUES = new ArrayList(); + VALID_REPORT_TYPE_VALUES.add(REPORT_TYPE_DURATION); + VALID_REPORT_TYPE_VALUES.add(REPORT_TYPE_COUNT); + } + + // required for populating via jackson + public AbstractReportDto() { + } + + public AbstractReportDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + protected PeriodUnit getPeriodUnit() { + return periodUnit; + } + + public String getReportType() { + return reportType; + } + + @CamundaQueryParam("reportType") + public void setReportType(String reportType) { + if (!VALID_REPORT_TYPE_VALUES.contains(reportType)) { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "reportType parameter has invalid value: " + reportType); + } + this.reportType = reportType; + } + + @CamundaQueryParam(value = "periodUnit", converter = PeriodUnitConverter.class) + public void setPeriodUnit(PeriodUnit periodUnit) { + this.periodUnit = periodUnit; + } + + protected List executeReportQuery(T report) { + return report.duration(periodUnit); + } + + public List executeReport(ProcessEngine engine) { + T reportQuery = createNewReportQuery(engine); + applyFilters(reportQuery); + + try { + return executeReportQuery(reportQuery); + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + protected abstract T createNewReportQuery(ProcessEngine engine); + + protected abstract void applyFilters(T reportQuery); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractSearchQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractSearchQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..fd562821d6158b85fcd7572652faf9874c1f3cb6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AbstractSearchQueryDto.java @@ -0,0 +1,133 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.lang.annotation.Annotation; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Map.Entry; + +import org.camunda.bpm.engine.rest.dto.converter.JacksonAwareStringToTypeConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringToTypeConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Roman Smirnov + * + */ +public abstract class AbstractSearchQueryDto { + + protected ObjectMapper objectMapper; + + // required for populating via jackson + public AbstractSearchQueryDto() { + + } + + public AbstractSearchQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + this.objectMapper = objectMapper; + for (Entry> param : queryParameters.entrySet()) { + String key = param.getKey(); + String value = param.getValue().iterator().next(); + this.setValueBasedOnAnnotation(key, value); + } + } + + // note: with Jackson version >= 1.9, it would be better to use @JacksonInject and + // configure the object mapper in the JacksonConfigurator class to be an injectable value. + // then, explicitly calling this method with every query is not necessary any longer + @JsonIgnore + public void setObjectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + /** + * Finds the methods that are annotated with a {@link CamundaQueryParam} with a value that matches the key parameter. + * Before invoking these methods, the annotated {@link StringToTypeConverter} is used to convert the String value to the desired Java type. + * @param key + * @param value + */ + protected void setValueBasedOnAnnotation(String key, String value) { + List matchingMethods = findMatchingAnnotatedMethods(key); + for (Method method : matchingMethods) { + Class> converterClass = findAnnotatedTypeConverter(method); + if (converterClass == null) { + continue; + } + + JacksonAwareStringToTypeConverter converter = null; + try { + converter = converterClass.newInstance(); + converter.setObjectMapper(objectMapper); + Object convertedValue = converter.convertQueryParameterToType(value); + method.invoke(this, convertedValue); + } catch (InstantiationException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, "Server error."); + } catch (IllegalAccessException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, "Server error."); + } catch (InvocationTargetException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Cannot set query parameter '" + key + "' to value '" + value + "'"); + } catch (RestException e) { + throw new InvalidRequestException(e.getStatus(), e, + "Cannot set query parameter '" + key + "' to value '" + value + "': " + e.getMessage()); + } + } + } + + private List findMatchingAnnotatedMethods(String parameterName) { + List result = new ArrayList(); + Method[] methods = this.getClass().getMethods(); + for (int i = 0; i < methods.length; i++) { + Method method = methods[i]; + Annotation[] methodAnnotations = method.getAnnotations(); + + for (int j = 0; j < methodAnnotations.length; j++) { + Annotation annotation = methodAnnotations[j]; + if (annotation instanceof CamundaQueryParam) { + CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation; + if (parameterAnnotation.value().equals(parameterName)) { + result.add(method); + } + } + } + } + return result; + } + + private Class> findAnnotatedTypeConverter(Method method) { + Annotation[] methodAnnotations = method.getAnnotations(); + + for (int j = 0; j < methodAnnotations.length; j++) { + Annotation annotation = methodAnnotations[j]; + if (annotation instanceof CamundaQueryParam) { + CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation; + return parameterAnnotation.converter(); + } + } + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AnnotationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AnnotationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0edf5ec8ae48d69fff55ac002948bac5aff12a90 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AnnotationDto.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +public class AnnotationDto { + + protected String annotation; + + public String getAnnotation() { + return annotation; + } + + public void setAnnotation(String annotation) { + this.annotation = annotation; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AtomLink.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AtomLink.java new file mode 100644 index 0000000000000000000000000000000000000000..031df46b0b747a340cde9338c72fdf1d2cd81188 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AtomLink.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + + +public class AtomLink { + + private String method; + private String href; + private String rel; + + public AtomLink() { + } + + public AtomLink(String rel, String href, String method) { + this.href = href; + this.rel = rel; + this.method = method; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + + public String getRel() { + return rel; + } + + public void setRel(String rel) { + this.rel = rel; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AuthorizationExceptionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AuthorizationExceptionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c126520e730768e63fe88ff9a2004589a29b474b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/AuthorizationExceptionDto.java @@ -0,0 +1,137 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.List; + +import org.camunda.bpm.engine.AuthorizationException; + +/** + *

Dto for {@link AuthorizationException}

+ * + *

The exception contains a list of Missing authorizations. The List is a + * disjunction i.e. a user should have any of the authorization for the engine + * to continue the execution beyond the point where it failed.

+ * + * @author Daniel Meyer + * + */ +public class AuthorizationExceptionDto extends ExceptionDto { + + protected String userId; + protected String resourceName; + protected String resourceId; + protected String permissionName; + protected List missingAuthorizations; + + // transformer ///////////////////////////// + + public static AuthorizationExceptionDto fromException(AuthorizationException e) { + AuthorizationExceptionDto dto = new AuthorizationExceptionDto(); + + dto.setMessage(e.getMessage()); + dto.setType(AuthorizationException.class.getSimpleName()); + + dto.setUserId(e.getUserId()); + dto.setMissingAuthorizations(MissingAuthorizationDto.fromInfo(e.getMissingAuthorizations())); + dto.setPermissionName(e.getViolatedPermissionName()); + dto.setResourceId(e.getResourceId()); + dto.setResourceName(e.getResourceType()); + + return dto; + } + + // getter / setters //////////////////////// + /** + * @return the name of the resource if there + * is only one {@link MissingAuthorizationDto}, {@code null} otherwise + * + * @deprecated Use {@link #getMissingAuthorizations()} to get the name of the resource + * of the {@link MissingAuthorizationDto}(s). This method will be removed in future version. + */ + @Deprecated + public String getResourceName() { + return resourceName; + } + + /** + * @deprecated Use {@link #setMissingAuthorizations(List)}} to set the + * the {@link MissingAuthorizationDto}(s). This method will be removed in future version. + */ + @Deprecated + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + /** + * @return the id of the resource if there + * is only one {@link MissingAuthorizationDto}, {@code null} otherwise + * + * @deprecated Use {@link #getMissingAuthorizations()} to get the id of the resource + * of the {@link MissingAuthorizationDto}(s). This method will be removed in future version. + */ + @Deprecated + public String getResourceId() { + return resourceId; + } + + /** + * @deprecated Use {@link #setMissingAuthorizations(List)}} to set the + * the {@link MissingAuthorizationDto}(s). This method will be removed in future version. + */ + @Deprecated + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + /** + * @return the name of the violated permission if there + * is only one {@link MissingAuthorizationDto}, {@code null} otherwise + * + * @deprecated Use {@link #getMissingAuthorizations()} to get the name of the violated permission + * of the {@link MissingAuthorizationDto}(s). This method will be removed in future version. + */ + @Deprecated + public String getPermissionName() { + return permissionName; + } + + /** + * @deprecated Use {@link #setMissingAuthorizations(List)}} to set the + * the {@link MissingAuthorizationDto}(s). This method will be removed in future version. + */ + @Deprecated + public void setPermissionName(String permissionName) { + this.permissionName = permissionName; + } + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + /** + * @return Disjunctive list of {@link MissingAuthorizationDto} from + * which a user needs to have at least one for the authorization to pass + */ + public List getMissingAuthorizations() { + return missingAuthorizations; + } + public void setMissingAuthorizations(List info) { + this.missingAuthorizations = info; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CamundaQueryParam.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CamundaQueryParam.java new file mode 100644 index 0000000000000000000000000000000000000000..3d2e133391ea092bbbca1ba9e995daac91f24363 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CamundaQueryParam.java @@ -0,0 +1,33 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import org.camunda.bpm.engine.rest.dto.converter.JacksonAwareStringToTypeConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringConverter; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.METHOD) + +public @interface CamundaQueryParam { + public String value(); + public Class> converter() default StringConverter.class; +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ConditionQueryParameterDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ConditionQueryParameterDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bcb487eab916d726030fb04d520f81f6c81f3086 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ConditionQueryParameterDto.java @@ -0,0 +1,102 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.impl.QueryOperator; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * @author roman.smirnov + */ +public class ConditionQueryParameterDto { + + public ConditionQueryParameterDto() { + + } + + public static final String EQUALS_OPERATOR_NAME = "eq"; + public static final String NOT_EQUALS_OPERATOR_NAME = "neq"; + public static final String GREATER_THAN_OPERATOR_NAME = "gt"; + public static final String GREATER_THAN_OR_EQUALS_OPERATOR_NAME = "gteq"; + public static final String LESS_THAN_OPERATOR_NAME = "lt"; + public static final String LESS_THAN_OR_EQUALS_OPERATOR_NAME = "lteq"; + public static final String LIKE_OPERATOR_NAME = "like"; + public static final String NOT_LIKE_OPERATOR_NAME = "notLike"; + + protected static final Map NAME_OPERATOR_MAP = new HashMap<>(); + + static { + NAME_OPERATOR_MAP.put(EQUALS_OPERATOR_NAME, QueryOperator.EQUALS); + NAME_OPERATOR_MAP.put(NOT_EQUALS_OPERATOR_NAME, QueryOperator.NOT_EQUALS); + NAME_OPERATOR_MAP.put(GREATER_THAN_OPERATOR_NAME, QueryOperator.GREATER_THAN); + NAME_OPERATOR_MAP.put(GREATER_THAN_OR_EQUALS_OPERATOR_NAME, QueryOperator.GREATER_THAN_OR_EQUAL); + NAME_OPERATOR_MAP.put(LESS_THAN_OPERATOR_NAME, QueryOperator.LESS_THAN); + NAME_OPERATOR_MAP.put(LESS_THAN_OR_EQUALS_OPERATOR_NAME, QueryOperator.LESS_THAN_OR_EQUAL); + NAME_OPERATOR_MAP.put(LIKE_OPERATOR_NAME, QueryOperator.LIKE); + NAME_OPERATOR_MAP.put(NOT_LIKE_OPERATOR_NAME, QueryOperator.NOT_LIKE); + }; + + protected static final Map OPERATOR_NAME_MAP = new HashMap<>(); + + static { + OPERATOR_NAME_MAP.put(QueryOperator.EQUALS, EQUALS_OPERATOR_NAME); + OPERATOR_NAME_MAP.put(QueryOperator.NOT_EQUALS, NOT_EQUALS_OPERATOR_NAME); + OPERATOR_NAME_MAP.put(QueryOperator.GREATER_THAN, GREATER_THAN_OPERATOR_NAME); + OPERATOR_NAME_MAP.put(QueryOperator.GREATER_THAN_OR_EQUAL, GREATER_THAN_OR_EQUALS_OPERATOR_NAME); + OPERATOR_NAME_MAP.put(QueryOperator.LESS_THAN, LESS_THAN_OPERATOR_NAME); + OPERATOR_NAME_MAP.put(QueryOperator.LESS_THAN_OR_EQUAL, LESS_THAN_OR_EQUALS_OPERATOR_NAME); + OPERATOR_NAME_MAP.put(QueryOperator.LIKE, LIKE_OPERATOR_NAME); + OPERATOR_NAME_MAP.put(QueryOperator.NOT_LIKE, NOT_LIKE_OPERATOR_NAME); + }; + + protected String operator; + protected Object value; + + public String getOperator() { + return operator; + } + public void setOperator(String operator) { + this.operator = operator; + } + public Object resolveValue(ObjectMapper objectMapper) { + if (value instanceof String && objectMapper != null) { + try { + return objectMapper.readValue("\"" + value + "\"", Date.class); + } catch (Exception e) { + // ignore the exception + } + } + + return value; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public static QueryOperator getQueryOperator(String name) { + return NAME_OPERATOR_MAP.get(name); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CountResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CountResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9bcfe30ac15463451c7c1bc59a0d83ef69cd6f46 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CountResultDto.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +public class CountResultDto { + + long count; + + public CountResultDto() { + } + + public CountResultDto(long count) { + this.count = count; + } + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CreateIncidentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CreateIncidentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b09601d7d60ae93500691e5551069d7c4f84b7cd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/CreateIncidentDto.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +public class CreateIncidentDto { + + private String incidentType; + private String configuration; + private String message; + + public String getIncidentType() { + return incidentType; + } + + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + public String getConfiguration() { + return configuration; + } + + public void setConfiguration(String configuration) { + this.configuration = configuration; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/DeleteEngineEntityDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/DeleteEngineEntityDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d13b40b2231e602843df894f1665947dc6f0a35e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/DeleteEngineEntityDto.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +/** + * Used for anything that needs a delete reason. + * @author Thorben Lindhauer + * + */ +public class DeleteEngineEntityDto { + + private String deleteReason; + + public String getDeleteReason() { + return deleteReason; + } + + public void setDeleteReason(String deleteReason) { + this.deleteReason = deleteReason; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ExceptionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ExceptionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d7205f34458f01b3f24ec8b7eb02619026bc401e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ExceptionDto.java @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + + +/** + * + * @author nico.rehwaldt + */ +public class ExceptionDto { + + protected String type; + protected String message; + protected Integer code; + + public ExceptionDto() { + + } + + public String getType() { + return type; + } + + public String getMessage() { + return message; + } + + public static ExceptionDto fromException(Exception e) { + + ExceptionDto dto = new ExceptionDto(); + + dto.type = e.getClass().getSimpleName(); + dto.message = e.getMessage(); + + return dto; + } + + public static ExceptionDto fromException(Throwable e) { + + ExceptionDto dto = new ExceptionDto(); + + dto.type = e.getClass().getSimpleName(); + dto.message = e.getMessage(); + + return dto; + } + + public void setType(String type) { + this.type = type; + } + + public void setMessage(String message) { + this.message = message; + } + + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/HistoryTimeToLiveDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/HistoryTimeToLiveDto.java new file mode 100644 index 0000000000000000000000000000000000000000..be1b1ead0e0e30781f5f9cc89df84694461d4e7f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/HistoryTimeToLiveDto.java @@ -0,0 +1,40 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +/** + * @author Svetlana Dorokhova + */ +public class HistoryTimeToLiveDto { + + private Integer historyTimeToLive; + + public HistoryTimeToLiveDto() { + } + + public HistoryTimeToLiveDto(Integer historyTimeToLive) { + this.historyTimeToLive = historyTimeToLive; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public void setHistoryTimeToLive(Integer historyTimeToLive) { + this.historyTimeToLive = historyTimeToLive; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/LinkableDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/LinkableDto.java new file mode 100644 index 0000000000000000000000000000000000000000..17784dddaf7aaac18a51f2e695d71b67088347be --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/LinkableDto.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +public abstract class LinkableDto { + + protected List links = new ArrayList(); + + public List getLinks() { + return links; + } + + public void addLink(AtomLink link) { + links.add(link); + } + + public void addReflexiveLink(URI linkUri, String method, String relation) { + AtomLink link = generateLink(linkUri, method, relation); + links.add(link); + } + + public AtomLink generateLink(URI linkUri, String method, String relation) { + AtomLink link = new AtomLink(relation, linkUri.toString(), method); + return link; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/MissingAuthorizationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/MissingAuthorizationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..664fa32d9803228b7a654454208dc794a65547b7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/MissingAuthorizationDto.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.camunda.bpm.engine.authorization.MissingAuthorization; + +/** + * *

Dto for {@link MissingAuthorization}

+ * @author Filip Hrisafov + * + */ +public class MissingAuthorizationDto { + + private String permissionName; + private String resourceName; + protected String resourceId; + + // transformer ///////////////////////////// + + public static MissingAuthorizationDto fromInfo(MissingAuthorization info) { + MissingAuthorizationDto dto = new MissingAuthorizationDto(); + + dto.setPermissionName(info.getViolatedPermissionName()); + dto.setResourceId(info.getResourceId()); + dto.setResourceName(info.getResourceType()); + + return dto; + } + + public static List fromInfo(Collection infos) { + List dtos = new ArrayList(); + for (MissingAuthorization info : infos) { + dtos.add(fromInfo(info)); + } + return dtos; + } + + // getter / setters //////////////////////// + public String getPermissionName() { + return permissionName; + } + + public void setPermissionName(String permissionName) { + this.permissionName = permissionName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ModificationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ModificationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9822b044c65a08a9d131727245e3df1cbbb7b8e6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ModificationDto.java @@ -0,0 +1,112 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.modification.ProcessInstanceModificationInstructionDto; +import org.camunda.bpm.engine.runtime.ModificationBuilder; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ModificationDto { + + protected List instructions; + protected List processInstanceIds; + protected ProcessInstanceQueryDto processInstanceQuery; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + protected String processDefinitionId; + protected boolean skipIoMappings; + protected boolean skipCustomListeners; + protected String annotation; + + public List getInstructions() { + return instructions; + } + + public void setInstructions(List instructions) { + this.instructions = instructions; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { + this.processInstanceQuery = processInstanceQuery; + } + + public boolean isSkipIoMappings() { + return skipIoMappings; + } + + public void setSkipIoMappings(boolean skipIoMappings) { + this.skipIoMappings = skipIoMappings; + } + + public boolean isSkipCustomListeners() { + return skipCustomListeners; + } + + public void setSkipCustomListeners(boolean skipCustomListeners) { + this.skipCustomListeners = skipCustomListeners; + } + + public void applyTo(ModificationBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) { + for (ProcessInstanceModificationInstructionDto instruction : instructions) { + + instruction.applyTo(builder, processEngine, objectMapper); + } + + } + + public String getAnnotation() { + return annotation; + } + + public void setAnnotation(String annotation) { + this.annotation = annotation; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ParseExceptionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ParseExceptionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5d83cfc81b9584bb2e7754a5e2d10c4bdf399319 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ParseExceptionDto.java @@ -0,0 +1,72 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.ParseException; +import org.camunda.bpm.engine.Problem; +import org.camunda.bpm.engine.ResourceReport; + +/** + * Dto for {@link ParseException} + * + * The exception contains a list of errors and warning that occurred during + * parsing. + */ +public class ParseExceptionDto extends ExceptionDto { + + protected Map details = new HashMap<>(); + + // transformer ///////////////////////////// + + public static ParseExceptionDto fromException(ParseException exception) { + ParseExceptionDto dto = new ParseExceptionDto(); + + dto.setType(ParseException.class.getSimpleName()); + dto.setMessage(exception.getMessage()); + + for (ResourceReport report : exception.getResorceReports()) { + List errorDtos = new ArrayList<>(); + for (Problem error : report.getErrors()) { + errorDtos.add(ProblemDto.fromProblem(error)); + } + + List warningDtos = new ArrayList<>(); + for (Problem warning : report.getWarnings()) { + warningDtos.add(ProblemDto.fromProblem(warning)); + } + ResourceReportDto resourceReportDto = new ResourceReportDto(errorDtos, warningDtos); + dto.details.put(report.getResourceName(), resourceReportDto); + } + + return dto; + } + + // getter / setters //////////////////////// + + public Map getDetails() { + return details; + } + + public void setDetails(Map details) { + this.details = details; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/PatchVariablesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/PatchVariablesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..3db97e2d84de331cffe1c455b0367823e890ee7c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/PatchVariablesDto.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.List; +import java.util.Map; + +/** + * @author Thorben Lindhauer + */ +public class PatchVariablesDto { + + private Map modifications; + private List deletions; + + public Map getModifications() { + return modifications; + } + public void setModifications(Map modifications) { + this.modifications = modifications; + } + public List getDeletions() { + return deletions; + } + public void setDeletions(List deletions) { + this.deletions = deletions; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ProblemDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ProblemDto.java new file mode 100644 index 0000000000000000000000000000000000000000..cb23ac5a0b743ff82da7c4ae05f6d3f1d5adaf11 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ProblemDto.java @@ -0,0 +1,93 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.List; + +import org.camunda.bpm.engine.Problem; + +/** + * Dto for {@link Problem} + * + * The problem contains a list of element ids and other details for root + * causing the issue. + */ +public class ProblemDto { + + protected String message; + protected int line; + protected int column; + protected String mainElementId; + protected List еlementIds; + + // transformer ///////////////////////////// + + public static ProblemDto fromProblem(Problem problem) { + ProblemDto dto = new ProblemDto(); + + dto.setMessage(problem.getMessage()); + dto.setLine(problem.getLine()); + dto.setColumn(problem.getColumn()); + dto.setMainElementId(problem.getMainElementId()); + dto.setЕlementIds(problem.getElementIds()); + + return dto; + } + + // getter / setters //////////////////////// + + public String getMessage() { + return message; + } + + public void setMessage(String errorMessage) { + this.message = errorMessage; + } + + public int getLine() { + return line; + } + + public void setLine(int line) { + this.line = line; + } + + public int getColumn() { + return column; + } + + public void setColumn(int column) { + this.column = column; + } + + public String getMainElementId() { + return mainElementId; + } + + public void setMainElementId(String mainElementId) { + this.mainElementId = mainElementId; + } + + public List getЕlementIds() { + return еlementIds; + } + + public void setЕlementIds(List elementIds) { + this.еlementIds = elementIds; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ProcessEngineDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ProcessEngineDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e9808e600435becd55b8cda625cd99eb050e707b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ProcessEngineDto.java @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +public class ProcessEngineDto { + + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ResourceOptionsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ResourceOptionsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..54bd6bac7734669a01d13b29a48006914d21ff55 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ResourceOptionsDto.java @@ -0,0 +1,25 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +/** + * @author Daniel Meyer + * + */ +public class ResourceOptionsDto extends LinkableDto { + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ResourceReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ResourceReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f60319e8635da3e92d968828d1ebc5fb9ffb8a3a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/ResourceReportDto.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.List; + +public class ResourceReportDto { + + protected List errors; + protected List warnings; + + public ResourceReportDto(List errors, List warnings) { + this.errors = errors; + this.warnings = warnings; + } + + // getter / setters //////////////////////// + + public List getErrors() { + return errors; + } + + public void setErrors(List errors) { + this.errors = errors; + } + + public List getWarnings() { + return warnings; + } + + public void setWarnings(List warnings) { + this.warnings = warnings; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SchemaLogEntryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SchemaLogEntryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..cb936a48902a73bf073a17d9c1e7f7135459955b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SchemaLogEntryDto.java @@ -0,0 +1,72 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.camunda.bpm.engine.management.SchemaLogEntry; + +/** + * @author Miklas Boskamp + * + */ +public class SchemaLogEntryDto { + + private String id; + private Date timestamp; + private String version; + + public static List fromSchemaLogEntries(List entries) { + List dtos = new ArrayList<>(); + for (SchemaLogEntry entry : entries) { + dtos.add(new SchemaLogEntryDto(entry.getId(), entry.getTimestamp(), entry.getVersion())); + } + return dtos; + } + + public SchemaLogEntryDto(String id, Date timestamp, String version) { + this.id = id; + this.timestamp = timestamp; + this.version = version; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SchemaLogQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SchemaLogQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c670704511367c7387938565305d39bf7ab09737 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SchemaLogQueryDto.java @@ -0,0 +1,84 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.management.SchemaLogQuery; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Miklas Boskamp + * + */ +public class SchemaLogQueryDto extends AbstractQueryDto{ + + private static final String SORT_BY_TIMESTAMP_VALUE = "timestamp"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_TIMESTAMP_VALUE); + } + + String version; + + public SchemaLogQueryDto() { + } + + public SchemaLogQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + public String getVersion() { + return version; + } + + @CamundaQueryParam("version") + public void setVersion(String version) { + this.version = version; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected SchemaLogQuery createNewQuery(ProcessEngine engine) { + return engine.getManagementService().createSchemaLogQuery(); + } + + @Override + protected void applyFilters(SchemaLogQuery query) { + if(this.version != null) { + query.version(this.version); + } + } + + @Override + protected void applySortBy(SchemaLogQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if(sortBy.equals(SORT_BY_TIMESTAMP_VALUE)) { + query.orderByTimestamp(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SignalDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SignalDto.java new file mode 100644 index 0000000000000000000000000000000000000000..dae4884dbd13a6d209dba00a09df9a660a8de1d0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SignalDto.java @@ -0,0 +1,70 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.Map; + +/** + * @author Tassilo Weidner + */ +public class SignalDto { + private String name; + private String executionId; + private Map variables; + private String tenantId; + private boolean withoutTenantId; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getExecutionId() { + return executionId; + } + + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public boolean isWithoutTenantId() { + return withoutTenantId; + } + + public void setWithoutTenantId(boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SortingDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SortingDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2ceaab54b0c54f87b02d68acbf4c539fee91aa71 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SortingDto.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + + +import static com.fasterxml.jackson.annotation.JsonInclude.Include.*; + +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonInclude; + +/** + * @author Thorben Lindhauer + * + */ +public class SortingDto { + + protected String sortBy; + protected String sortOrder; + + @JsonInclude(NON_NULL) + protected Map parameters; + + public String getSortBy() { + return sortBy; + } + + public void setSortBy(String sortBy) { + this.sortBy = sortBy; + } + + public String getSortOrder() { + return sortOrder; + } + + public void setSortOrder(String sortOrder) { + this.sortOrder = sortOrder; + } + + public Map getParameters() { + return parameters; + } + + public void setParameters(Map parameters) { + this.parameters = parameters; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/StatisticsResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/StatisticsResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..3a8594663ad53c6e06d169ff7c677fe970310236 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/StatisticsResultDto.java @@ -0,0 +1,67 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import org.camunda.bpm.engine.rest.dto.repository.ActivityStatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.repository.IncidentStatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionStatisticsResultDto; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +import java.util.List; + +@JsonTypeInfo( + use = JsonTypeInfo.Id.CLASS +) +@JsonSubTypes({ + @JsonSubTypes.Type(value = ActivityStatisticsResultDto.class), + @JsonSubTypes.Type(value = ProcessDefinitionStatisticsResultDto.class) +}) +public abstract class StatisticsResultDto { + + protected String id; + protected Integer instances; + protected Integer failedJobs; + protected List incidents; + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public Integer getInstances() { + return instances; + } + public void setInstances(Integer instances) { + this.instances = instances; + } + public Integer getFailedJobs() { + return failedJobs; + } + public void setFailedJobs(Integer failedJobs) { + this.failedJobs = failedJobs; + } + public List getIncidents() { + return incidents; + } + public void setIncidents(List incidents) { + this.incidents = incidents; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SuspensionStateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SuspensionStateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5ea86dc2e8d98f8ea87ccce69ce1a93bf70c02b4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/SuspensionStateDto.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateBuilder; + +public class SuspensionStateDto { + + private boolean suspended; + + public boolean getSuspended() { + return suspended; + } + + public void setSuspended(boolean suspended) { + this.suspended = suspended; + } + + public static SuspensionStateDto fromState(boolean suspended) { + SuspensionStateDto dto = new SuspensionStateDto(); + dto.suspended = suspended; + return dto; + } + + public void updateSuspensionState(ProcessEngine engine) {} + + public void updateSuspensionState(ProcessEngine engine, String processInstanceId) { + UpdateProcessInstanceSuspensionStateBuilder updateSuspensionStateBuilder = null; + if (processInstanceId != null) { + updateSuspensionStateBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState() + .byProcessInstanceId(processInstanceId); + } else { + String message = "Specify processInstance with processInstanceId"; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + if (getSuspended()) { + updateSuspensionStateBuilder.suspend(); + } else { + updateSuspensionStateBuilder.activate(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/TelemetryConfigurationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/TelemetryConfigurationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..64c83d39444cf64113f97d29a75b64f3f031fb9f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/TelemetryConfigurationDto.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +/** + * @deprecated The sending telemetry data feature is removed. + * Please remove any usages. + */ +@Deprecated +public class TelemetryConfigurationDto { + + protected Boolean enableTelemetry; + + public TelemetryConfigurationDto() { + } + + public TelemetryConfigurationDto(Boolean enableTelemetry) { + this.enableTelemetry = enableTelemetry; + } + + public Boolean isEnableTelemetry() { + return enableTelemetry; + } + + public void setEnableTelemetry(Boolean enableTelemetry) { + this.enableTelemetry = enableTelemetry; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VariableQueryParameterDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VariableQueryParameterDto.java new file mode 100644 index 0000000000000000000000000000000000000000..93bdb0563f70e30fd31057df0989de7565c032ea --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VariableQueryParameterDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import org.camunda.bpm.engine.impl.TaskQueryVariableValue; +import org.camunda.bpm.engine.variable.Variables; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class VariableQueryParameterDto extends ConditionQueryParameterDto { + + public VariableQueryParameterDto() { + + } + + public VariableQueryParameterDto(TaskQueryVariableValue variableValue) { + this.name = variableValue.getName(); + this.operator = OPERATOR_NAME_MAP.get(variableValue.getOperator()); + this.value = variableValue.getValue(); + } + + protected String name; + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + public Object resolveValue(ObjectMapper objectMapper) { + Object value = super.resolveValue(objectMapper); + + if (value != null && Number.class.isAssignableFrom(value.getClass())) { + return Variables.numberValue((Number) value); + } + + return value; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VariableValueDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VariableValueDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b54125eee44888adcf7741cb0d2c586a8932473e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VariableValueDto.java @@ -0,0 +1,270 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import javax.activation.MimeType; +import javax.activation.MimeTypeParseException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData.FormPart; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.impl.type.AbstractValueTypeImpl; +import org.camunda.bpm.engine.variable.type.FileValueType; +import org.camunda.bpm.engine.variable.type.PrimitiveValueType; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.type.ValueTypeResolver; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.SerializableValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * @author Daniel Meyer + * @author Thorben Lindhauer + * + */ +public class VariableValueDto { + + protected String type; + protected Object value; + protected Map valueInfo; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public Map getValueInfo() { + return valueInfo; + } + + public void setValueInfo(Map valueInfo) { + this.valueInfo = valueInfo; + } + + public TypedValue toTypedValue(ProcessEngine processEngine, ObjectMapper objectMapper) { + ValueTypeResolver valueTypeResolver = processEngine.getProcessEngineConfiguration().getValueTypeResolver(); + + if (type == null) { + if (valueInfo != null && valueInfo.get(ValueType.VALUE_INFO_TRANSIENT) instanceof Boolean) { + return Variables.untypedValue(value, (Boolean) valueInfo.get(ValueType.VALUE_INFO_TRANSIENT)); + } + return Variables.untypedValue(value); + } + + ValueType valueType = valueTypeResolver.typeForName(fromRestApiTypeName(type)); + if(valueType == null) { + throw new RestException(Status.BAD_REQUEST, String.format("Unsupported value type '%s'", type)); + } + else { + if(valueType instanceof PrimitiveValueType) { + PrimitiveValueType primitiveValueType = (PrimitiveValueType) valueType; + Class javaType = primitiveValueType.getJavaType(); + Object mappedValue = null; + try { + if(value != null) { + if(javaType.isAssignableFrom(value.getClass())) { + mappedValue = value; + } + else { + // use jackson to map the value to the requested java type + mappedValue = objectMapper.readValue("\""+value+"\"", javaType); + } + } + return valueType.createValue(mappedValue, valueInfo); + } + catch (Exception e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, + String.format("Cannot convert value '%s' of type '%s' to java type %s", value, type, javaType.getName())); + } + } + else if(valueType instanceof SerializableValueType) { + if(value != null && !(value instanceof String)) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Must provide 'null' or String value for value of SerializableValue type '"+type+"'."); + } + return ((SerializableValueType) valueType).createValueFromSerialized((String) value, valueInfo); + } + else if(valueType instanceof FileValueType) { + + if (value instanceof String) { + value = Base64.decodeBase64((String) value); + } + + return valueType.createValue(value, valueInfo); + } else { + return valueType.createValue(value, valueInfo); + } + } + + } + + protected FileValue fileValueWithDecodedString(FileValue fileValue, String value) { + return Variables.fileValue(fileValue.getFilename()) + .file(Base64.decodeBase64(value)) + .mimeType(fileValue.getMimeType()) + .encoding(fileValue.getEncoding()) + .create(); + } + + public static VariableMap toMap(Map variables, ProcessEngine processEngine, ObjectMapper objectMapper) { + if(variables == null) { + return null; + } + + VariableMap result = Variables.createVariables(); + for (Entry variableEntry : variables.entrySet()) { + result.put(variableEntry.getKey(), variableEntry.getValue().toTypedValue(processEngine, objectMapper)); + } + + return result; + } + + public static Map fromMap(VariableMap variables) + { + return fromMap(variables, false); + } + + public static Map fromMap(VariableMap variables, boolean preferSerializedValue) + { + Map result = new HashMap<>(); + for (String variableName : variables.keySet()) { + VariableValueDto valueDto = VariableValueDto.fromTypedValue(variables.getValueTyped(variableName), preferSerializedValue); + result.put(variableName, valueDto); + } + + return result; + } + + public static VariableValueDto fromTypedValue(TypedValue typedValue) { + VariableValueDto dto = new VariableValueDto(); + fromTypedValue(dto, typedValue); + return dto; + } + + public static VariableValueDto fromTypedValue(TypedValue typedValue, boolean preferSerializedValue) { + VariableValueDto dto = new VariableValueDto(); + fromTypedValue(dto, typedValue, preferSerializedValue); + return dto; + } + + public static void fromTypedValue(VariableValueDto dto, TypedValue typedValue) { + fromTypedValue(dto, typedValue, false); + } + + public static void fromTypedValue(VariableValueDto dto, TypedValue typedValue, boolean preferSerializedValue) { + + ValueType type = typedValue.getType(); + if (type != null) { + String typeName = type.getName(); + dto.setType(toRestApiTypeName(typeName)); + dto.setValueInfo(type.getValueInfo(typedValue)); + } + + if(typedValue instanceof SerializableValue) { + SerializableValue serializableValue = (SerializableValue) typedValue; + + if(serializableValue.isDeserialized() && !preferSerializedValue) { + dto.setValue(serializableValue.getValue()); + } + else { + dto.setValue(serializableValue.getValueSerialized()); + } + + } + else if(typedValue instanceof FileValue){ + //do not set the value for FileValues since we don't want to send megabytes over the network without explicit request + } + else { + dto.setValue(typedValue.getValue()); + } + + } + + public static String toRestApiTypeName(String name) { + return name.substring(0, 1).toUpperCase() + name.substring(1); + } + + public static String fromRestApiTypeName(String name) { + return name.substring(0, 1).toLowerCase() + name.substring(1); + } + + public static VariableValueDto fromFormPart(String type, FormPart binaryDataFormPart) { + VariableValueDto dto = new VariableValueDto(); + + dto.type = type; + dto.value = binaryDataFormPart.getBinaryContent(); + + if (ValueType.FILE.getName().equals(fromRestApiTypeName(type))) { + + String contentType = binaryDataFormPart.getContentType(); + if (contentType == null) { + contentType = MediaType.APPLICATION_OCTET_STREAM; + } + + dto.valueInfo = new HashMap<>(); + dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_NAME, binaryDataFormPart.getFileName()); + MimeType mimeType = null; + try { + mimeType = new MimeType(contentType); + } catch (MimeTypeParseException e) { + throw new RestException(Status.BAD_REQUEST, "Invalid mime type given"); + } + + dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_MIME_TYPE, mimeType.getBaseType()); + + String encoding = mimeType.getParameter("encoding"); + if (encoding != null) { + dto.valueInfo.put(FileValueType.VALUE_INFO_FILE_ENCODING, encoding); + } + + String transientString = mimeType.getParameter("transient"); + boolean isTransient = Boolean.parseBoolean(transientString); + if (isTransient) { + dto.valueInfo.put(AbstractValueTypeImpl.VALUE_INFO_TRANSIENT, isTransient); + } + } + + return dto; + + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VersionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VersionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..7d8f62f54d1f9b49cfe3b1c56cc198c11aee1aa3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/VersionDto.java @@ -0,0 +1,34 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto; + +public class VersionDto { + + private String version; + + public VersionDto(String version) { + this.version = version; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationCheckResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationCheckResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..6b043217fd426c30cf8377d93993e5c9c6038b3a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationCheckResultDto.java @@ -0,0 +1,72 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.authorization; + +import org.camunda.bpm.engine.rest.util.ResourceUtil; + +/** + * @author Daniel Meyer + * + */ +public class AuthorizationCheckResultDto { + + protected String permissionName; + protected String resourceName; + protected String resourceId; + + protected Boolean isAuthorized; + + public AuthorizationCheckResultDto() { + } + + public AuthorizationCheckResultDto(boolean userAuthorized, String permissionName, ResourceUtil resource, String resourceId) { + isAuthorized = userAuthorized; + this.permissionName = permissionName; + resourceName = resource.resourceName(); + this.resourceId = resourceId; + } + + public String getPermissionName() { + return permissionName; + } + public void setPermissionName(String permissionName) { + this.permissionName = permissionName; + } + + public Boolean isAuthorized() { + return isAuthorized; + } + + public void setAuthorized(Boolean isAuthorized) { + this.isAuthorized = isAuthorized; + } + + public String getResourceName() { + return resourceName; + } + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceId() { + return resourceId; + } + + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationCreateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationCreateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9869a401ac75a222a0a61f460b0caa0572a78074 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationCreateDto.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.authorization; + +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.impl.util.PermissionConverter; + +/** + * @author Daniel Meyer + * + */ +public class AuthorizationCreateDto { + + protected Integer type; + protected String[] permissions; + protected String userId; + protected String groupId; + protected Integer resourceType; + protected String resourceId; + + // transformers /////////////////////////////////////// + + public static void update(AuthorizationCreateDto dto, Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) { + + dbAuthorization.setGroupId(dto.getGroupId()); + dbAuthorization.setUserId(dto.getUserId()); + dbAuthorization.setResourceType(dto.getResourceType()); + dbAuthorization.setResourceId(dto.getResourceId()); + dbAuthorization.setPermissions(PermissionConverter.getPermissionsForNames(dto.getPermissions(), dto.getResourceType(), engineConfiguration)); + + } + + ////////////////////////////////////////////////////// + + public int getType() { + return type; + } + public void setType(int type) { + this.type = type; + } + public String[] getPermissions() { + return permissions; + } + public void setPermissions(String[] permissions) { + this.permissions = permissions; + } + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + public String getGroupId() { + return groupId; + } + public void setGroupId(String groupId) { + this.groupId = groupId; + } + public Integer getResourceType() { + return resourceType; + } + public void setResourceType(Integer resourceType) { + this.resourceType = resourceType; + } + public String getResourceId() { + return resourceId; + } + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4ec638a1569380c1eccd32e09e45fd32c8ddae81 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationDto.java @@ -0,0 +1,157 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.authorization; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.util.PermissionConverter; + +/** + * @author Daniel Meyer + * + */ +public class AuthorizationDto { + + protected String id; + protected Integer type; + protected String[] permissions; + protected String userId; + protected String groupId; + protected Integer resourceType; + protected String resourceId; + protected Date removalTime; + protected String rootProcessInstanceId; + + // transformers /////////////////////////////////////// + + public static AuthorizationDto fromAuthorization(Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) { + AuthorizationDto authorizationDto = new AuthorizationDto(); + + authorizationDto.setId(dbAuthorization.getId()); + authorizationDto.setType(dbAuthorization.getAuthorizationType()); + + Permission[] dbPermissions = getPermissions(dbAuthorization, engineConfiguration); + authorizationDto.setPermissions(PermissionConverter.getNamesForPermissions(dbAuthorization, dbPermissions)); + + authorizationDto.setUserId(dbAuthorization.getUserId()); + authorizationDto.setGroupId(dbAuthorization.getGroupId()); + authorizationDto.setResourceType(dbAuthorization.getResourceType()); + authorizationDto.setResourceId(dbAuthorization.getResourceId()); + authorizationDto.setRemovalTime(dbAuthorization.getRemovalTime()); + authorizationDto.setRootProcessInstanceId(dbAuthorization.getRootProcessInstanceId()); + + return authorizationDto; + } + + public static void update(AuthorizationDto dto, Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) { + + dbAuthorization.setGroupId(dto.getGroupId()); + dbAuthorization.setUserId(dto.getUserId()); + dbAuthorization.setResourceId(dto.getResourceId()); + + // update optional fields + + if(dto.getResourceType() != null) { + dbAuthorization.setResourceType(dto.getResourceType()); + } + + if(dto.getPermissions() != null) { + dbAuthorization.setPermissions(PermissionConverter.getPermissionsForNames(dto.getPermissions(), dto.getResourceType(), engineConfiguration)); + } + + } + + public static List fromAuthorizationList(List resultList, ProcessEngineConfiguration engineConfiguration) { + ArrayList result = new ArrayList(); + + for (Authorization authorization : resultList) { + result.add(fromAuthorization(authorization, engineConfiguration)); + } + + return result; + } + + ////////////////////////////////////////////////////// + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public int getType() { + return type; + } + public void setType(int type) { + this.type = type; + } + public String[] getPermissions() { + return permissions; + } + public void setPermissions(String[] permissions) { + this.permissions = permissions; + } + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + public String getGroupId() { + return groupId; + } + public void setGroupId(String groupId) { + this.groupId = groupId; + } + public Integer getResourceType() { + return resourceType; + } + public void setResourceType(Integer resourceType) { + this.resourceType = resourceType; + } + public String getResourceId() { + return resourceId; + } + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + public Date getRemovalTime() { + return removalTime; + } + public void setRemovalTime(Date removalTime) { + this.removalTime = removalTime; + } + + private static Permission[] getPermissions(Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) { + int givenResourceType = dbAuthorization.getResourceType(); + Permission[] permissionsByResourceType = ((ProcessEngineConfigurationImpl) engineConfiguration).getPermissionProvider().getPermissionsForResource(givenResourceType); + return dbAuthorization.getPermissions(permissionsByResourceType); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..33bbd6fd06a9b1601dbc2ad4556df3c95e1812d0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/authorization/AuthorizationQueryDto.java @@ -0,0 +1,134 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.authorization; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.authorization.AuthorizationQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * @author Daniel Meyer + */ +public class AuthorizationQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_RESOURCE_TYPE = "resourceType"; + private static final String SORT_BY_RESOURCE_ID = "resourceId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_RESOURCE_TYPE); + VALID_SORT_BY_VALUES.add(SORT_BY_RESOURCE_ID); + } + + protected String id; + protected Integer type; + protected String[] userIdIn; + protected String[] groupIdIn; + protected Integer resourceType; + protected String resourceId; + + public AuthorizationQueryDto() { + + } + + public AuthorizationQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("id") + public void setId(String id) { + this.id = id; + } + + @CamundaQueryParam(value="type", converter = IntegerConverter.class) + public void setType(Integer type) { + this.type = type; + } + + @CamundaQueryParam(value="userIdIn", converter = StringArrayConverter.class) + public void setUserIdIn(String[] userIdIn) { + this.userIdIn = userIdIn; + } + + @CamundaQueryParam(value="groupIdIn", converter = StringArrayConverter.class) + public void setGroupIdIn(String[] groupIdIn) { + this.groupIdIn = groupIdIn; + } + + @CamundaQueryParam(value="resourceType", converter = IntegerConverter.class) + public void setResourceType(int resourceType) { + this.resourceType = resourceType; + } + + @CamundaQueryParam("resourceId") + public void setResourceId(String resourceId) { + this.resourceId = resourceId; + } + + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + protected AuthorizationQuery createNewQuery(ProcessEngine engine) { + return engine.getAuthorizationService().createAuthorizationQuery(); + } + + protected void applyFilters(AuthorizationQuery query) { + + if (id != null) { + query.authorizationId(id); + } + if (type != null) { + query.authorizationType(type); + } + if (userIdIn != null) { + query.userIdIn(userIdIn); + } + if (groupIdIn != null) { + query.groupIdIn(groupIdIn); + } + if (resourceType != null) { + query.resourceType(resourceType); + } + if (resourceId != null) { + query.resourceId(resourceId); + } + } + + @Override + protected void applySortBy(AuthorizationQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_RESOURCE_ID)) { + query.orderByResourceId(); + } else if (sortBy.equals(SORT_BY_RESOURCE_TYPE)) { + query.orderByResourceType(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchDto.java new file mode 100644 index 0000000000000000000000000000000000000000..526f975890887582e91c1596a3116b107439a357 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchDto.java @@ -0,0 +1,123 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.batch; + +import org.camunda.bpm.engine.batch.Batch; + +import java.util.Date; + +public class BatchDto { + + protected String id; + protected String type; + protected int totalJobs; + protected int jobsCreated; + protected int batchJobsPerSeed; + protected int invocationsPerBatchJob; + protected String seedJobDefinitionId; + protected String monitorJobDefinitionId; + protected String batchJobDefinitionId; + protected boolean suspended; + protected String tenantId; + protected String createUserId; + protected Date startTime; + protected Date executionStartTime; + + public String getId() { + return id; + } + + public String getType() { + return type; + } + + public int getTotalJobs() { + return totalJobs; + } + + public int getJobsCreated() { + return jobsCreated; + } + + public int getBatchJobsPerSeed() { + return batchJobsPerSeed; + } + + public int getInvocationsPerBatchJob() { + return invocationsPerBatchJob; + } + + public String getSeedJobDefinitionId() { + return seedJobDefinitionId; + } + + public String getMonitorJobDefinitionId() { + return monitorJobDefinitionId; + } + + public String getBatchJobDefinitionId() { + return batchJobDefinitionId; + } + + public boolean isSuspended() { + return suspended; + } + + public String getTenantId() { + return tenantId; + } + + public String getCreateUserId() { + return createUserId; + } + + public Date getStartTime() { + return startTime; + } + + public void setStartTime(final Date startTime) { + this.startTime = startTime; + } + + public Date getExecutionStartTime() { + return executionStartTime; + } + + public void setExecutionStartTime(final Date executionStartTime) { + this.executionStartTime = executionStartTime; + } + + public static BatchDto fromBatch(Batch batch) { + BatchDto dto = new BatchDto(); + dto.id = batch.getId(); + dto.type = batch.getType(); + dto.totalJobs = batch.getTotalJobs(); + dto.jobsCreated = batch.getJobsCreated(); + dto.batchJobsPerSeed = batch.getBatchJobsPerSeed(); + dto.invocationsPerBatchJob = batch.getInvocationsPerBatchJob(); + dto.seedJobDefinitionId = batch.getSeedJobDefinitionId(); + dto.monitorJobDefinitionId = batch.getMonitorJobDefinitionId(); + dto.batchJobDefinitionId = batch.getBatchJobDefinitionId(); + dto.suspended = batch.isSuspended(); + dto.tenantId = batch.getTenantId(); + dto.createUserId = batch.getCreateUserId(); + dto.startTime = batch.getStartTime(); + dto.executionStartTime = batch.getExecutionStartTime(); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5d67a2d4627384844a8ce8dc6b6ca286e76ec299 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchQueryDto.java @@ -0,0 +1,122 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.batch; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.BatchQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class BatchQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_BATCH_ID_VALUE = "batchId"; + private static final String SORT_BY_TENANT_ID_VALUE = "tenantId"; + + protected String batchId; + protected String type; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean suspended; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_BATCH_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID_VALUE); + } + + public BatchQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("batchId") + public void setBatchId(String batchId) { + this.batchId = batchId; + } + + @CamundaQueryParam("type") + public void setType(String type) { + this.type = type; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value="suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + protected BatchQuery createNewQuery(ProcessEngine engine) { + return engine.getManagementService().createBatchQuery(); + } + + protected void applyFilters(BatchQuery query) { + if (batchId != null) { + query.batchId(batchId); + } + if (type != null) { + query.type(type); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(suspended)) { + query.suspended(); + } + if (FALSE.equals(suspended)) { + query.active(); + } + } + + protected void applySortBy(BatchQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { + query.orderById(); + } + else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchStatisticsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchStatisticsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..78929d4c96ccf24cdbc22696a5beffceb8cbfbcb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchStatisticsDto.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.batch; + +import org.camunda.bpm.engine.batch.BatchStatistics; + +public class BatchStatisticsDto extends BatchDto { + + protected int remainingJobs; + protected int completedJobs; + protected int failedJobs; + + public int getRemainingJobs() { + return remainingJobs; + } + + public int getCompletedJobs() { + return completedJobs; + } + + public int getFailedJobs() { + return failedJobs; + } + + public static BatchStatisticsDto fromBatchStatistics(BatchStatistics batchStatistics) { + BatchStatisticsDto dto = new BatchStatisticsDto(); + dto.id = batchStatistics.getId(); + dto.type = batchStatistics.getType(); + dto.totalJobs = batchStatistics.getTotalJobs(); + dto.jobsCreated = batchStatistics.getJobsCreated(); + dto.batchJobsPerSeed = batchStatistics.getBatchJobsPerSeed(); + dto.invocationsPerBatchJob = batchStatistics.getInvocationsPerBatchJob(); + dto.seedJobDefinitionId = batchStatistics.getSeedJobDefinitionId(); + dto.monitorJobDefinitionId = batchStatistics.getMonitorJobDefinitionId(); + dto.batchJobDefinitionId = batchStatistics.getBatchJobDefinitionId(); + dto.tenantId = batchStatistics.getTenantId(); + dto.createUserId = batchStatistics.getCreateUserId(); + dto.suspended = batchStatistics.isSuspended(); + dto.startTime = batchStatistics.getStartTime(); + dto.executionStartTime = batchStatistics.getExecutionStartTime(); + + dto.remainingJobs = batchStatistics.getRemainingJobs(); + dto.completedJobs = batchStatistics.getCompletedJobs(); + dto.failedJobs = batchStatistics.getFailedJobs(); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchStatisticsQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchStatisticsQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..165fd651b73fa505981001995c17044efaa0f62d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/batch/BatchStatisticsQueryDto.java @@ -0,0 +1,174 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.batch; + +import static java.lang.Boolean.FALSE; +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.BatchStatisticsQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class BatchStatisticsQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_BATCH_ID_VALUE = "batchId"; + private static final String SORT_BY_TENANT_ID_VALUE = "tenantId"; + private static final String SORT_BY_START_TIME_VALUE = "startTime"; + + protected String batchId; + protected String type; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean suspended; + protected String userId; + protected Date startedBefore; + protected Date startedAfter; + protected Boolean withFailures; + protected Boolean withoutFailures; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_BATCH_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_START_TIME_VALUE); + } + + public BatchStatisticsQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("batchId") + public void setBatchId(String batchId) { + this.batchId = batchId; + } + + @CamundaQueryParam("type") + public void setType(String type) { + this.type = type; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value="suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value="createdBy") + public void setCreateUserId(String userId) { + this.userId = userId; + } + + @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) + public void setStartedBefore(Date startedBefore) { + this.startedBefore = startedBefore; + } + + @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) + public void setStartedAfter(Date startedAfter) { + this.startedAfter = startedAfter; + } + + @CamundaQueryParam(value = "withFailures", converter = BooleanConverter.class) + public void setWithFailures(final Boolean withFailures) { + this.withFailures = withFailures; + } + + @CamundaQueryParam(value = "withoutFailures", converter = BooleanConverter.class) + public void setWithoutFailures(final Boolean withoutFailures) { + this.withoutFailures = withoutFailures; + } + + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + protected BatchStatisticsQuery createNewQuery(ProcessEngine engine) { + return engine.getManagementService().createBatchStatisticsQuery(); + } + + protected void applyFilters(BatchStatisticsQuery query) { + if (batchId != null) { + query.batchId(batchId); + } + if (type != null) { + query.type(type); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(suspended)) { + query.suspended(); + } + if (FALSE.equals(suspended)) { + query.active(); + } + if (userId != null) { + query.createdBy(userId); + } + if (startedBefore != null) { + query.startedBefore(startedBefore); + } + if (startedAfter != null) { + query.startedAfter(startedAfter); + } + if (TRUE.equals(withFailures)) { + query.withFailures(); + } + if (TRUE.equals(withoutFailures)) { + query.withoutFailures(); + } + } + + protected void applySortBy(BatchStatisticsQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { + query.orderById(); + } + else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { + query.orderByTenantId(); + } + else if (sortBy.equals(SORT_BY_START_TIME_VALUE)) { + query.orderByStartTime(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/condition/EvaluationConditionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/condition/EvaluationConditionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d109ff5743a86741e8f612af7148b85b9681fa4f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/condition/EvaluationConditionDto.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.condition; + +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +public class EvaluationConditionDto { + private String businessKey; + private Map variables; + private String tenantId; + private boolean withoutTenantId; + private String processDefinitionId; + + public String getBusinessKey() { + return businessKey; + } + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + public Map getVariables() { + return variables; + } + public void setVariables(Map variables) { + this.variables = variables; + } + public String getTenantId() { + return tenantId; + } + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + public boolean isWithoutTenantId() { + return withoutTenantId; + } + public void setWithoutTenantId(boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + public String getProcessDefinitionId() { + return processDefinitionId; + } + public void setProcessDefinitionId(String processInstanceId) { + this.processDefinitionId = processInstanceId; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/BooleanConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/BooleanConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..0c4ee0dbcbf965b97606cc4a7ff0049bb35b92e1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/BooleanConverter.java @@ -0,0 +1,26 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + + +public class BooleanConverter extends JacksonAwareStringToTypeConverter { + + @Override + public Boolean convertQueryParameterToType(String value) { + return mapToType(value, Boolean.class); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/ConditionListConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/ConditionListConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..96dca22b66e884adb03a15caadc39bfb5766e0bf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/ConditionListConverter.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.Response.Status; +import java.util.ArrayList; +import java.util.List; + +public class ConditionListConverter extends JacksonAwareStringToTypeConverter> { + + private static final String EXPRESSION_DELIMITER = ","; + private static final String ATTRIBUTE_DELIMITER = "_"; + + @Override + public List convertQueryParameterToType(String value) { + String[] expressions = value.split(EXPRESSION_DELIMITER); + + List queryConditions = new ArrayList(); + + for (String expression : expressions) { + String[] valueTuple = expression.split(ATTRIBUTE_DELIMITER); + if (valueTuple.length != 2) { + throw new InvalidRequestException(Status.BAD_REQUEST, "condition query parameter has to have format OPERATOR_VALUE."); + } + + ConditionQueryParameterDto queryCondition = new ConditionQueryParameterDto(); + queryCondition.setOperator(valueTuple[0]); + queryCondition.setValue(valueTuple[1]); + + queryConditions.add(queryCondition); + } + + return queryConditions; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/DateConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/DateConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..91947d36f2784e19e8296a39b85623f7b35cec22 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/DateConverter.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.Response; +import java.util.Date; + +public class DateConverter extends JacksonAwareStringToTypeConverter { + + @Override + public Date convertQueryParameterToType(String value) { + if (value != null && (value.startsWith("\"") || value.endsWith("\""))) { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, String + .format("Cannot convert value %s to java type %s because of double quotes", value, + java.util.Date.class.getName())); + } + return mapToType("\"" + value + "\"", Date.class); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/DelegationStateConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/DelegationStateConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..b31f0ebbfa39dc8f021be227edaafcc458da8f27 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/DelegationStateConverter.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.task.DelegationState; + +import javax.ws.rs.core.Response.Status; + +public class DelegationStateConverter extends JacksonAwareStringToTypeConverter { + + @Override + public DelegationState convertQueryParameterToType(String value) { + try { + return DelegationState.valueOf(value.toUpperCase()); + + } catch (IllegalArgumentException e) { + String message = "Valid values for property 'delegationState' are 'PENDING' or 'RESOLVED', but was '"+value+"'"; + throw new InvalidRequestException(Status.BAD_REQUEST, e, message); + + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/IntegerConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/IntegerConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..2f0ab9fc8a33edac38cf868bbd768b02d0bedd9f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/IntegerConverter.java @@ -0,0 +1,25 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +public class IntegerConverter extends JacksonAwareStringToTypeConverter { + + @Override + public Integer convertQueryParameterToType(String value) { + return mapToType(value, Integer.class); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/JacksonAwareStringToTypeConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/JacksonAwareStringToTypeConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..fa1d0769a0af84f9d4e43990acd052a8b89febff --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/JacksonAwareStringToTypeConverter.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.Response.Status; +import java.io.IOException; + +/** + * @author Thorben Lindhauer + */ +public abstract class JacksonAwareStringToTypeConverter implements StringToTypeConverter { + + protected ObjectMapper objectMapper; + + public abstract T convertQueryParameterToType(String value); + + public void setObjectMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + protected T mapToType(String value, Class typeClass) { + try { + return objectMapper.readValue(value, typeClass); + } catch (JsonParseException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, String.format("Cannot convert value %s to java type %s", + value, typeClass.getName())); + } catch (JsonMappingException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, String.format("Cannot convert value %s to java type %s", + value, typeClass.getName())); + } catch (IOException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, String.format("Cannot convert value %s to java type %s", + value, typeClass.getName())); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/LongConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/LongConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..ed1ef9fc9709f317bca7d192a0de69269b63d27d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/LongConverter.java @@ -0,0 +1,25 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +public class LongConverter extends JacksonAwareStringToTypeConverter { + + @Override + public Long convertQueryParameterToType(String value) { + return mapToType(value, Long.class); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/PeriodUnitConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/PeriodUnitConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..428a45f3992ddc52c2277803807856c998497700 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/PeriodUnitConverter.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import org.camunda.bpm.engine.query.PeriodUnit; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.Response.Status; + +/** + * @author Roman Smirnov + * + */ +public class PeriodUnitConverter extends JacksonAwareStringToTypeConverter { + + public PeriodUnit convertQueryParameterToType(String value) { + return mapToEnum(value, PeriodUnit.class); + } + + protected > T mapToEnum(String value, Class type) { + try { + return Enum.valueOf(type, value.toUpperCase()); + } + catch (IllegalArgumentException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, String.format("Cannot convert value %s to java enum type %s", + value, type.getName())); + } + catch (NullPointerException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, String.format("Cannot convert value %s to java enum type %s", + value, type.getName())); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/ReportResultToCsvConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/ReportResultToCsvConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..98b3cda947bd4bdd52378bbc117f896a663c40d9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/ReportResultToCsvConverter.java @@ -0,0 +1,73 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import java.util.List; + +import org.camunda.bpm.engine.history.DurationReportResult; +import org.camunda.bpm.engine.history.ReportResult; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceReportDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.Response.Status; + +/** + * @author Roman Smirnov + * + */ +public class ReportResultToCsvConverter { + + protected static String DELIMITER = ","; + protected static String NEW_LINE_SEPARATOR = "\n"; + + public static String DURATION_HEADER = "PERIOD" + + DELIMITER + "PERIOD_UNIT" + + DELIMITER + "MINIMUM" + + DELIMITER + "MAXIMUM" + + DELIMITER + "AVERAGE"; + + public static String convertReportResult(List reports, String reportType) { + if (HistoricProcessInstanceReportDto.REPORT_TYPE_DURATION.equals(reportType)) { + return convertDurationReportResult(reports); + } + + throw new InvalidRequestException(Status.BAD_REQUEST, "Unkown report type " + reportType); + } + + protected static String convertDurationReportResult(List reports) { + StringBuilder buffer = new StringBuilder(); + + buffer.append(DURATION_HEADER); + + for (ReportResult report : reports) { + DurationReportResult durationReport = (DurationReportResult) report; + buffer.append(NEW_LINE_SEPARATOR); + buffer.append(durationReport.getPeriod()); + buffer.append(DELIMITER); + buffer.append(durationReport.getPeriodUnit().toString()); + buffer.append(DELIMITER); + buffer.append(durationReport.getMinimum()); + buffer.append(DELIMITER); + buffer.append(durationReport.getMaximum()); + buffer.append(DELIMITER); + buffer.append(durationReport.getAverage()); + } + + return buffer.toString(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringArrayConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringArrayConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..f4981b9c73aaff9c0eb2942d4b2aa51672986ba9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringArrayConverter.java @@ -0,0 +1,27 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + + +public class StringArrayConverter extends JacksonAwareStringToTypeConverter { + + @Override + public String[] convertQueryParameterToType(String value) { + return value.split(","); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..d67cc9f0c02dd72dc411c0c22db18c117829417c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringConverter.java @@ -0,0 +1,25 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +public class StringConverter extends JacksonAwareStringToTypeConverter { + + @Override + public String convertQueryParameterToType(String value) { + return value; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringListConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringListConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..ac59760dc52bb92cf1f03155dbf725a872376235 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringListConverter.java @@ -0,0 +1,34 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class StringListConverter extends JacksonAwareStringToTypeConverter> { + + @Override + public List convertQueryParameterToType(String value) { + if (value == null || value.trim().isEmpty()) { + return Collections.emptyList(); + } + else { + return Arrays.asList(value.split(",")); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringSetConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringSetConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..f83b6352aae8c6eedc9bb9736594f5a3827c799d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringSetConverter.java @@ -0,0 +1,29 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class StringSetConverter extends JacksonAwareStringToTypeConverter> { + + @Override + public Set convertQueryParameterToType(String value) { + return new HashSet(Arrays.asList(value.split(","))); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringToTypeConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringToTypeConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..230d59eee2233e659941ad800a2c2a88bb5efcd0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/StringToTypeConverter.java @@ -0,0 +1,28 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +/** + * Implementations are used to convert http parameters from string to java types. + * @author Thorben Lindhauer + * + * @param + */ +public interface StringToTypeConverter { + + T convertQueryParameterToType(String value); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/TaskReportResultToCsvConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/TaskReportResultToCsvConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..e9976ef1ff0e804a8f069cce1492e3f154203160 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/TaskReportResultToCsvConverter.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import org.camunda.bpm.engine.task.TaskCountByCandidateGroupResult; + +import java.util.List; + +/** + * @author Roman Smirnov + * + */ +public class TaskReportResultToCsvConverter { + + protected static String DELIMITER = ","; + protected static String NEW_LINE_SEPARATOR = "\n"; + + public static String CANDIDATE_GROUP_HEADER = "CANDIDATE_GROUP_NAME" + + DELIMITER + + "TASK_COUNT"; + + public static String convertCandidateGroupReportResult(List reports) { + StringBuilder buffer = new StringBuilder(); + + buffer.append(CANDIDATE_GROUP_HEADER); + + for (TaskCountByCandidateGroupResult report : reports) { + buffer.append(NEW_LINE_SEPARATOR); + buffer.append(report.getGroupName()); + buffer.append(DELIMITER); + buffer.append(report.getTaskCount()); + } + + return buffer.toString(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/VariableListConverter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/VariableListConverter.java new file mode 100644 index 0000000000000000000000000000000000000000..8d17c6f1e7abbaddf87cec97a93fe2c4a46707dc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/converter/VariableListConverter.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.converter; + +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.Response.Status; +import java.util.ArrayList; +import java.util.List; + +/** + * Reads a list of {@link VariableQueryParameterDto}s from a single parameter. Expects a given format (see method comments). + * @author Thorben Lindhauer + * + */ +public class VariableListConverter extends + JacksonAwareStringToTypeConverter> { + + private static final String EXPRESSION_DELIMITER = ","; + private static final String ATTRIBUTE_DELIMITER = "_"; + + /** + * Expects a query parameter of multiple variable expressions formatted as KEY_OPERATOR_VALUE, e.g. aVariable_eq_aValue. + * Multiple values are expected to be comma-separated. + */ + @Override + public List convertQueryParameterToType(String value) { + String[] expressions = value.split(EXPRESSION_DELIMITER); + + List queryVariables = new ArrayList(); + + for (String expression : expressions) { + String[] valueTriple = expression.split(ATTRIBUTE_DELIMITER); + if (valueTriple.length != 3) { + throw new InvalidRequestException(Status.BAD_REQUEST, "variable query parameter has to have format KEY_OPERATOR_VALUE."); + } + + VariableQueryParameterDto queryVariable = new VariableQueryParameterDto(); + queryVariable.setName(valueTriple[0]); + queryVariable.setOperator(valueTriple[1]); + queryVariable.setValue(valueTriple[2]); + + queryVariables.add(queryVariable); + } + + return queryVariables; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/dmn/EvaluateDecisionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/dmn/EvaluateDecisionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..8a9f48cc204aecc4089b371603f636595527f4f2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/dmn/EvaluateDecisionDto.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.dmn; + +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +/** + * @author Philipp Ossler + */ +public class EvaluateDecisionDto { + + protected Map variables; + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/CompleteExternalTaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/CompleteExternalTaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..91d08f7a97cdd7ad7d2e4a3ad244a840ac677f5b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/CompleteExternalTaskDto.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +/** + * @author Thorben Lindhauer + * + */ +public class CompleteExternalTaskDto extends HandleExternalTaskDto { + + protected Map variables; + protected Map localVariables; + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public Map getLocalVariables() { + return localVariables; + } + + public void setLocalVariables(Map localVariables) { + this.localVariables = localVariables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExtendLockOnExternalTaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExtendLockOnExternalTaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..58af32384a4256abcf6dc2fa91f6559c5842c8eb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExtendLockOnExternalTaskDto.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +public class ExtendLockOnExternalTaskDto extends HandleExternalTaskDto { + + protected long newDuration; + + public long getNewDuration() { + return newDuration; + } + + public void setNewDuration(long newDuration) { + this.newDuration = newDuration; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskBpmnError.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskBpmnError.java new file mode 100644 index 0000000000000000000000000000000000000000..8e16d8783b1952f941a5a368b9c41bb52536ccfb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskBpmnError.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import org.camunda.bpm.engine.rest.dto.task.TaskBpmnErrorDto; + +/** + * + * @author Christopher Zell + */ +public class ExternalTaskBpmnError extends TaskBpmnErrorDto { + + protected String workerId; + + public String getWorkerId() { + return workerId; + } + + public void setWorkerId(String workerId) { + this.workerId = workerId; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9c762c79331257b592b24df08db3ba80621d7b18 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskDto.java @@ -0,0 +1,129 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import java.util.Date; + +import org.camunda.bpm.engine.externaltask.ExternalTask; + +/** + * @author Thorben Lindhauer + * + */ +public class ExternalTaskDto { + + protected String activityId; + protected String activityInstanceId; + protected String errorMessage; + protected String executionId; + protected String id; + protected Date lockExpirationTime; + private Date createTime; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processDefinitionVersionTag; + protected String processInstanceId; + protected Integer retries; + protected boolean suspended; + protected String workerId; + protected String topicName; + protected String tenantId; + protected long priority; + protected String businessKey; + + public String getActivityId() { + return activityId; + } + public String getActivityInstanceId() { + return activityInstanceId; + } + public String getErrorMessage() { + return errorMessage; + } + public String getExecutionId() { + return executionId; + } + public String getId() { + return id; + } + public Date getLockExpirationTime() { + return lockExpirationTime; + } + public Date getCreateTime() { + return createTime; + } + public String getProcessDefinitionId() { + return processDefinitionId; + } + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + public String getProcessDefinitionVersionTag() { + return processDefinitionVersionTag; + } + public String getProcessInstanceId() { + return processInstanceId; + } + public Integer getRetries() { + return retries; + } + public boolean isSuspended() { + return suspended; + } + public String getWorkerId() { + return workerId; + } + public String getTopicName() { + return topicName; + } + public String getTenantId() { + return tenantId; + } + + public long getPriority() { + return priority; + } + + public String getBusinessKey() { + return businessKey; + } + + public static ExternalTaskDto fromExternalTask(ExternalTask task) { + ExternalTaskDto dto = new ExternalTaskDto(); + dto.activityId = task.getActivityId(); + dto.activityInstanceId = task.getActivityInstanceId(); + dto.errorMessage = task.getErrorMessage(); + dto.executionId = task.getExecutionId(); + dto.id = task.getId(); + dto.lockExpirationTime = task.getLockExpirationTime(); + dto.createTime = task.getCreateTime(); + dto.processDefinitionId = task.getProcessDefinitionId(); + dto.processDefinitionKey = task.getProcessDefinitionKey(); + dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag(); + dto.processInstanceId = task.getProcessInstanceId(); + dto.retries = task.getRetries(); + dto.suspended = task.isSuspended(); + dto.topicName = task.getTopicName(); + dto.workerId = task.getWorkerId(); + dto.tenantId = task.getTenantId(); + dto.priority = task.getPriority(); + dto.businessKey = task.getBusinessKey(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskFailureDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskFailureDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5fa94cc63295fc09e40752d545638d5d6908b023 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskFailureDto.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +/** + * @author Thorben Lindhauer + * @author Askar Akhmerov + */ +public class ExternalTaskFailureDto extends HandleExternalTaskDto { + + //short error description + protected String errorMessage; + //full stack trace or error information + protected String errorDetails; + protected long retryTimeout; + protected int retries; + protected Map variables; + protected Map localVariables; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public long getRetryTimeout() { + return retryTimeout; + } + + public void setRetryTimeout(long retryTimeout) { + this.retryTimeout = retryTimeout; + } + + public int getRetries() { + return retries; + } + + public void setRetries(int retries) { + this.retries = retries; + } + + public String getErrorDetails() { + return errorDetails; + } + + public void setErrorDetails(String errorDetails) { + this.errorDetails = errorDetails; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public Map getLocalVariables() { + return localVariables; + } + + public void setLocalVariables(Map localVariables) { + this.localVariables = localVariables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d0c80a3bae462da8a3398b9f3295948251bc3163 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/ExternalTaskQueryDto.java @@ -0,0 +1,362 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.externaltask.ExternalTaskQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.*; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +/** + * @author Thorben Lindhauer + * + */ +public class ExternalTaskQueryDto extends AbstractQueryDto { + + public static final Map> SORT_METHODS_BY_FIELD = Map.of( + "id", ExternalTaskQuery::orderById, + "lockExpirationTime", ExternalTaskQuery::orderByLockExpirationTime, + "processInstanceId", ExternalTaskQuery::orderByProcessInstanceId, + "processDefinitionId", ExternalTaskQuery::orderByProcessDefinitionId, + "processDefinitionKey", ExternalTaskQuery::orderByProcessDefinitionKey, + "tenantId", ExternalTaskQuery::orderByTenantId, + "taskPriority", ExternalTaskQuery::orderByPriority, + "createTime", ExternalTaskQuery::orderByCreateTime + ); + + protected String externalTaskId; + protected Set externalTaskIds; + protected String activityId; + protected List activityIdIn; + protected Date lockExpirationBefore; + protected Date lockExpirationAfter; + protected String topicName; + protected Boolean locked; + protected Boolean notLocked; + protected String executionId; + protected String processInstanceId; + protected List processInstanceIdIn; + protected String processDefinitionKey; + protected String[] processDefinitionKeyIn; + protected String processDefinitionId; + protected String processDefinitionName; + protected String processDefinitionNameLike; + protected Boolean active; + protected Boolean suspended; + protected Boolean withRetriesLeft; + protected Boolean noRetriesLeft; + protected String workerId; + protected List tenantIds; + protected Long priorityHigherThanOrEquals; + protected Long priorityLowerThanOrEquals; + protected Boolean variableNamesIgnoreCase; + protected Boolean variableValuesIgnoreCase; + + private List processVariables; + + public ExternalTaskQueryDto() { + } + + public ExternalTaskQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("externalTaskId") + public void setExternalTaskId(String externalTaskId) { + this.externalTaskId = externalTaskId; + } + + @CamundaQueryParam(value = "externalTaskIdIn", converter = StringSetConverter.class) + public void setExternalTaskIdIn(Set externalTaskIds) { + this.externalTaskIds = externalTaskIds; + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + @CamundaQueryParam(value = "activityIdIn", converter = StringListConverter.class) + public void setActivityIdIn(List activityIdIn) { + this.activityIdIn = activityIdIn; + } + + @CamundaQueryParam(value = "lockExpirationBefore", converter = DateConverter.class) + public void setLockExpirationBefore(Date lockExpirationBefore) { + this.lockExpirationBefore = lockExpirationBefore; + } + + @CamundaQueryParam(value = "lockExpirationAfter", converter = DateConverter.class) + public void setLockExpirationAfter(Date lockExpirationAfter) { + this.lockExpirationAfter = lockExpirationAfter; + } + + @CamundaQueryParam("topicName") + public void setTopicName(String topicName) { + this.topicName = topicName; + } + + @CamundaQueryParam(value = "locked", converter = BooleanConverter.class) + public void setLocked(Boolean locked) { + this.locked = locked; + } + + @CamundaQueryParam(value = "notLocked", converter = BooleanConverter.class) + public void setNotLocked(Boolean notLocked) { + this.notLocked = notLocked; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam(value="processInstanceIdIn", converter = StringListConverter.class) + public void setProcessInstanceIdIn(List processInstanceIdIn) { + this.processInstanceIdIn = processInstanceIdIn; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringArrayConverter.class) + public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) { + this.processDefinitionKeyIn = processDefinitionKeyIn; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionName") + public void setProcessDefinitionName(String processDefinitionName) { + this.processDefinitionName = processDefinitionName; + } + + @CamundaQueryParam("processDefinitionNameLike") + public void setProcessDefinitionNameLike(String processDefinitionNameLike) { + this.processDefinitionNameLike = processDefinitionNameLike; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value = "withRetriesLeft", converter = BooleanConverter.class) + public void setWithRetriesLeft(Boolean withRetriesLeft) { + this.withRetriesLeft = withRetriesLeft; + } + + @CamundaQueryParam(value = "noRetriesLeft", converter = BooleanConverter.class) + public void setNoRetriesLeft(Boolean noRetriesLeft) { + this.noRetriesLeft = noRetriesLeft; + } + + @CamundaQueryParam("workerId") + public void setWorkerId(String workerId) { + this.workerId = workerId; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + @CamundaQueryParam(value="priorityHigherThanOrEquals", converter = LongConverter.class) + public void setPriorityHigherThanOrEquals(Long priorityHigherThanOrEquals) { + this.priorityHigherThanOrEquals = priorityHigherThanOrEquals; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesCaseInsensitive) { + this.variableNamesIgnoreCase = variableNamesCaseInsensitive; + } + + @CamundaQueryParam(value ="variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesCaseInsensitive) { + this.variableValuesIgnoreCase = variableValuesCaseInsensitive; + } + + @CamundaQueryParam(value = "processVariables", converter = VariableListConverter.class) + public void setProcessVariables(List processVariables) { + this.processVariables = processVariables; + } + + @CamundaQueryParam(value="priorityLowerThanOrEquals", converter = LongConverter.class) + public void setPriorityLowerThanOrEquals(Long priorityLowerThanOrEquals) { + this.priorityLowerThanOrEquals = priorityLowerThanOrEquals; + } + + @Override + protected boolean isValidSortByValue(String value) { + return SORT_METHODS_BY_FIELD.containsKey(value); + } + + @Override + protected ExternalTaskQuery createNewQuery(ProcessEngine engine) { + return engine.getExternalTaskService().createExternalTaskQuery(); + } + + @Override + protected void applyFilters(ExternalTaskQuery query) { + if (externalTaskId != null) { + query.externalTaskId(externalTaskId); + } + if (externalTaskIds != null && !externalTaskIds.isEmpty()) { + query.externalTaskIdIn(externalTaskIds); + } + if (activityId != null) { + query.activityId(activityId); + } + if (activityIdIn != null && !activityIdIn.isEmpty()) { + query.activityIdIn(activityIdIn.toArray(new String[0])); + } + if (lockExpirationBefore != null) { + query.lockExpirationBefore(lockExpirationBefore); + } + if (lockExpirationAfter != null) { + query.lockExpirationAfter(lockExpirationAfter); + } + if (topicName != null) { + query.topicName(topicName); + } + if (locked != null && locked) { + query.locked(); + } + if (notLocked != null && notLocked) { + query.notLocked(); + } + if (executionId != null) { + query.executionId(executionId); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (processInstanceIdIn != null && !processInstanceIdIn.isEmpty()) { + query.processInstanceIdIn(processInstanceIdIn.toArray(new String[0])); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) { + query.processDefinitionKeyIn(processDefinitionKeyIn); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionName != null) { + query.processDefinitionName(processDefinitionName); + } + if (processDefinitionNameLike != null) { + query.processDefinitionNameLike(processDefinitionNameLike); + } + if (active != null && active) { + query.active(); + } + if (suspended != null && suspended) { + query.suspended(); + } + if (priorityHigherThanOrEquals != null) { + query.priorityHigherThanOrEquals(priorityHigherThanOrEquals); + } + if (priorityLowerThanOrEquals != null) { + query.priorityLowerThanOrEquals(priorityLowerThanOrEquals); + } + if (withRetriesLeft != null && withRetriesLeft) { + query.withRetriesLeft(); + } + if (noRetriesLeft != null && noRetriesLeft) { + query.noRetriesLeft(); + } + if(variableValuesIgnoreCase != null && variableValuesIgnoreCase) { + query.matchVariableValuesIgnoreCase(); + } + if(variableNamesIgnoreCase != null && variableNamesIgnoreCase) { + query.matchVariableNamesIgnoreCase(); + } + if (processVariables != null) { + for (VariableQueryParameterDto variableQueryParam : processVariables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.processVariableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.processVariableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.processVariableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.processVariableValueGreaterThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.processVariableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.processVariableValueLessThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.processVariableValueLike(variableName, String.valueOf(variableValue)); + } else if (op.equals(VariableQueryParameterDto.NOT_LIKE_OPERATOR_NAME)) { + query.processVariableValueNotLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Invalid process variable comparator specified: " + op); + } + } + } + if (workerId != null) { + query.workerId(workerId); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[0])); + } + } + + @Override + protected void applySortBy(ExternalTaskQuery query, String sortBy, Map parameters, ProcessEngine engine) { + var sortByMethod = SORT_METHODS_BY_FIELD.get(sortBy); + + if (sortByMethod != null) { + sortByMethod.accept(query); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/FetchExternalTasksDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/FetchExternalTasksDto.java new file mode 100644 index 0000000000000000000000000000000000000000..293a60fdb276f8b4500c11f0eb5526ed79ad5c29 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/FetchExternalTasksDto.java @@ -0,0 +1,340 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import static java.lang.Boolean.TRUE; +import static javax.ws.rs.core.Response.Status.BAD_REQUEST; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.externaltask.ExternalTaskQueryTopicBuilder; +import org.camunda.bpm.engine.externaltask.FetchAndLockBuilder; +import org.camunda.bpm.engine.impl.util.CollectionUtil; +import org.camunda.bpm.engine.rest.dto.SortingDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +/** + * @author Thorben Lindhauer + * + */ +public class FetchExternalTasksDto { + + protected int maxTasks; + protected String workerId; + protected boolean usePriority = false; + protected List topics; + protected boolean includeExtensionProperties = false; + + protected List sorting; + + public int getMaxTasks() { + return maxTasks; + } + + public void setMaxTasks(int maxTasks) { + this.maxTasks = maxTasks; + } + + public String getWorkerId() { + return workerId; + } + + public void setWorkerId(String workerId) { + this.workerId = workerId; + } + + public List getTopics() { + return topics; + } + + public void setTopics(List topics) { + this.topics = topics; + } + + public boolean isUsePriority() { + return usePriority; + } + + public void setUsePriority(boolean usePriority) { + this.usePriority = usePriority; + } + + public void setSorting(List sorting) { + this.sorting = sorting; + } + + public List getSorting() { + return this.sorting; + } + + public boolean isIncludeExtensionProperties() { + return includeExtensionProperties; + } + + public void setIncludeExtensionProperties(boolean includeExtensionProperties) { + this.includeExtensionProperties = includeExtensionProperties; + } + + public static class FetchExternalTaskTopicDto { + protected String topicName; + protected String businessKey; + protected String processDefinitionId; + protected String[] processDefinitionIdIn; + protected String processDefinitionKey; + protected String[] processDefinitionKeyIn; + protected String processDefinitionVersionTag; + protected long lockDuration; + protected List variables; + protected HashMap processVariables; + protected boolean deserializeValues = false; + protected boolean localVariables = false; + protected boolean includeExtensionProperties = false; + + protected boolean withoutTenantId; + protected String[] tenantIdIn; + + public String getTopicName() { + return topicName; + } + public void setTopicName(String topicName) { + this.topicName = topicName; + } + public String getBusinessKey() { + return businessKey; + } + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + public String getProcessDefinitionId() { + return processDefinitionId; + } + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + public String[] getProcessDefinitionIdIn() { + return processDefinitionIdIn; + } + public void setProcessDefinitionIdIn(String[] processDefinitionIds) { + this.processDefinitionIdIn = processDefinitionIds; + } + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + public String[] getProcessDefinitionKeyIn() { + return processDefinitionKeyIn; + } + public void setProcessDefinitionKeyIn(String[] processDefinitionKeys) { + this.processDefinitionKeyIn = processDefinitionKeys; + } + public String getProcessDefinitionVersionTag() { + return processDefinitionVersionTag; + } + public void setProcessDefinitionVersionTag(String processDefinitionVersionTag) { + this.processDefinitionVersionTag = processDefinitionVersionTag; + } + public long getLockDuration() { + return lockDuration; + } + public void setLockDuration(long lockDuration) { + this.lockDuration = lockDuration; + } + public List getVariables() { + return variables; + } + public void setVariables(List variables) { + this.variables = variables; + } + public HashMap getProcessVariables() { + return processVariables; + } + public void setProcessVariables(HashMap processVariables) { + this.processVariables = processVariables; + } + public boolean isDeserializeValues() { + return deserializeValues; + } + public void setDeserializeValues(boolean deserializeValues) { + this.deserializeValues = deserializeValues; + } + public boolean isLocalVariables() { + return localVariables; + } + public void setLocalVariables(boolean localVariables) { + this.localVariables = localVariables; + } + public boolean isWithoutTenantId() { + return withoutTenantId; + } + public void setWithoutTenantId(boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + public String[] getTenantIdIn() { + return tenantIdIn; + } + public void setTenantIdIn(String[] tenantIdIn) { + this.tenantIdIn = tenantIdIn; + } + public boolean isIncludeExtensionProperties() { + return includeExtensionProperties; + } + public void setIncludeExtensionProperties(boolean includeExtensionProperties) { + this.includeExtensionProperties = includeExtensionProperties; + } + } + + public ExternalTaskQueryTopicBuilder buildQuery(ProcessEngine processEngine) { + FetchAndLockBuilder fetchAndLockBuilder = getBuilder(processEngine); + + return configureTopics(fetchAndLockBuilder); + } + + protected ExternalTaskQueryTopicBuilder configureTopics(FetchAndLockBuilder builder) { + ExternalTaskQueryTopicBuilder topicBuilder = builder.subscribe(); + + if (CollectionUtil.isEmpty(topics)) { + return topicBuilder; + } + + topics.forEach(topic -> { + topicBuilder.topic(topic.getTopicName(), topic.getLockDuration()); + + if (topic.getBusinessKey() != null) { + topicBuilder.businessKey(topic.getBusinessKey()); + } + + if (topic.getProcessDefinitionId() != null) { + topicBuilder.processDefinitionId(topic.getProcessDefinitionId()); + } + + if (topic.getProcessDefinitionIdIn() != null) { + topicBuilder.processDefinitionIdIn(topic.getProcessDefinitionIdIn()); + } + + if (topic.getProcessDefinitionKey() != null) { + topicBuilder.processDefinitionKey(topic.getProcessDefinitionKey()); + } + + if (topic.getProcessDefinitionKeyIn() != null) { + topicBuilder.processDefinitionKeyIn(topic.getProcessDefinitionKeyIn()); + } + + if (topic.getVariables() != null) { + topicBuilder.variables(topic.getVariables()); + } + + if (topic.getProcessVariables() != null) { + topicBuilder.processInstanceVariableEquals(topic.getProcessVariables()); + } + + if (topic.isDeserializeValues()) { + topicBuilder.enableCustomObjectDeserialization(); + } + + if (topic.isLocalVariables()) { + topicBuilder.localVariables(); + } + + if (TRUE.equals(topic.isWithoutTenantId())) { + topicBuilder.withoutTenantId(); + } + + if (topic.getTenantIdIn() != null) { + topicBuilder.tenantIdIn(topic.getTenantIdIn()); + } + + if(topic.getProcessDefinitionVersionTag() != null) { + topicBuilder.processDefinitionVersionTag(topic.getProcessDefinitionVersionTag()); + } + + if(topic.isIncludeExtensionProperties()) { + topicBuilder.includeExtensionProperties(); + } + }); + + return topicBuilder; + } + + protected FetchAndLockBuilder getBuilder(ProcessEngine engine) { + ExternalTaskService service = engine.getExternalTaskService(); + + FetchAndLockBuilder builder = service.fetchAndLock() + .workerId(workerId) + .maxTasks(maxTasks) + .usePriority(usePriority); + + SortMapper mapper = new SortMapper(sorting, builder); + + return mapper.getBuilderWithSortConfigs(); + } + + /** + * Encapsulates the mapping of sorting configurations (field, order) to the respective methods builder config methods + * and applies them. + *

+ * To achieve that, maps are used internally to map fields and orders to the corresponding builder method. + */ + static class SortMapper { + + protected static Map> FIELD_MAPPINGS = Map.of( + "createTime", FetchAndLockBuilder::orderByCreateTime + ); + + protected static Map> ORDER_MAPPINGS = Map.of( + "asc", FetchAndLockBuilder::asc, + "desc", FetchAndLockBuilder::desc + ); + + protected final List sorting; + protected final FetchAndLockBuilder builder; + + protected SortMapper(List sorting, FetchAndLockBuilder builder) { + this.sorting = (sorting == null) ? Collections.emptyList() : sorting; + this.builder = builder; + } + + /** + * Applies the sorting field mappings to the builder and returns it. + */ + protected FetchAndLockBuilder getBuilderWithSortConfigs() { + for (SortingDto dto : sorting) { + String sortBy = dto.getSortBy(); + configureFieldOrBadRequest(sortBy, "sortBy", FIELD_MAPPINGS); + + String sortOrder = dto.getSortOrder(); + if (sortOrder != null) { + configureFieldOrBadRequest(sortOrder, "sortOrder", ORDER_MAPPINGS); + } + } + return builder; + } + + protected void configureFieldOrBadRequest(String key, String parameterName, Map> fieldMappings) { + if (!fieldMappings.containsKey(key)) { + throw new InvalidRequestException(BAD_REQUEST, "Cannot set query " + parameterName + " parameter to value " + key); + } + fieldMappings.get(key).accept(builder); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/FetchExternalTasksExtendedDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/FetchExternalTasksExtendedDto.java new file mode 100644 index 0000000000000000000000000000000000000000..07d18ee0a8445a6f80eec316c94af2221591e059 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/FetchExternalTasksExtendedDto.java @@ -0,0 +1,40 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +/** + * @author Tassilo Weidner + */ +public class FetchExternalTasksExtendedDto extends FetchExternalTasksDto { + + protected Long asyncResponseTimeout = null; + + public void setAsyncResponseTimeout(Long asyncResponseTimeout) { + this.asyncResponseTimeout = asyncResponseTimeout; + } + + public Long getAsyncResponseTimeout() { + return asyncResponseTimeout; + } + + @Override + public String toString() { + return "FetchExternalTasksExtendedDto [asyncResponseTimeout=" + asyncResponseTimeout + ", maxTasks=" + maxTasks + ", workerId=" + workerId + + ", usePriority=" + usePriority + ", topics=" + topics + "]"; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/HandleExternalTaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/HandleExternalTaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..47c7a6f3f0fec9bdb748e85423dbc7d2c9a7b3fd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/HandleExternalTaskDto.java @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +/** + * Base DTO class for Worker-related External Task operations. + * Contains the workerId property. + * + * Used in: + *

    + *
  • {@link LockExternalTaskDto}
  • + *
  • {@link ExtendLockOnExternalTaskDto}
  • + *
  • {@link ExternalTaskFailureDto}
  • + *
  • {@link CompleteExternalTaskDto}
  • + *
+ * + * Note: the {@link ExternalTaskBpmnError} class doesn't extend this class. Any adjustments made here + * should be mirrored in that class as well. + */ +public class HandleExternalTaskDto { + + protected String workerId; + + public String getWorkerId() { + return workerId; + } + + public void setWorkerId(String workerId) { + this.workerId = workerId; + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/LockExternalTaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/LockExternalTaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b4077dfd8b3f359ff3f76a1f522437797f16f275 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/LockExternalTaskDto.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +public class LockExternalTaskDto extends HandleExternalTaskDto { + + protected long lockDuration; + + public long getLockDuration() { + return lockDuration; + } + + public void setLockDuration(long lockDuration) { + this.lockDuration = lockDuration; + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/LockedExternalTaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/LockedExternalTaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..09ff2b6f5706efddfdc3828ae2e241decf0bc91f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/LockedExternalTaskDto.java @@ -0,0 +1,183 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +/** + * @author Thorben Lindhauer + * @author Askar Akhmerov + */ +public class LockedExternalTaskDto { + + protected String activityId; + protected String activityInstanceId; + protected String errorMessage; + protected String errorDetails; + protected String executionId; + protected String id; + protected Date lockExpirationTime; + private Date createTime; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processDefinitionVersionTag; + protected String processInstanceId; + protected Integer retries; + protected boolean suspended; + protected String workerId; + protected String topicName; + protected String tenantId; + protected Map variables; + protected long priority; + protected String businessKey; + protected Map extensionProperties; + + public String getActivityId() { + return activityId; + } + public String getActivityInstanceId() { + return activityInstanceId; + } + public String getErrorMessage() { + return errorMessage; + } + public String getExecutionId() { + return executionId; + } + public String getId() { + return id; + } + public Date getLockExpirationTime() { + return lockExpirationTime; + } + public Date getCreateTime () { + return createTime; + } + public String getProcessDefinitionId() { + return processDefinitionId; + } + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + public String getProcessDefinitionVersionTag() { + return processDefinitionVersionTag; + } + public String getProcessInstanceId() { + return processInstanceId; + } + public Integer getRetries() { + return retries; + } + public boolean isSuspended() { + return suspended; + } + public String getWorkerId() { + return workerId; + } + public String getTopicName() { + return topicName; + } + public String getTenantId() { + return tenantId; + } + public Map getVariables() { + return variables; + } + + public long getPriority() { + return priority; + } + + public String getErrorDetails() { + return errorDetails; + } + + public String getBusinessKey() { + return businessKey; + } + + public Map getExtensionProperties(){ + return extensionProperties; + } + + public static LockedExternalTaskDto fromLockedExternalTask(LockedExternalTask task) { + LockedExternalTaskDto dto = new LockedExternalTaskDto(); + dto.activityId = task.getActivityId(); + dto.activityInstanceId = task.getActivityInstanceId(); + dto.errorMessage = task.getErrorMessage(); + dto.errorDetails = task.getErrorDetails(); + dto.executionId = task.getExecutionId(); + dto.id = task.getId(); + dto.lockExpirationTime = task.getLockExpirationTime(); + dto.createTime = task.getCreateTime(); + dto.processDefinitionId = task.getProcessDefinitionId(); + dto.processDefinitionKey = task.getProcessDefinitionKey(); + dto.processDefinitionVersionTag = task.getProcessDefinitionVersionTag(); + dto.processInstanceId = task.getProcessInstanceId(); + dto.retries = task.getRetries(); + dto.topicName = task.getTopicName(); + dto.workerId = task.getWorkerId(); + dto.tenantId = task.getTenantId(); + dto.variables = VariableValueDto.fromMap(task.getVariables()); + dto.priority = task.getPriority(); + dto.businessKey = task.getBusinessKey(); + dto.extensionProperties = task.getExtensionProperties(); + + return dto; + } + + public static List fromLockedExternalTasks(List tasks) { + List dtos = new ArrayList<>(); + + for (LockedExternalTask task : tasks) { + dtos.add(LockedExternalTaskDto.fromLockedExternalTask(task)); + } + + return dtos; + } + @Override + public String toString() { + return + "LockedExternalTaskDto [activityId=" + activityId + + ", activityInstanceId=" + activityInstanceId + + ", errorMessage=" + errorMessage + + ", errorDetails=" + errorDetails + + ", executionId=" + executionId + + ", id=" + id + + ", lockExpirationTime=" + lockExpirationTime + + ", createTime=" + createTime + + ", processDefinitionId=" + processDefinitionId + + ", processDefinitionKey=" + processDefinitionKey + + ", processDefinitionVersionTag=" + processDefinitionVersionTag + + ", processInstanceId=" + processInstanceId + + ", retries=" + retries + + ", suspended=" + suspended + + ", workerId=" + workerId + + ", topicName=" + topicName + + ", tenantId=" + tenantId + + ", variables=" + variables + + ", priority=" + priority + + ", businessKey=" + businessKey + "]"; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/SetRetriesForExternalTasksDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/SetRetriesForExternalTasksDto.java new file mode 100644 index 0000000000000000000000000000000000000000..718f916db3f060a2ce3401abbbbe5459e6dda411 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/externaltask/SetRetriesForExternalTasksDto.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.externaltask; + +import java.util.List; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; + +public class SetRetriesForExternalTasksDto { + + protected List externalTaskIds; + protected List processInstanceIds; + + protected ExternalTaskQueryDto externalTaskQuery; + protected ProcessInstanceQueryDto processInstanceQuery; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + + protected Integer retries; + + public List getExternalTaskIds() { + return externalTaskIds; + } + + public void setExternalTaskIds(List externalTaskIds) { + this.externalTaskIds = externalTaskIds; + } + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ExternalTaskQueryDto getExternalTaskQuery() { + return externalTaskQuery; + } + + public void setExternalTaskQuery(ExternalTaskQueryDto externalTaskQuery) { + this.externalTaskQuery = externalTaskQuery; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQueryDto) { + this.processInstanceQuery = processInstanceQueryDto; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto) { + this.historicProcessInstanceQuery = historicProcessInstanceQueryDto; + } + + public Integer getRetries() { + return retries; + } + + public void setRetries(Integer retries) { + this.retries = retries; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricCaseInstanceReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricCaseInstanceReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..beb37090f2f4c0b1bf8b43314ccc4e400efc1000 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricCaseInstanceReportDto.java @@ -0,0 +1,119 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricCaseInstanceReport; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CleanableHistoricCaseInstanceReportDto extends AbstractQueryDto { + + protected String[] caseDefinitionIdIn; + protected String[] caseDefinitionKeyIn; + protected String[] tenantIdIn; + protected Boolean withoutTenantId; + protected Boolean compact; + + protected static final String SORT_BY_FINISHED_VALUE = "finished"; + + public static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_FINISHED_VALUE); + } + + public CleanableHistoricCaseInstanceReportDto() { + } + + public CleanableHistoricCaseInstanceReportDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam(value = "caseDefinitionIdIn", converter = StringArrayConverter.class) + public void setCaseDefinitionIdIn(String[] caseDefinitionIdIn) { + this.caseDefinitionIdIn = caseDefinitionIdIn; + } + + @CamundaQueryParam(value = "caseDefinitionKeyIn", converter = StringArrayConverter.class) + public void setCaseDefinitionKeyIn(String[] caseDefinitionKeyIn) { + this.caseDefinitionKeyIn = caseDefinitionKeyIn; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class) + public void setTenantIdIn(String[] tenantIdIn) { + this.tenantIdIn = tenantIdIn; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "compact", converter = BooleanConverter.class) + public void setCompact(Boolean compact) { + this.compact = compact; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected CleanableHistoricCaseInstanceReport createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createCleanableHistoricCaseInstanceReport(); + } + + @Override + protected void applyFilters(CleanableHistoricCaseInstanceReport query) { + if (caseDefinitionIdIn != null && caseDefinitionIdIn.length > 0) { + query.caseDefinitionIdIn(caseDefinitionIdIn); + } + if (caseDefinitionKeyIn != null && caseDefinitionKeyIn.length > 0) { + query.caseDefinitionKeyIn(caseDefinitionKeyIn); + } + if (Boolean.TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (tenantIdIn != null && tenantIdIn.length > 0) { + query.tenantIdIn(tenantIdIn); + } + if (Boolean.TRUE.equals(compact)) { + query.compact(); + } + + } + + @Override + protected void applySortBy(CleanableHistoricCaseInstanceReport query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { + query.orderByFinished(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricCaseInstanceReportResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricCaseInstanceReportResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..547592b71b8175717b46617d2c1e1dc47e70a3ac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricCaseInstanceReportResultDto.java @@ -0,0 +1,118 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.history.CleanableHistoricCaseInstanceReportResult; + +public class CleanableHistoricCaseInstanceReportResultDto implements Serializable { + + private static final long serialVersionUID = 1L; + + protected String caseDefinitionId; + protected String caseDefinitionKey; + protected String caseDefinitionName; + protected int caseDefinitionVersion; + protected Integer historyTimeToLive; + protected long finishedCaseInstanceCount; + protected long cleanableCaseInstanceCount; + protected String tenantId; + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public void setCaseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + } + + public String getCaseDefinitionName() { + return caseDefinitionName; + } + + public void setCaseDefinitionName(String caseDefinitionName) { + this.caseDefinitionName = caseDefinitionName; + } + + public int getCaseDefinitionVersion() { + return caseDefinitionVersion; + } + + public void setCaseDefinitionVersion(int caseDefinitionVersion) { + this.caseDefinitionVersion = caseDefinitionVersion; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public void setHistoryTimeToLive(Integer historyTimeToLive) { + this.historyTimeToLive = historyTimeToLive; + } + + public long getFinishedCaseInstanceCount() { + return finishedCaseInstanceCount; + } + + public void setFinishedCaseInstanceCount(long finishedCaseInstanceCount) { + this.finishedCaseInstanceCount = finishedCaseInstanceCount; + } + + public long getCleanableCaseInstanceCount() { + return cleanableCaseInstanceCount; + } + + public void setCleanableCaseInstanceCount(long cleanableCaseInstanceCount) { + this.cleanableCaseInstanceCount = cleanableCaseInstanceCount; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public static List convert(List reportResult) { + List dtos = new ArrayList(); + for (CleanableHistoricCaseInstanceReportResult current : reportResult) { + CleanableHistoricCaseInstanceReportResultDto dto = new CleanableHistoricCaseInstanceReportResultDto(); + dto.setCaseDefinitionId(current.getCaseDefinitionId()); + dto.setCaseDefinitionKey(current.getCaseDefinitionKey()); + dto.setCaseDefinitionName(current.getCaseDefinitionName()); + dto.setCaseDefinitionVersion(current.getCaseDefinitionVersion()); + dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); + dto.setFinishedCaseInstanceCount(current.getFinishedCaseInstanceCount()); + dto.setCleanableCaseInstanceCount(current.getCleanableCaseInstanceCount()); + dto.setTenantId(current.getTenantId()); + dtos.add(dto); + } + return dtos; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricDecisionInstanceReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricDecisionInstanceReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d9b0085b34f604913a1408e3a5e490d023a03100 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricDecisionInstanceReportDto.java @@ -0,0 +1,118 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricDecisionInstanceReport; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CleanableHistoricDecisionInstanceReportDto extends AbstractQueryDto{ + + protected String[] decisionDefinitionIdIn; + protected String[] decisionDefinitionKeyIn; + protected String[] tenantIdIn; + protected Boolean withoutTenantId; + protected Boolean compact; + + protected static final String SORT_BY_FINISHED_VALUE = "finished"; + + public static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_FINISHED_VALUE); + } + + public CleanableHistoricDecisionInstanceReportDto() { + } + + public CleanableHistoricDecisionInstanceReportDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam(value = "decisionDefinitionIdIn", converter = StringArrayConverter.class) + public void setDecisionDefinitionIdIn(String[] decisionDefinitionIdIn) { + this.decisionDefinitionIdIn = decisionDefinitionIdIn; + } + + @CamundaQueryParam(value = "decisionDefinitionKeyIn", converter = StringArrayConverter.class) + public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) { + this.decisionDefinitionKeyIn = decisionDefinitionKeyIn; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class) + public void setTenantIdIn(String[] tenantIdIn) { + this.tenantIdIn = tenantIdIn; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "compact", converter = BooleanConverter.class) + public void setCompact(Boolean compact) { + this.compact = compact; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected CleanableHistoricDecisionInstanceReport createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createCleanableHistoricDecisionInstanceReport(); + } + + @Override + protected void applyFilters(CleanableHistoricDecisionInstanceReport query) { + if (decisionDefinitionIdIn != null && decisionDefinitionIdIn.length > 0) { + query.decisionDefinitionIdIn(decisionDefinitionIdIn); + } + if (decisionDefinitionKeyIn != null && decisionDefinitionKeyIn.length > 0) { + query.decisionDefinitionKeyIn(decisionDefinitionKeyIn); + } + if (Boolean.TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (tenantIdIn != null && tenantIdIn.length > 0) { + query.tenantIdIn(tenantIdIn); + } + if (Boolean.TRUE.equals(compact)) { + query.compact(); + } + } + + @Override + protected void applySortBy(CleanableHistoricDecisionInstanceReport query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { + query.orderByFinished(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricDecisionInstanceReportResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricDecisionInstanceReportResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..981588185849c370dffc1bc1394953e209e3ed6f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricDecisionInstanceReportResultDto.java @@ -0,0 +1,118 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.history.CleanableHistoricDecisionInstanceReportResult; + +public class CleanableHistoricDecisionInstanceReportResultDto implements Serializable { + + private static final long serialVersionUID = 1L; + + protected String decisionDefinitionId; + protected String decisionDefinitionKey; + protected String decisionDefinitionName; + protected int decisionDefinitionVersion; + protected Integer historyTimeToLive; + protected long finishedDecisionInstanceCount; + protected long cleanableDecisionInstanceCount; + protected String tenantId; + + public String getDecisionDefinitionId() { + return decisionDefinitionId; + } + + public void setDecisionDefinitionId(String decisionDefinitionId) { + this.decisionDefinitionId = decisionDefinitionId; + } + + public String getDecisionDefinitionKey() { + return decisionDefinitionKey; + } + + public void setDecisionDefinitionKey(String decisionDefinitionKey) { + this.decisionDefinitionKey = decisionDefinitionKey; + } + + public String getDecisionDefinitionName() { + return decisionDefinitionName; + } + + public void setDecisionDefinitionName(String decisionDefinitionName) { + this.decisionDefinitionName = decisionDefinitionName; + } + + public int getDecisionDefinitionVersion() { + return decisionDefinitionVersion; + } + + public void setDecisionDefinitionVersion(int decisionDefinitionVersion) { + this.decisionDefinitionVersion = decisionDefinitionVersion; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public void setHistoryTimeToLive(Integer historyTimeToLive) { + this.historyTimeToLive = historyTimeToLive; + } + + public long getFinishedDecisionInstanceCount() { + return finishedDecisionInstanceCount; + } + + public void setFinishedDecisionInstanceCount(long finishedDecisionInstanceCount) { + this.finishedDecisionInstanceCount = finishedDecisionInstanceCount; + } + + public long getCleanableDecisionInstanceCount() { + return cleanableDecisionInstanceCount; + } + + public void setCleanableDecisionInstanceCount(long cleanableDecisionInstanceCount) { + this.cleanableDecisionInstanceCount = cleanableDecisionInstanceCount; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public static List convert(List reportResult) { + List dtos = new ArrayList(); + for (CleanableHistoricDecisionInstanceReportResult current : reportResult) { + CleanableHistoricDecisionInstanceReportResultDto dto = new CleanableHistoricDecisionInstanceReportResultDto(); + dto.setDecisionDefinitionId(current.getDecisionDefinitionId()); + dto.setDecisionDefinitionKey(current.getDecisionDefinitionKey()); + dto.setDecisionDefinitionName(current.getDecisionDefinitionName()); + dto.setDecisionDefinitionVersion(current.getDecisionDefinitionVersion()); + dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); + dto.setFinishedDecisionInstanceCount(current.getFinishedDecisionInstanceCount()); + dto.setCleanableDecisionInstanceCount(current.getCleanableDecisionInstanceCount()); + dto.setTenantId(current.getTenantId()); + dtos.add(dto); + } + return dtos; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricProcessInstanceReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricProcessInstanceReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ccc260c1668ed629c6b9ccaed2176074dd09ea0a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricProcessInstanceReportDto.java @@ -0,0 +1,119 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReport; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CleanableHistoricProcessInstanceReportDto extends AbstractQueryDto { + + protected String[] processDefinitionIdIn; + protected String[] processDefinitionKeyIn; + protected String[] tenantIdIn; + protected Boolean withoutTenantId; + protected Boolean compact; + + protected static final String SORT_BY_FINISHED_VALUE = "finished"; + + public static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_FINISHED_VALUE); + } + + public CleanableHistoricProcessInstanceReportDto() { + } + + public CleanableHistoricProcessInstanceReportDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam(value = "processDefinitionIdIn", converter = StringArrayConverter.class) + public void setProcessDefinitionIdIn(String[] processDefinitionIdIn) { + this.processDefinitionIdIn = processDefinitionIdIn; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringArrayConverter.class) + public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) { + this.processDefinitionKeyIn = processDefinitionKeyIn; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class) + public void setTenantIdIn(String[] tenantIdIn) { + this.tenantIdIn = tenantIdIn; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "compact", converter = BooleanConverter.class) + public void setCompact(Boolean compact) { + this.compact = compact; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected CleanableHistoricProcessInstanceReport createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createCleanableHistoricProcessInstanceReport(); + } + + @Override + protected void applyFilters(CleanableHistoricProcessInstanceReport query) { + if (processDefinitionIdIn != null && processDefinitionIdIn.length > 0) { + query.processDefinitionIdIn(processDefinitionIdIn); + } + if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) { + query.processDefinitionKeyIn(processDefinitionKeyIn); + } + if (Boolean.TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (tenantIdIn != null && tenantIdIn.length > 0) { + query.tenantIdIn(tenantIdIn); + } + if (Boolean.TRUE.equals(compact)) { + query.compact(); + } + + } + + @Override + protected void applySortBy(CleanableHistoricProcessInstanceReport query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { + query.orderByFinished(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricProcessInstanceReportResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricProcessInstanceReportResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f854e8016ffe3e52b5fa9af3e15748f9fbdfbd48 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/CleanableHistoricProcessInstanceReportResultDto.java @@ -0,0 +1,125 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReport; +import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReportResult; + +public class CleanableHistoricProcessInstanceReportResultDto { + + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processDefinitionName; + protected int processDefinitionVersion; + protected Integer historyTimeToLive; + protected long finishedProcessInstanceCount; + protected long cleanableProcessInstanceCount; + protected String tenantId; + + public CleanableHistoricProcessInstanceReportResultDto() { + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + public void setProcessDefinitionName(String processDefinitionName) { + this.processDefinitionName = processDefinitionName; + } + + public void setProcessDefinitionVersion(int processDefinitionVersion) { + this.processDefinitionVersion = processDefinitionVersion; + } + + public void setHistoryTimeToLive(Integer historyTimeToLive) { + this.historyTimeToLive = historyTimeToLive; + } + + public void setFinishedProcessInstanceCount(long finishedProcessInstanceCount) { + this.finishedProcessInstanceCount = finishedProcessInstanceCount; + } + + public void setCleanableProcessInstanceCount(long cleanableProcessInstanceCount) { + this.cleanableProcessInstanceCount = cleanableProcessInstanceCount; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionName() { + return processDefinitionName; + } + + public int getProcessDefinitionVersion() { + return processDefinitionVersion; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public Long getFinishedProcessInstanceCount() { + return finishedProcessInstanceCount; + } + + public Long getCleanableProcessInstanceCount() { + return cleanableProcessInstanceCount; + } + + public String getTenantId() { + return tenantId; + } + + protected CleanableHistoricProcessInstanceReport createNewReportQuery(ProcessEngine engine) { + return engine.getHistoryService().createCleanableHistoricProcessInstanceReport(); + } + + public static List convert(List reportResult) { + List dtos = new ArrayList(); + for (CleanableHistoricProcessInstanceReportResult current : reportResult) { + CleanableHistoricProcessInstanceReportResultDto dto = new CleanableHistoricProcessInstanceReportResultDto(); + dto.setProcessDefinitionId(current.getProcessDefinitionId()); + dto.setProcessDefinitionKey(current.getProcessDefinitionKey()); + dto.setProcessDefinitionName(current.getProcessDefinitionName()); + dto.setProcessDefinitionVersion(current.getProcessDefinitionVersion()); + dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); + dto.setFinishedProcessInstanceCount(current.getFinishedProcessInstanceCount()); + dto.setCleanableProcessInstanceCount(current.getCleanableProcessInstanceCount()); + dto.setTenantId(current.getTenantId()); + dtos.add(dto); + } + return dtos; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/DeleteHistoricProcessInstancesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/DeleteHistoricProcessInstancesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..96e44c173efb0e116bd76992d80f71ae4799883c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/DeleteHistoricProcessInstancesDto.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.List; + +/** + * @author Askar Akhmerov + */ +public class DeleteHistoricProcessInstancesDto { + + protected List historicProcessInstanceIds; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + protected String deleteReason; + protected boolean failIfNotExists = true; + + public List getHistoricProcessInstanceIds() { + return historicProcessInstanceIds; + } + + public void setHistoricProcessInstanceIds(List historicProcessInstanceIds) { + this.historicProcessInstanceIds = historicProcessInstanceIds; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } + + public String getDeleteReason() { + return deleteReason; + } + + public void setDeleteReason(String deleteReason) { + this.deleteReason = deleteReason; + } + + public boolean isFailIfNotExists() { + return failIfNotExists; + } + + public void setFailIfNotExists(boolean failIfNotExists) { + this.failIfNotExists = failIfNotExists; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/DurationReportResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/DurationReportResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..91f53793d01608cb57904c5250892533eee67c7e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/DurationReportResultDto.java @@ -0,0 +1,56 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.DurationReportResult; + +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * @author Roman Smirnov + * + */ +@JsonTypeName("durationReportResult") +public class DurationReportResultDto extends ReportResultDto { + + protected long minimum; + protected long maximum; + protected long average; + + public long getMinimum() { + return minimum; + } + + public long getMaximum() { + return maximum; + } + + public long getAverage() { + return average; + } + + public static DurationReportResultDto fromDurationReportResult(DurationReportResult durationReport) { + DurationReportResultDto dto = new DurationReportResultDto(); + + dto.minimum = durationReport.getMinimum(); + dto.maximum = durationReport.getMaximum(); + dto.average = durationReport.getAverage(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0763472904d67e5284b2f8ae0ca457e20d562b49 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityInstanceDto.java @@ -0,0 +1,156 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricActivityInstance; + +public class HistoricActivityInstanceDto { + + private String id; + private String parentActivityInstanceId; + private String activityId; + private String activityName; + private String activityType; + private String processDefinitionKey; + private String processDefinitionId; + private String processInstanceId; + private String executionId; + private String taskId; + private String calledProcessInstanceId; + private String calledCaseInstanceId; + private String assignee; + private Date startTime; + private Date endTime; + private Long durationInMillis; + private Boolean canceled; + private Boolean completeScope; + private String tenantId; + private Date removalTime; + private String rootProcessInstanceId; + + public String getId() { + return id; + } + + public String getParentActivityInstanceId() { + return parentActivityInstanceId; + } + + public String getActivityId() { + return activityId; + } + + public String getActivityName() { + return activityName; + } + + public String getActivityType() { + return activityType; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getTaskId() { + return taskId; + } + + public String getCalledProcessInstanceId() { + return calledProcessInstanceId; + } + + public String getCalledCaseInstanceId() { + return calledCaseInstanceId; + } + + public String getAssignee() { + return assignee; + } + + public Date getStartTime() { + return startTime; + } + + public Date getEndTime() { + return endTime; + } + + public Long getDurationInMillis() { + return durationInMillis; + } + + public Boolean getCanceled() { + return canceled; + } + + public Boolean getCompleteScope() { + return completeScope; + } + + public String getTenantId() { + return tenantId; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public static void fromHistoricActivityInstance(HistoricActivityInstanceDto dto, + HistoricActivityInstance historicActivityInstance) { + + dto.id = historicActivityInstance.getId(); + dto.parentActivityInstanceId = historicActivityInstance.getParentActivityInstanceId(); + dto.activityId = historicActivityInstance.getActivityId(); + dto.activityName = historicActivityInstance.getActivityName(); + dto.activityType = historicActivityInstance.getActivityType(); + dto.processDefinitionKey = historicActivityInstance.getProcessDefinitionKey(); + dto.processDefinitionId = historicActivityInstance.getProcessDefinitionId(); + dto.processInstanceId = historicActivityInstance.getProcessInstanceId(); + dto.executionId = historicActivityInstance.getExecutionId(); + dto.taskId = historicActivityInstance.getTaskId(); + dto.calledProcessInstanceId = historicActivityInstance.getCalledProcessInstanceId(); + dto.calledCaseInstanceId = historicActivityInstance.getCalledCaseInstanceId(); + dto.assignee = historicActivityInstance.getAssignee(); + dto.startTime = historicActivityInstance.getStartTime(); + dto.endTime = historicActivityInstance.getEndTime(); + dto.durationInMillis = historicActivityInstance.getDurationInMillis(); + dto.canceled = historicActivityInstance.isCanceled(); + dto.completeScope = historicActivityInstance.isCompleteScope(); + dto.tenantId = historicActivityInstance.getTenantId(); + dto.removalTime = historicActivityInstance.getRemovalTime(); + dto.rootProcessInstanceId = historicActivityInstance.getRootProcessInstanceId(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f9afd719cc74d0690e9ff9d7e2637a483bc81390 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityInstanceQueryDto.java @@ -0,0 +1,292 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricActivityInstanceQueryDto extends AbstractQueryDto { + + protected static final String SORT_BY_HISTORIC_ACTIVITY_INSTANCE_ID_VALUE = "activityInstanceId"; + protected static final String SORT_BY_PROCESS_INSTANCE_ID_VALUE = "instanceId"; + protected static final String SORT_BY_EXECUTION_ID_VALUE = "executionId"; + protected static final String SORT_BY_ACTIVITY_ID_VALUE = "activityId"; + protected static final String SORT_BY_ACTIVITY_NAME_VALUE = "activityName"; + protected static final String SORT_BY_ACTIVITY_TYPE_VALUE = "activityType"; + protected static final String SORT_BY_HISTORIC_ACTIVITY_INSTANCE_START_TIME_VALUE = "startTime"; + protected static final String SORT_BY_HISTORIC_ACTIVITY_INSTANCE_END_TIME_VALUE = "endTime"; + protected static final String SORT_BY_HISTORIC_ACTIVITY_INSTANCE_DURATION_VALUE = "duration"; + protected static final String SORT_BY_PROCESS_DEFINITION_ID_VALUE = "definitionId"; + protected static final String SORT_PARTIALLY_BY_OCCURRENCE = "occurrence"; + protected static final String SORT_BY_TENANT_ID = "tenantId"; + + protected static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_TYPE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_START_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_END_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_DURATION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_PARTIALLY_BY_OCCURRENCE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String activityInstanceId; + protected String processInstanceId; + protected String processDefinitionId; + protected String executionId; + protected String activityId; + protected String activityName; + protected String activityNameLike; + protected String activityType; + protected String taskAssignee; + protected Boolean finished; + protected Boolean unfinished; + protected Boolean completeScope; + protected Boolean canceled; + protected Date startedBefore; + protected Date startedAfter; + protected Date finishedBefore; + protected Date finishedAfter; + protected List tenantIds; + protected Boolean withoutTenantId; + + public HistoricActivityInstanceQueryDto() { + } + + public HistoricActivityInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("activityInstanceId") + public void setActivityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + @CamundaQueryParam("activityName") + public void setActivityName(String activityName) { + this.activityName = activityName; + } + + @CamundaQueryParam("activityNameLike") + public void setActivityNameLike(String activityNameLike) { + this.activityNameLike = activityNameLike; + } + + @CamundaQueryParam("activityType") + public void setActivityType(String activityType) { + this.activityType = activityType; + } + + @CamundaQueryParam("taskAssignee") + public void setTaskAssignee(String taskAssignee) { + this.taskAssignee = taskAssignee; + } + + @CamundaQueryParam(value = "finished", converter = BooleanConverter.class) + public void setFinished(Boolean finished) { + this.finished = finished; + } + + @CamundaQueryParam(value = "unfinished", converter = BooleanConverter.class) + public void setUnfinished(Boolean unfinished) { + this.unfinished = unfinished; + } + + @CamundaQueryParam(value = "completeScope", converter = BooleanConverter.class) + public void setCompleteScope(Boolean completeScope) { + this.completeScope = completeScope; + } + + @CamundaQueryParam(value = "canceled", converter = BooleanConverter.class) + public void setCanceled(Boolean canceled) { + this.canceled = canceled; + } + + @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) + public void setStartedBefore(Date startedBefore) { + this.startedBefore = startedBefore; + } + + @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) + public void setStartedAfter(Date startedAfter) { + this.startedAfter = startedAfter; + } + + @CamundaQueryParam(value = "finishedBefore", converter = DateConverter.class) + public void setFinishedBefore(Date finishedBefore) { + this.finishedBefore = finishedBefore; + } + + @CamundaQueryParam(value = "finishedAfter", converter = DateConverter.class) + public void setFinishedAfter(Date finishedAfter) { + this.finishedAfter = finishedAfter; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricActivityInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricActivityInstanceQuery(); + } + + @Override + protected void applyFilters(HistoricActivityInstanceQuery query) { + if (activityInstanceId != null) { + query.activityInstanceId(activityInstanceId); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (executionId != null) { + query.executionId(executionId); + } + if (activityId != null) { + query.activityId(activityId); + } + if (activityName != null) { + query.activityName(activityName); + } + if (activityNameLike != null) { + query.activityNameLike(activityNameLike); + } + if (activityType != null) { + query.activityType(activityType); + } + if (taskAssignee != null) { + query.taskAssignee(taskAssignee); + } + if (finished != null && finished) { + query.finished(); + } + if (unfinished != null && unfinished) { + query.unfinished(); + } + if (completeScope != null && completeScope) { + query.completeScope(); + } + if (canceled != null && canceled) { + query.canceled(); + } + if (startedBefore != null) { + query.startedBefore(startedBefore); + } + if (startedAfter != null) { + query.startedAfter(startedAfter); + } + if (finishedBefore != null) { + query.finishedBefore(finishedBefore); + } + if (finishedAfter != null) { + query.finishedAfter(finishedAfter); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + } + + @Override + protected void applySortBy(HistoricActivityInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_ID_VALUE)) { + query.orderByHistoricActivityInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID_VALUE)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID_VALUE)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_EXECUTION_ID_VALUE)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_ID_VALUE)) { + query.orderByActivityId(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_NAME_VALUE)) { + query.orderByActivityName(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_TYPE_VALUE)) { + query.orderByActivityType(); + } else if (sortBy.equals(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_START_TIME_VALUE)) { + query.orderByHistoricActivityInstanceStartTime(); + } else if (sortBy.equals(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_END_TIME_VALUE)) { + query.orderByHistoricActivityInstanceEndTime(); + } else if (sortBy.equals(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_DURATION_VALUE)) { + query.orderByHistoricActivityInstanceDuration(); + } else if (sortBy.equals(SORT_PARTIALLY_BY_OCCURRENCE)) { + query.orderPartiallyByOccurrence(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityStatisticsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityStatisticsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5cda2469fbef594821bb97eb16abc2527dbfb8d9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricActivityStatisticsDto.java @@ -0,0 +1,87 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricActivityStatistics; + +/** + * + * @author Roman Smirnov + * + */ +public class HistoricActivityStatisticsDto { + + protected String id; + protected long instances; + protected long canceled; + protected long finished; + protected long completeScope; + protected long openIncidents; + protected long resolvedIncidents; + protected long deletedIncidents; + + public HistoricActivityStatisticsDto () {} + + public String getId() { + return id; + } + + public long getInstances() { + return instances; + } + + public long getCanceled() { + return canceled; + } + + public long getFinished() { + return finished; + } + + public long getCompleteScope() { + return completeScope; + } + + public long getOpenIncidents() { + return openIncidents; + } + + public long getResolvedIncidents() { + return resolvedIncidents; + } + + public long getDeletedIncidents() { + return deletedIncidents; + } + + public static HistoricActivityStatisticsDto fromHistoricActivityStatistics(HistoricActivityStatistics statistics) { + HistoricActivityStatisticsDto result = new HistoricActivityStatisticsDto(); + + result.id = statistics.getId(); + + result.instances = statistics.getInstances(); + result.canceled = statistics.getCanceled(); + result.finished = statistics.getFinished(); + result.completeScope = statistics.getCompleteScope(); + result.openIncidents = statistics.getOpenIncidents(); + result.resolvedIncidents = statistics.getResolvedIncidents(); + result.deletedIncidents = statistics.getDeletedIncidents(); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..93687a541fa5f906d4354220b50cc6f3d6455e62 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityInstanceDto.java @@ -0,0 +1,165 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricCaseActivityInstance; + +import java.util.Date; + +public class HistoricCaseActivityInstanceDto { + + private String id; + private String parentCaseActivityInstanceId; + private String caseActivityId; + private String caseActivityName; + private String caseActivityType; + private String caseDefinitionId; + private String caseInstanceId; + private String caseExecutionId; + private String taskId; + private String calledProcessInstanceId; + private String calledCaseInstanceId; + private String tenantId; + private Date createTime; + private Date endTime; + private Long durationInMillis; + private Boolean required; + private Boolean available; + private Boolean enabled; + private Boolean disabled; + private Boolean active; + private Boolean completed; + private Boolean terminated; + + public String getId() { + return id; + } + + public String getParentCaseActivityInstanceId() { + return parentCaseActivityInstanceId; + } + + public String getCaseActivityId() { + return caseActivityId; + } + + public String getCaseActivityName() { + return caseActivityName; + } + + public String getCaseActivityType() { + return caseActivityType; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getTaskId() { + return taskId; + } + + public String getCalledProcessInstanceId() { + return calledProcessInstanceId; + } + + public String getCalledCaseInstanceId() { + return calledCaseInstanceId; + } + + public String getTenantId() { + return tenantId; + } + + public Date getCreateTime() { + return createTime; + } + + public Date getEndTime() { + return endTime; + } + + public Long getDurationInMillis() { + return durationInMillis; + } + + public Boolean getRequired() { + return required; + } + + public Boolean getAvailable() { + return available; + } + + public Boolean getEnabled() { + return enabled; + } + + public Boolean getDisabled() { + return disabled; + } + + public Boolean getActive() { + return active; + } + + public Boolean getCompleted() { + return completed; + } + + public Boolean getTerminated() { + return terminated; + } + + public static HistoricCaseActivityInstanceDto fromHistoricCaseActivityInstance(HistoricCaseActivityInstance historicCaseActivityInstance) { + + HistoricCaseActivityInstanceDto dto = new HistoricCaseActivityInstanceDto(); + + dto.id = historicCaseActivityInstance.getId(); + dto.parentCaseActivityInstanceId = historicCaseActivityInstance.getParentCaseActivityInstanceId(); + dto.caseActivityId = historicCaseActivityInstance.getCaseActivityId(); + dto.caseActivityName = historicCaseActivityInstance.getCaseActivityName(); + dto.caseActivityType = historicCaseActivityInstance.getCaseActivityType(); + dto.caseDefinitionId = historicCaseActivityInstance.getCaseDefinitionId(); + dto.caseInstanceId = historicCaseActivityInstance.getCaseInstanceId(); + dto.caseExecutionId = historicCaseActivityInstance.getCaseExecutionId(); + dto.taskId = historicCaseActivityInstance.getTaskId(); + dto.calledProcessInstanceId = historicCaseActivityInstance.getCalledProcessInstanceId(); + dto.calledCaseInstanceId = historicCaseActivityInstance.getCalledCaseInstanceId(); + dto.tenantId = historicCaseActivityInstance.getTenantId(); + dto.createTime = historicCaseActivityInstance.getCreateTime(); + dto.endTime = historicCaseActivityInstance.getEndTime(); + dto.durationInMillis = historicCaseActivityInstance.getDurationInMillis(); + dto.required = historicCaseActivityInstance.isRequired(); + dto.available = historicCaseActivityInstance.isAvailable(); + dto.enabled = historicCaseActivityInstance.isEnabled(); + dto.disabled = historicCaseActivityInstance.isDisabled(); + dto.active = historicCaseActivityInstance.isActive(); + dto.completed = historicCaseActivityInstance.isCompleted(); + dto.terminated = historicCaseActivityInstance.isTerminated(); + + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4960a5a2ac0306dcb5222a391771fcc05a583455 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityInstanceQueryDto.java @@ -0,0 +1,332 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstanceQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricCaseActivityInstanceQueryDto extends AbstractQueryDto { + + protected static final String SORT_BY_HISTORIC_ACTIVITY_INSTANCE_ID_VALUE = "caseActivityInstanceId"; + protected static final String SORT_BY_CASE_INSTANCE_ID_VALUE = "caseInstanceId"; + protected static final String SORT_BY_CASE_EXECUTION_ID_VALUE = "caseExecutionId"; + protected static final String SORT_BY_CASE_ACTIVITY_ID_VALUE = "caseActivityId"; + protected static final String SORT_BY_CASE_ACTIVITY_NAME_VALUE = "caseActivityName"; + protected static final String SORT_BY_CASE_ACTIVITY_TYPE_VALUE = "caseActivityType"; + protected static final String SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATE_TIME_VALUE = "createTime"; + protected static final String SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME_VALUE = "endTime"; + protected static final String SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_DURATION_VALUE = "duration"; + protected static final String SORT_BY_CASE_DEFINITION_ID_VALUE = "caseDefinitionId"; + protected static final String SORT_BY_TENANT_ID = "tenantId"; + + protected static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_EXECUTION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_ACTIVITY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_ACTIVITY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_ACTIVITY_TYPE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATE_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_DURATION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String caseActivityInstanceId; + protected List caseActivityInstanceIds; + protected String caseInstanceId; + protected String caseDefinitionId; + protected String caseExecutionId; + protected String caseActivityId; + protected List caseActivityIds; + protected String caseActivityName; + protected String caseActivityType; + protected Date createdBefore; + protected Date createdAfter; + protected Date endedBefore; + protected Date endedAfter; + protected Boolean required; + protected Boolean finished; + protected Boolean unfinished; + protected Boolean available; + protected Boolean enabled; + protected Boolean disabled; + protected Boolean active; + protected Boolean completed; + protected Boolean terminated; + protected List tenantIds; + protected Boolean withoutTenantId; + + public HistoricCaseActivityInstanceQueryDto() { + } + + public HistoricCaseActivityInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("caseActivityInstanceId") + public void setCaseActivityInstanceId(String caseActivityInstanceId) { + this.caseActivityInstanceId = caseActivityInstanceId; + } + + @CamundaQueryParam(value = "caseActivityInstanceIdIn", converter = StringListConverter.class) + public void setCaseActivityInstanceIdIn(List caseActivityInstanceIds) { + this.caseActivityInstanceIds = caseActivityInstanceIds; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("caseExecutionId") + public void setCaseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + } + + @CamundaQueryParam("caseActivityId") + public void setCaseActivityId(String caseActivityId) { + this.caseActivityId = caseActivityId; + } + + @CamundaQueryParam(value = "caseActivityIdIn", converter = StringListConverter.class) + public void setCaseActivityIdIn(List caseActivityIds) { + this.caseActivityIds = caseActivityIds; + } + + @CamundaQueryParam("caseActivityName") + public void setCaseActivityName(String caseActivityName) { + this.caseActivityName = caseActivityName; + } + + @CamundaQueryParam("caseActivityType") + public void setCaseActivityType(String caseActivityType) { + this.caseActivityType = caseActivityType; + } + + @CamundaQueryParam(value = "createdBefore", converter = DateConverter.class) + public void setCreatedBefore(Date createdBefore) { + this.createdBefore = createdBefore; + } + + @CamundaQueryParam(value = "createdAfter", converter = DateConverter.class) + public void setCreatedAfter(Date createdAfter) { + this.createdAfter = createdAfter; + } + + @CamundaQueryParam(value = "endedBefore", converter = DateConverter.class) + public void setEndedBefore(Date endedBefore) { + this.endedBefore = endedBefore; + } + + @CamundaQueryParam(value = "endedAfter", converter = DateConverter.class) + public void setEndedAfter(Date endedAfter) { + this.endedAfter = endedAfter; + } + + @CamundaQueryParam(value = "required", converter = BooleanConverter.class) + public void setRequired(Boolean required) { + this.required = required; + } + + @CamundaQueryParam(value = "finished", converter = BooleanConverter.class) + public void setFinished(Boolean finished) { + this.finished = finished; + } + + @CamundaQueryParam(value = "unfinished", converter = BooleanConverter.class) + public void setUnfinished(Boolean unfinished) { + this.unfinished = unfinished; + } + + @CamundaQueryParam(value = "available", converter = BooleanConverter.class) + public void setAvailable(Boolean available) { + this.available = available; + } + + @CamundaQueryParam(value = "enabled", converter = BooleanConverter.class) + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @CamundaQueryParam(value = "disabled", converter = BooleanConverter.class) + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "completed", converter = BooleanConverter.class) + public void setCompleted(Boolean completed) { + this.completed = completed; + } + + @CamundaQueryParam(value = "terminated", converter = BooleanConverter.class) + public void setTerminated(Boolean terminated) { + this.terminated = terminated; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricCaseActivityInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricCaseActivityInstanceQuery(); + } + + @Override + protected void applyFilters(HistoricCaseActivityInstanceQuery query) { + if (caseActivityInstanceId != null) { + query.caseActivityInstanceId(caseActivityInstanceId); + } + if (caseActivityInstanceIds != null && !caseActivityInstanceIds.isEmpty()) { + query.caseActivityInstanceIdIn(caseActivityInstanceIds.toArray(new String[caseActivityInstanceIds.size()])); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (caseExecutionId != null) { + query.caseExecutionId(caseExecutionId); + } + if (caseActivityId != null) { + query.caseActivityId(caseActivityId); + } + if (caseActivityIds != null && !caseActivityIds.isEmpty()) { + query.caseActivityIdIn(caseActivityIds.toArray(new String[caseActivityIds.size()])); + } + if (caseActivityName != null) { + query.caseActivityName(caseActivityName); + } + if (caseActivityType != null) { + query.caseActivityType(caseActivityType); + } + if (createdBefore != null) { + query.createdBefore(createdBefore); + } + if (createdAfter != null) { + query.createdAfter(createdAfter); + } + if (endedBefore != null) { + query.endedBefore(endedBefore); + } + if (endedAfter != null) { + query.endedAfter(endedAfter); + } + if (required != null && required) { + query.required(); + } + if (finished != null && finished) { + query.ended(); + } + if (unfinished != null && unfinished) { + query.notEnded(); + } + if (available != null && available) { + query.available(); + } + if (enabled != null && enabled) { + query.enabled(); + } + if (disabled != null && disabled) { + query.disabled(); + } + if (active != null && active) { + query.active(); + } + if (completed != null && completed) { + query.completed(); + } + if (terminated != null && terminated) { + query.terminated(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + } + + protected void applySortBy(HistoricCaseActivityInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_HISTORIC_ACTIVITY_INSTANCE_ID_VALUE)) { + query.orderByHistoricCaseActivityInstanceId(); + } else if (sortBy.equals(SORT_BY_CASE_INSTANCE_ID_VALUE)) { + query.orderByCaseInstanceId(); + } else if (sortBy.equals(SORT_BY_CASE_EXECUTION_ID_VALUE)) { + query.orderByCaseExecutionId(); + } else if (sortBy.equals(SORT_BY_CASE_ACTIVITY_ID_VALUE)) { + query.orderByCaseActivityId(); + } else if (sortBy.equals(SORT_BY_CASE_ACTIVITY_NAME_VALUE)) { + query.orderByCaseActivityName(); + } else if (sortBy.equals(SORT_BY_CASE_ACTIVITY_TYPE_VALUE)) { + query.orderByCaseActivityType(); + } else if (sortBy.equals(SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATE_TIME_VALUE)) { + query.orderByHistoricCaseActivityInstanceCreateTime(); + } else if (sortBy.equals(SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME_VALUE)) { + query.orderByHistoricCaseActivityInstanceEndTime(); + } else if (sortBy.equals(SORT_BY_HISTORIC_CASE_ACTIVITY_INSTANCE_DURATION_VALUE)) { + query.orderByHistoricCaseActivityInstanceDuration(); + } else if (sortBy.equals(SORT_BY_CASE_DEFINITION_ID_VALUE)) { + query.orderByCaseDefinitionId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityStatisticsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityStatisticsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..381c69330e2dc91166fe8f4baf523227cf719853 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseActivityStatisticsDto.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricCaseActivityStatistics; + +/** + * @author Roman Smirnov + * + */ +public class HistoricCaseActivityStatisticsDto { + + protected String id; + protected long available; + protected long enabled; + protected long disabled; + protected long active; + protected long completed; + protected long terminated; + + public String getId() { + return id; + } + + public long getAvailable() { + return available; + } + + public long getEnabled() { + return enabled; + } + + public long getDisabled() { + return disabled; + } + + public long getActive() { + return active; + } + + public long getCompleted() { + return completed; + } + + public long getTerminated() { + return terminated; + } + + public static HistoricCaseActivityStatisticsDto fromHistoricCaseActivityStatistics(HistoricCaseActivityStatistics statistics) { + HistoricCaseActivityStatisticsDto result = new HistoricCaseActivityStatisticsDto(); + + result.id = statistics.getId(); + result.available = statistics.getAvailable(); + result.enabled = statistics.getEnabled(); + result.disabled = statistics.getDisabled(); + result.active = statistics.getActive(); + result.completed = statistics.getCompleted(); + result.terminated = statistics.getTerminated(); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..6da8113379eae8633ae872bf78f4b6dd14e04288 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseInstanceDto.java @@ -0,0 +1,130 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricCaseInstance; + +public class HistoricCaseInstanceDto { + + protected String id; + protected String businessKey; + protected String caseDefinitionId; + protected String caseDefinitionKey; + protected String caseDefinitionName; + protected Date createTime; + protected Date closeTime; + protected Long durationInMillis; + protected String createUserId; + protected String superCaseInstanceId; + protected String superProcessInstanceId; + protected String tenantId; + protected Boolean active; + protected Boolean completed; + protected Boolean terminated; + protected Boolean closed; + + public String getId() { + return id; + } + + public String getBusinessKey() { + return businessKey; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseDefinitionName() { + return caseDefinitionName; + } + + public Date getCreateTime() { + return createTime; + } + + public Date getCloseTime() { + return closeTime; + } + + public Long getDurationInMillis() { + return durationInMillis; + } + + public String getCreateUserId() { + return createUserId; + } + + public String getSuperCaseInstanceId() { + return superCaseInstanceId; + } + + public String getSuperProcessInstanceId() { + return superProcessInstanceId; + } + + public String getTenantId() { + return tenantId; + } + + public Boolean getActive() { + return active; + } + + public Boolean getCompleted() { + return completed; + } + + public Boolean getTerminated() { + return terminated; + } + + public Boolean getClosed() { + return closed; + } + + public static HistoricCaseInstanceDto fromHistoricCaseInstance(HistoricCaseInstance historicCaseInstance) { + + HistoricCaseInstanceDto dto = new HistoricCaseInstanceDto(); + + dto.id = historicCaseInstance.getId(); + dto.businessKey = historicCaseInstance.getBusinessKey(); + dto.caseDefinitionId = historicCaseInstance.getCaseDefinitionId(); + dto.caseDefinitionKey = historicCaseInstance.getCaseDefinitionKey(); + dto.caseDefinitionName = historicCaseInstance.getCaseDefinitionName(); + dto.createTime = historicCaseInstance.getCreateTime(); + dto.closeTime = historicCaseInstance.getCloseTime(); + dto.durationInMillis = historicCaseInstance.getDurationInMillis(); + dto.createUserId = historicCaseInstance.getCreateUserId(); + dto.superCaseInstanceId = historicCaseInstance.getSuperCaseInstanceId(); + dto.superProcessInstanceId = historicCaseInstance.getSuperProcessInstanceId(); + dto.tenantId = historicCaseInstance.getTenantId(); + dto.active = historicCaseInstance.isActive(); + dto.completed = historicCaseInstance.isCompleted(); + dto.terminated = historicCaseInstance.isTerminated(); + dto.closed = historicCaseInstance.isClosed(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..8e4886d2a464fc9b5cd9f55ddc2efb46e18d6acd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricCaseInstanceQueryDto.java @@ -0,0 +1,394 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricCaseInstanceQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringSetConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricCaseInstanceQueryDto extends AbstractQueryDto { + + public static final String SORT_BY_CASE_INSTANCE_ID_VALUE = "instanceId"; + public static final String SORT_BY_CASE_DEFINITION_ID_VALUE = "definitionId"; + public static final String SORT_BY_CASE_INSTANCE_BUSINESS_KEY_VALUE = "businessKey"; + public static final String SORT_BY_CASE_INSTANCE_CREATE_TIME_VALUE = "createTime"; + public static final String SORT_BY_CASE_INSTANCE_CLOSE_TIME_VALUE = "closeTime"; + public static final String SORT_BY_CASE_INSTANCE_DURATION_VALUE = "duration"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + public static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INSTANCE_BUSINESS_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INSTANCE_CREATE_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INSTANCE_CLOSE_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INSTANCE_DURATION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + public String caseInstanceId; + public Set caseInstanceIds; + public String caseDefinitionId; + public String caseDefinitionKey; + public String caseDefinitionName; + public String caseDefinitionNameLike; + public List caseDefinitionKeyNotIn; + public String caseInstanceBusinessKey; + public String caseInstanceBusinessKeyLike; + public String superCaseInstanceId; + public String subCaseInstanceId; + private String superProcessInstanceId; + private String subProcessInstanceId; + private List tenantIds; + private Boolean withoutTenantId; + public String createdBy; + public List caseActivityIdIn; + + public Date createdBefore; + public Date createdAfter; + public Date closedBefore; + public Date closedAfter; + + public Boolean active; + public Boolean completed; + public Boolean terminated; + public Boolean closed; + public Boolean notClosed; + + protected List variables; + + protected Boolean variableValuesIgnoreCase; + protected Boolean variableNamesIgnoreCase; + + public HistoricCaseInstanceQueryDto() {} + + public HistoricCaseInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam(value = "caseInstanceIds", converter = StringSetConverter.class) + public void setCaseInstanceIds(Set caseInstanceIds) { + this.caseInstanceIds = caseInstanceIds; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("caseDefinitionName") + public void setCaseDefinitionName(String caseDefinitionName) { + this.caseDefinitionName = caseDefinitionName; + } + + @CamundaQueryParam("caseDefinitionNameLike") + public void setCaseDefinitionNameLike(String caseDefinitionNameLike) { + this.caseDefinitionNameLike = caseDefinitionNameLike; + } + + @CamundaQueryParam("caseDefinitionKey") + public void setCaseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + } + + @CamundaQueryParam(value = "caseDefinitionKeyNotIn", converter = StringListConverter.class) + public void setCaseDefinitionKeyNotIn(List caseDefinitionKeys) { + this.caseDefinitionKeyNotIn = caseDefinitionKeys; + } + + @CamundaQueryParam("caseInstanceBusinessKey") + public void setCaseInstanceBusinessKey(String caseInstanceBusinessKey) { + this.caseInstanceBusinessKey = caseInstanceBusinessKey; + } + + @CamundaQueryParam("caseInstanceBusinessKeyLike") + public void setCaseInstanceBusinessKeyLike(String caseInstanceBusinessKeyLike) { + this.caseInstanceBusinessKeyLike = caseInstanceBusinessKeyLike; + } + + @CamundaQueryParam("superCaseInstanceId") + public void setSuperCaseInstanceId(String superCaseInstanceId) { + this.superCaseInstanceId = superCaseInstanceId; + } + + @CamundaQueryParam("subCaseInstanceId") + public void setSubCaseInstanceId(String subCaseInstanceId) { + this.subCaseInstanceId = subCaseInstanceId; + } + + @CamundaQueryParam("superProcessInstanceId") + public void setSuperProcessInstanceId(String superProcessInstanceId) { + this.superProcessInstanceId = superProcessInstanceId; + } + + @CamundaQueryParam("subProcessInstanceId") + public void setSubProcessInstanceId(String subProcessInstanceId) { + this.subProcessInstanceId = subProcessInstanceId; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam("createdBy") + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + @CamundaQueryParam(value = "createdBefore", converter = DateConverter.class) + public void setCreatedBefore(Date createdBefore) { + this.createdBefore = createdBefore; + } + + @CamundaQueryParam(value = "createdAfter", converter = DateConverter.class) + public void setCreatedAfter(Date createdAfter) { + this.createdAfter = createdAfter; + } + + @CamundaQueryParam(value = "closedBefore", converter = DateConverter.class) + public void setClosedBefore(Date closedBefore) { + this.closedBefore = closedBefore; + } + + @CamundaQueryParam(value = "closedAfter", converter = DateConverter.class) + public void setClosedAfter(Date closedAfter) { + this.closedAfter = closedAfter; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "completed", converter = BooleanConverter.class) + public void setCompleted(Boolean completed) { + this.completed = completed; + } + + @CamundaQueryParam(value = "terminated", converter = BooleanConverter.class) + public void setTerminated(Boolean terminated) { + this.terminated = terminated; + } + + @CamundaQueryParam(value = "closed", converter = BooleanConverter.class) + public void setClosed(Boolean closed) { + this.closed = closed; + } + + @CamundaQueryParam(value = "notClosed", converter = BooleanConverter.class) + public void setNotClosed(Boolean notClosed) { + this.notClosed = notClosed; + } + + @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) + public void setVariables(List variables) { + this.variables = variables; + } + + @CamundaQueryParam(value = "variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam(value = "caseActivityIdIn", converter = StringListConverter.class) + public void setCaseActivityIdIn(List caseActivityIdIn) { + this.caseActivityIdIn = caseActivityIdIn; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricCaseInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricCaseInstanceQuery(); + } + + @Override + protected void applyFilters(HistoricCaseInstanceQuery query) { + + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (caseInstanceIds != null) { + query.caseInstanceIds(caseInstanceIds); + } + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (caseDefinitionKey != null) { + query.caseDefinitionKey(caseDefinitionKey); + } + if (caseDefinitionName != null) { + query.caseDefinitionName(caseDefinitionName); + } + if (caseDefinitionNameLike != null) { + query.caseDefinitionNameLike(caseDefinitionNameLike); + } + if (caseDefinitionKeyNotIn != null) { + query.caseDefinitionKeyNotIn(caseDefinitionKeyNotIn); + } + if (caseInstanceBusinessKey != null) { + query.caseInstanceBusinessKey(caseInstanceBusinessKey); + } + if (caseInstanceBusinessKeyLike != null) { + query.caseInstanceBusinessKeyLike(caseInstanceBusinessKeyLike); + } + if (superCaseInstanceId != null) { + query.superCaseInstanceId(superCaseInstanceId); + } + if (subCaseInstanceId != null) { + query.subCaseInstanceId(subCaseInstanceId); + } + if (superProcessInstanceId != null) { + query.superProcessInstanceId(superProcessInstanceId); + } + if (subProcessInstanceId != null) { + query.subProcessInstanceId(subProcessInstanceId); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (createdBy != null) { + query.createdBy(createdBy); + } + if (createdBefore != null) { + query.createdBefore(createdBefore); + } + if (createdAfter != null) { + query.createdAfter(createdAfter); + } + if (closedBefore != null) { + query.closedBefore(closedBefore); + } + if (closedAfter != null) { + query.closedAfter(closedAfter); + } + if (active != null && active) { + query.active(); + } + if (completed != null && completed) { + query.completed(); + } + if (terminated != null && terminated) { + query.terminated(); + } + if (closed != null && closed) { + query.closed(); + } + if (notClosed != null && notClosed) { + query.notClosed(); + } + if (caseActivityIdIn != null && !caseActivityIdIn.isEmpty()) { + query.caseActivityIdIn(caseActivityIdIn.toArray(new String[caseActivityIdIn.size()])); + } + if(Boolean.TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + if(Boolean.TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + if (variables != null) { + for (VariableQueryParameterDto variableQueryParam : variables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.variableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.variableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.variableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.variableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.variableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + } + + @Override + protected void applySortBy(HistoricCaseInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_CASE_INSTANCE_ID_VALUE)) { + query.orderByCaseInstanceId(); + } else if (sortBy.equals(SORT_BY_CASE_DEFINITION_ID_VALUE)) { + query.orderByCaseDefinitionId(); + } else if (sortBy.equals(SORT_BY_CASE_INSTANCE_BUSINESS_KEY_VALUE)) { + query.orderByCaseInstanceBusinessKey(); + } else if (sortBy.equals(SORT_BY_CASE_INSTANCE_CREATE_TIME_VALUE)) { + query.orderByCaseInstanceCreateTime(); + } else if (sortBy.equals(SORT_BY_CASE_INSTANCE_CLOSE_TIME_VALUE)) { + query.orderByCaseInstanceCloseTime(); + } else if (sortBy.equals(SORT_BY_CASE_INSTANCE_DURATION_VALUE)) { + query.orderByCaseInstanceDuration(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInputInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInputInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..6abb8e9f106ff31e35d3f518181896d216f2ebb4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInputInstanceDto.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricDecisionInputInstance; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +public class HistoricDecisionInputInstanceDto extends VariableValueDto { + + protected String id; + protected String decisionInstanceId; + protected String clauseId; + protected String clauseName; + protected String errorMessage; + protected Date createTime; + protected Date removalTime; + protected String rootProcessInstanceId; + + public String getId() { + return id; + } + + public String getDecisionInstanceId() { + return decisionInstanceId; + } + + public String getClauseId() { + return clauseId; + } + + public String getClauseName() { + return clauseName; + } + + public String getErrorMessage() { + return errorMessage; + } + + public Date getCreateTime() { + return createTime; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public static HistoricDecisionInputInstanceDto fromHistoricDecisionInputInstance(HistoricDecisionInputInstance historicDecisionInputInstance) { + + HistoricDecisionInputInstanceDto dto = new HistoricDecisionInputInstanceDto(); + + dto.id = historicDecisionInputInstance.getId(); + dto.decisionInstanceId = historicDecisionInputInstance.getDecisionInstanceId(); + dto.clauseId = historicDecisionInputInstance.getClauseId(); + dto.clauseName = historicDecisionInputInstance.getClauseName(); + dto.createTime = historicDecisionInputInstance.getCreateTime(); + dto.removalTime = historicDecisionInputInstance.getRemovalTime(); + dto.rootProcessInstanceId = historicDecisionInputInstance.getRootProcessInstanceId(); + + if(historicDecisionInputInstance.getErrorMessage() == null) { + VariableValueDto.fromTypedValue(dto, historicDecisionInputInstance.getTypedValue()); + } + else { + dto.errorMessage = historicDecisionInputInstance.getErrorMessage(); + dto.type = VariableValueDto.toRestApiTypeName(historicDecisionInputInstance.getTypeName()); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ec5f4ced297ba486c5f8d82cbff9618ec94f9c91 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceDto.java @@ -0,0 +1,211 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.history.HistoricDecisionInputInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricDecisionOutputInstance; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +public class HistoricDecisionInstanceDto { + + protected String id; + protected String decisionDefinitionId; + protected String decisionDefinitionKey; + protected String decisionDefinitionName; + protected Date evaluationTime; + protected Date removalTime; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processInstanceId; + protected String rootProcessInstanceId; + protected String caseDefinitionId; + protected String caseDefinitionKey; + protected String caseInstanceId; + protected String activityId; + protected String activityInstanceId; + protected String userId; + protected List inputs; + protected List outputs; + protected Double collectResultValue; + protected String rootDecisionInstanceId; + protected String decisionRequirementsDefinitionId; + protected String decisionRequirementsDefinitionKey; + protected String tenantId; + + public String getId() { + return id; + } + + public String getDecisionDefinitionId() { + return decisionDefinitionId; + } + + public String getDecisionDefinitionKey() { + return decisionDefinitionKey; + } + + public String getDecisionDefinitionName() { + return decisionDefinitionName; + } + + public Date getEvaluationTime() { + return evaluationTime; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getActivityId() { + return activityId; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public String getUserId() { + return userId; + } + + @JsonInclude(Include.NON_NULL) + public List getInputs() { + return inputs; + } + + @JsonInclude(Include.NON_NULL) + public List getOutputs() { + return outputs; + } + + public Double getCollectResultValue() { + return collectResultValue; + } + + public String getRootDecisionInstanceId() { + return rootDecisionInstanceId; + } + + public String getTenantId() { + return tenantId; + } + + public String getDecisionRequirementsDefinitionId() { + return decisionRequirementsDefinitionId; + } + + public String getDecisionRequirementsDefinitionKey() { + return decisionRequirementsDefinitionKey; + } + + public Date getRemovalTime() { + return removalTime; + } + + public void setRemovalTime(Date removalTime) { + this.removalTime = removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + + public static HistoricDecisionInstanceDto fromHistoricDecisionInstance(HistoricDecisionInstance historicDecisionInstance) { + HistoricDecisionInstanceDto dto = new HistoricDecisionInstanceDto(); + + dto.id = historicDecisionInstance.getId(); + dto.decisionDefinitionId = historicDecisionInstance.getDecisionDefinitionId(); + dto.decisionDefinitionKey = historicDecisionInstance.getDecisionDefinitionKey(); + dto.decisionDefinitionName = historicDecisionInstance.getDecisionDefinitionName(); + dto.evaluationTime = historicDecisionInstance.getEvaluationTime(); + dto.removalTime = historicDecisionInstance.getRemovalTime(); + dto.processDefinitionId = historicDecisionInstance.getProcessDefinitionId(); + dto.processDefinitionKey = historicDecisionInstance.getProcessDefinitionKey(); + dto.processInstanceId = historicDecisionInstance.getProcessInstanceId(); + dto.caseDefinitionId = historicDecisionInstance.getCaseDefinitionId(); + dto.caseDefinitionKey = historicDecisionInstance.getCaseDefinitionKey(); + dto.caseInstanceId = historicDecisionInstance.getCaseInstanceId(); + dto.activityId = historicDecisionInstance.getActivityId(); + dto.activityInstanceId = historicDecisionInstance.getActivityInstanceId(); + dto.userId = historicDecisionInstance.getUserId(); + dto.collectResultValue = historicDecisionInstance.getCollectResultValue(); + dto.rootDecisionInstanceId = historicDecisionInstance.getRootDecisionInstanceId(); + dto.rootProcessInstanceId = historicDecisionInstance.getRootProcessInstanceId(); + dto.decisionRequirementsDefinitionId = historicDecisionInstance.getDecisionRequirementsDefinitionId(); + dto.decisionRequirementsDefinitionKey = historicDecisionInstance.getDecisionRequirementsDefinitionKey(); + dto.tenantId = historicDecisionInstance.getTenantId(); + + try { + List inputs = new ArrayList(); + for (HistoricDecisionInputInstance input : historicDecisionInstance.getInputs()) { + HistoricDecisionInputInstanceDto inputDto = HistoricDecisionInputInstanceDto.fromHistoricDecisionInputInstance(input); + inputs.add(inputDto); + } + dto.inputs = inputs; + } + catch (ProcessEngineException e) { + // no inputs fetched + } + + try { + List outputs = new ArrayList(); + for (HistoricDecisionOutputInstance output : historicDecisionInstance.getOutputs()) { + HistoricDecisionOutputInstanceDto outputDto = HistoricDecisionOutputInstanceDto.fromHistoricDecisionOutputInstance(output); + outputs.add(outputDto); + } + dto.outputs = outputs; + } + catch (ProcessEngineException e) { + // no outputs fetched + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c5965ccd538580d5f063a87bc0a59e0c469287aa --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceQueryDto.java @@ -0,0 +1,347 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricDecisionInstanceQueryDto extends AbstractQueryDto { + + public static final String SORT_BY_EVALUATION_TIME_VALUE = "evaluationTime"; + public static final String SORT_BY_TENANT_ID = "tenantId"; + + public static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_EVALUATION_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String decisionInstanceId; + protected String[] decisionInstanceIdIn; + + protected String decisionDefinitionId; + protected String[] decisionDefinitionIdIn; + + protected String decisionDefinitionKey; + protected String[] decisionDefinitionKeyIn; + + protected String decisionDefinitionName; + protected String decisionDefinitionNameLike; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processInstanceId; + protected String caseDefinitionId; + protected String caseDefinitionKey; + protected String caseInstanceId; + protected String[] activityIdIn; + protected String[] activityInstanceIdIn; + protected Date evaluatedBefore; + protected Date evaluatedAfter; + protected String userId; + protected Boolean includeInputs; + protected Boolean includeOutputs; + protected Boolean disableBinaryFetching; + protected Boolean disableCustomObjectDeserialization; + protected String rootDecisionInstanceId; + protected Boolean rootDecisionInstancesOnly; + protected String decisionRequirementsDefinitionId; + protected String decisionRequirementsDefinitionKey; + protected List tenantIds; + protected Boolean withoutTenantId; + + public HistoricDecisionInstanceQueryDto() { + } + + public HistoricDecisionInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("decisionInstanceId") + public void setDecisionInstanceId(String decisionInstanceId) { + this.decisionInstanceId = decisionInstanceId; + } + + @CamundaQueryParam(value = "decisionInstanceIdIn", converter = StringArrayConverter.class) + public void setDecisionInstanceIdIn(String[] decisionInstanceIdIn) { + this.decisionInstanceIdIn = decisionInstanceIdIn; + } + + @CamundaQueryParam("decisionDefinitionId") + public void setDecisionDefinitionId(String decisionDefinitionId) { + this.decisionDefinitionId = decisionDefinitionId; + } + + @CamundaQueryParam(value = "decisionDefinitionIdIn", converter = StringArrayConverter.class) + public void setDecisionDefinitionIdIn(String[] decisionDefinitionIdIn) { + this.decisionDefinitionIdIn = decisionDefinitionIdIn; + } + + @CamundaQueryParam("decisionDefinitionKey") + public void setDecisionDefinitionKey(String decisionDefinitionKey) { + this.decisionDefinitionKey = decisionDefinitionKey; + } + + @CamundaQueryParam(value = "decisionDefinitionKeyIn", converter = StringArrayConverter.class) + public void setDecisionDefinitionKeyIn(String[] decisionDefinitionKeyIn) { + this.decisionDefinitionKeyIn = decisionDefinitionKeyIn; + } + + @CamundaQueryParam("decisionDefinitionName") + public void setDecisionDefinitionName(String decisionDefinitionName) { + this.decisionDefinitionName = decisionDefinitionName; + } + + @CamundaQueryParam("decisionDefinitionNameLike") + public void setDecisionDefinitionNameLike(String decisionDefinitionNameLike) { + this.decisionDefinitionNameLike = decisionDefinitionNameLike; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("caseDefinitionKey") + public void setCaseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class) + public void setActivityIdIn(String[] activityIdIn) { + this.activityIdIn = activityIdIn; + } + + @CamundaQueryParam(value="activityInstanceIdIn", converter = StringArrayConverter.class) + public void setActivityInstanceIdIn(String[] activityInstanceIdIn) { + this.activityInstanceIdIn = activityInstanceIdIn; + } + + @CamundaQueryParam(value = "evaluatedBefore", converter = DateConverter.class) + public void setEvaluatedBefore(Date evaluatedBefore) { + this.evaluatedBefore = evaluatedBefore; + } + + @CamundaQueryParam(value = "evaluatedAfter", converter = DateConverter.class) + public void setEvaluatedAfter(Date evaluatedAfter) { + this.evaluatedAfter = evaluatedAfter; + } + + @CamundaQueryParam(value = "userId") + public void setUserId(String userId) { + this.userId = userId; + } + + @CamundaQueryParam(value = "includeInputs", converter = BooleanConverter.class) + public void setIncludeInputs(Boolean includeInputs) { + this.includeInputs = includeInputs; + } + + @CamundaQueryParam(value = "includeOutputs", converter = BooleanConverter.class) + public void setIncludeOutputs(Boolean includeOutputs) { + this.includeOutputs = includeOutputs; + } + + @CamundaQueryParam(value = "disableBinaryFetching", converter = BooleanConverter.class) + public void setDisableBinaryFetching(Boolean disableBinaryFetching) { + this.disableBinaryFetching = disableBinaryFetching; + } + + @CamundaQueryParam(value = "disableCustomObjectDeserialization", converter = BooleanConverter.class) + public void setDisableCustomObjectDeserialization(Boolean disableCustomObjectDeserialization) { + this.disableCustomObjectDeserialization = disableCustomObjectDeserialization; + } + + @CamundaQueryParam(value = "rootDecisionInstanceId") + public void setRootDecisionInstanceId(String rootDecisionInstanceId) { + this.rootDecisionInstanceId = rootDecisionInstanceId; + } + + @CamundaQueryParam(value = "rootDecisionInstancesOnly", converter = BooleanConverter.class) + public void setRootDecisionInstancesOnly(Boolean rootDecisionInstancesOnly) { + this.rootDecisionInstancesOnly = rootDecisionInstancesOnly; + } + + @CamundaQueryParam(value = "decisionRequirementsDefinitionId") + public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { + this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; + } + + @CamundaQueryParam(value = "decisionRequirementsDefinitionKey") + public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { + this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricDecisionInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricDecisionInstanceQuery(); + } + + @Override + protected void applyFilters(HistoricDecisionInstanceQuery query) { + if (decisionInstanceId != null) { + query.decisionInstanceId(decisionInstanceId); + } + if (decisionInstanceIdIn != null) { + query.decisionInstanceIdIn(decisionInstanceIdIn); + } + if (decisionDefinitionId != null) { + query.decisionDefinitionId(decisionDefinitionId); + } + if (decisionDefinitionIdIn != null) { + query.decisionDefinitionIdIn(decisionDefinitionIdIn); + } + if (decisionDefinitionKey != null) { + query.decisionDefinitionKey(decisionDefinitionKey); + } + if (decisionDefinitionKeyIn != null) { + query.decisionDefinitionKeyIn(decisionDefinitionKeyIn); + } + if (decisionDefinitionName != null) { + query.decisionDefinitionName(decisionDefinitionName); + } + if (decisionDefinitionNameLike != null) { + query.decisionDefinitionNameLike(decisionDefinitionNameLike); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (caseDefinitionKey != null) { + query.caseDefinitionKey(caseDefinitionKey); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (activityIdIn != null) { + query.activityIdIn(activityIdIn); + } + if (activityInstanceIdIn != null) { + query.activityInstanceIdIn(activityInstanceIdIn); + } + if (evaluatedBefore != null) { + query.evaluatedBefore(evaluatedBefore); + } + if (evaluatedAfter != null) { + query.evaluatedAfter(evaluatedAfter); + } + if (userId != null) { + query.userId(userId); + } + if (TRUE.equals(includeInputs)) { + query.includeInputs(); + } + if (TRUE.equals(includeOutputs)) { + query.includeOutputs(); + } + if (TRUE.equals(disableBinaryFetching)) { + query.disableBinaryFetching(); + } + if (TRUE.equals(disableCustomObjectDeserialization)) { + query.disableCustomObjectDeserialization(); + } + if (rootDecisionInstanceId != null) { + query.rootDecisionInstanceId(rootDecisionInstanceId); + } + if (TRUE.equals(rootDecisionInstancesOnly)) { + query.rootDecisionInstancesOnly(); + } + if (decisionRequirementsDefinitionId != null) { + query.decisionRequirementsDefinitionId(decisionRequirementsDefinitionId); + } + if (decisionRequirementsDefinitionKey != null) { + query.decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + } + + @Override + protected void applySortBy(HistoricDecisionInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_EVALUATION_TIME_VALUE)) { + query.orderByEvaluationTime(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceStatisticsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceStatisticsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b3f192af9bd12e36d68bb36bdbca19c9b2ffff46 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionInstanceStatisticsDto.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricDecisionInstanceStatistics; + +/** + * @author Askar Akhmerov + */ +public class HistoricDecisionInstanceStatisticsDto { + + protected String decisionDefinitionKey; + protected int evaluations; + + public int getEvaluations() { + return evaluations; + } + + public void setEvaluations(int evaluations) { + this.evaluations = evaluations; + } + + public String getDecisionDefinitionKey() { + return decisionDefinitionKey; + } + + public void setDecisionDefinitionKey(String decisionDefinitionKey) { + this.decisionDefinitionKey = decisionDefinitionKey; + } + + public static HistoricDecisionInstanceStatisticsDto fromDecisionDefinitionStatistics(HistoricDecisionInstanceStatistics stats) { + HistoricDecisionInstanceStatisticsDto instance = new HistoricDecisionInstanceStatisticsDto(); + instance.setEvaluations(stats.getEvaluations()); + instance.setDecisionDefinitionKey(stats.getDecisionDefinitionKey()); + return instance; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionOutputInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionOutputInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..26c3518e556840aed1daf05fca3805c70597c353 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDecisionOutputInstanceDto.java @@ -0,0 +1,108 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricDecisionOutputInstance; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +public class HistoricDecisionOutputInstanceDto extends VariableValueDto { + + protected String id; + protected String decisionInstanceId; + protected String clauseId; + protected String clauseName; + protected String ruleId; + protected Integer ruleOrder; + protected String variableName; + protected String errorMessage; + protected Date createTime; + protected Date removalTime; + protected String rootProcessInstanceId; + + public String getId() { + return id; + } + + public String getDecisionInstanceId() { + return decisionInstanceId; + } + + public String getClauseId() { + return clauseId; + } + + public String getClauseName() { + return clauseName; + } + + public String getRuleId() { + return ruleId; + } + + public Integer getRuleOrder() { + return ruleOrder; + } + + public String getVariableName() { + return variableName; + } + + public String getErrorMessage() { + return errorMessage; + } + + public Date getCreateTime() { + return createTime; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public static HistoricDecisionOutputInstanceDto fromHistoricDecisionOutputInstance(HistoricDecisionOutputInstance historicDecisionOutputInstance) { + + HistoricDecisionOutputInstanceDto dto = new HistoricDecisionOutputInstanceDto(); + + dto.id = historicDecisionOutputInstance.getId(); + dto.decisionInstanceId = historicDecisionOutputInstance.getDecisionInstanceId(); + dto.clauseId = historicDecisionOutputInstance.getClauseId(); + dto.clauseName = historicDecisionOutputInstance.getClauseName(); + dto.ruleId = historicDecisionOutputInstance.getRuleId(); + dto.ruleOrder = historicDecisionOutputInstance.getRuleOrder(); + dto.variableName = historicDecisionOutputInstance.getVariableName(); + dto.createTime = historicDecisionOutputInstance.getCreateTime(); + dto.removalTime = historicDecisionOutputInstance.getRemovalTime(); + dto.rootProcessInstanceId = historicDecisionOutputInstance.getRootProcessInstanceId(); + + if(historicDecisionOutputInstance.getErrorMessage() == null) { + VariableValueDto.fromTypedValue(dto, historicDecisionOutputInstance.getTypedValue()); + } + else { + dto.errorMessage = historicDecisionOutputInstance.getErrorMessage(); + dto.type = VariableValueDto.toRestApiTypeName(historicDecisionOutputInstance.getTypeName()); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDetailDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDetailDto.java new file mode 100644 index 0000000000000000000000000000000000000000..7fabc7cc30704755630f1762cc8f6031cb79deef --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDetailDto.java @@ -0,0 +1,160 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricDetail; +import org.camunda.bpm.engine.history.HistoricFormField; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonSubTypes.Type; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +/** + * @author Roman Smirnov + * + */ +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type" +) +@JsonSubTypes({ + @Type(value = HistoricFormFieldDto.class), + @Type(value = HistoricVariableUpdateDto.class) +}) +public abstract class HistoricDetailDto { + + protected String id; + protected String processDefinitionKey; + protected String processDefinitionId; + protected String processInstanceId; + protected String activityInstanceId; + protected String executionId; + protected String caseDefinitionKey; + protected String caseDefinitionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String taskId; + protected String tenantId; + protected String userOperationId; + protected Date time; + protected Date removalTime; + protected String rootProcessInstanceId; + + public String getId() { + return id; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getTaskId() { + return taskId; + } + + public String getTenantId() { + return tenantId; + } + + public String getUserOperationId() { + return userOperationId; + } + + public Date getTime() { + return time; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public static HistoricDetailDto fromHistoricDetail(HistoricDetail historicDetail) { + + HistoricDetailDto dto = null; + + if (historicDetail instanceof HistoricFormField) { + HistoricFormField historicFormField = (HistoricFormField) historicDetail; + dto = HistoricFormFieldDto.fromHistoricFormField(historicFormField); + + } else if (historicDetail instanceof HistoricVariableUpdate) { + HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail; + dto = HistoricVariableUpdateDto.fromHistoricVariableUpdate(historicVariableUpdate); + } + + fromHistoricDetail(historicDetail, dto); + return dto; + } + + protected static void fromHistoricDetail(HistoricDetail historicDetail, HistoricDetailDto dto) { + dto.id = historicDetail.getId(); + dto.processDefinitionKey = historicDetail.getProcessDefinitionKey(); + dto.processDefinitionId = historicDetail.getProcessDefinitionId(); + dto.processInstanceId = historicDetail.getProcessInstanceId(); + dto.activityInstanceId = historicDetail.getActivityInstanceId(); + dto.executionId = historicDetail.getExecutionId(); + dto.taskId = historicDetail.getTaskId(); + dto.caseDefinitionKey = historicDetail.getCaseDefinitionKey(); + dto.caseDefinitionId = historicDetail.getCaseDefinitionId(); + dto.caseInstanceId = historicDetail.getCaseInstanceId(); + dto.caseExecutionId = historicDetail.getCaseExecutionId(); + dto.tenantId = historicDetail.getTenantId(); + dto.userOperationId = historicDetail.getUserOperationId(); + dto.time = historicDetail.getTime(); + dto.removalTime = historicDetail.getRemovalTime(); + dto.rootProcessInstanceId = historicDetail.getRootProcessInstanceId(); + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDetailQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDetailQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..7a62e0fb0617d0f2acaba128873ec910c807b5af --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricDetailQueryDto.java @@ -0,0 +1,302 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricDetailQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.SortingDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import static java.lang.Boolean.TRUE; + +/** + * @author Roman Smirnov + * + */ +public class HistoricDetailQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_PROCESS_INSTANCE_ID = "processInstanceId"; + private static final String SORT_BY_VARIABLE_NAME = "variableName"; + private static final String SORT_BY_VARIABLE_TYPE = "variableType"; + private static final String SORT_BY_VARIABLE_REVISION = "variableRevision"; + private static final String SORT_BY_FORM_PROPERTY_ID = "formPropertyId"; + private static final String SORT_BY_TIME = "time"; + private static final String SORT_PARTIALLY_BY_OCCURENCE = "occurrence"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_VARIABLE_NAME); + VALID_SORT_BY_VALUES.add(SORT_BY_VARIABLE_TYPE); + VALID_SORT_BY_VALUES.add(SORT_BY_VARIABLE_REVISION); + VALID_SORT_BY_VALUES.add(SORT_BY_FORM_PROPERTY_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_TIME); + VALID_SORT_BY_VALUES.add(SORT_PARTIALLY_BY_OCCURENCE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String processInstanceId; + protected String executionId; + protected String activityInstanceId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String variableInstanceId; + protected String[] variableTypeIn; + protected String variableNameLike; + protected String taskId; + protected Boolean formFields; + protected Boolean variableUpdates; + protected Boolean excludeTaskDetails; + protected List tenantIds; + protected Boolean withoutTenantId; + protected String[] processInstanceIdIn; + protected String userOperationId; + private Date occurredBefore; + private Date occurredAfter; + protected Boolean initial; + + public HistoricDetailQueryDto() { + } + + public HistoricDetailQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam(value = "processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam(value = "executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam(value = "activityInstanceId") + public void setActivityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + } + + @CamundaQueryParam(value = "caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam(value = "caseExecutionId") + public void setCaseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + } + + @CamundaQueryParam(value = "variableInstanceId") + public void setVariableInstanceId(String variableInstanceId) { + this.variableInstanceId = variableInstanceId; + } + + @CamundaQueryParam(value="variableTypeIn", converter = StringArrayConverter.class) + public void setVariableTypeIn(String[] variableTypeIn) { + this.variableTypeIn = variableTypeIn; + } + + @CamundaQueryParam(value="variableNameLike") + public void setVariableNameLike(String variableNameLike) { + this.variableNameLike = variableNameLike; + } + + @CamundaQueryParam(value = "taskId") + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + @CamundaQueryParam(value = "formFields", converter = BooleanConverter.class) + public void setFormFields(Boolean formFields) { + this.formFields = formFields; + } + + @CamundaQueryParam(value = "variableUpdates", converter = BooleanConverter.class) + public void setVariableUpdates(Boolean variableUpdates) { + this.variableUpdates = variableUpdates; + } + + @CamundaQueryParam(value = "excludeTaskDetails", converter = BooleanConverter.class) + public void setExcludeTaskDetails(Boolean excludeTaskDetails) { + this.excludeTaskDetails = excludeTaskDetails; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value="processInstanceIdIn", converter = StringArrayConverter.class) + public void setProcessInstanceIdIn(String[] processInstanceIdIn) { + this.processInstanceIdIn = processInstanceIdIn; + } + + @CamundaQueryParam(value = "userOperationId") + public void setUserOperationId(String userOperationId) { + this.userOperationId = userOperationId; + } + + @CamundaQueryParam(value = "occurredBefore", converter = DateConverter.class) + public void setOccurredBefore(Date occurredBefore) { + this.occurredBefore = occurredBefore; + } + + @CamundaQueryParam(value = "occurredAfter", converter = DateConverter.class) + public void setOccurredAfter(Date occurredAfter) { + this.occurredAfter = occurredAfter; + } + + @CamundaQueryParam(value = "initial", converter = BooleanConverter.class) + public void setInitial(Boolean initial) { + this.initial = initial; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricDetailQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricDetailQuery(); + } + + @Override + protected boolean sortOptionsValid() { + if (sortings != null) { + for (SortingDto sorting : sortings) { + String sortingOrder = sorting.getSortOrder(); + String sortingBy = sorting.getSortBy(); + + if (!VALID_SORT_BY_VALUES.contains(sortingBy)) { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "sortBy parameter has invalid value: " + sortingBy); + } + + if (sortingBy == null || sortingOrder == null) { + return false; + } + } + } + + return super.sortOptionsValid(); + } + + @Override + protected void applyFilters(HistoricDetailQuery query) { + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (executionId != null) { + query.executionId(executionId); + } + if (activityInstanceId != null) { + query.activityInstanceId(activityInstanceId); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (caseExecutionId != null) { + query.caseExecutionId(caseExecutionId); + } + if (variableInstanceId != null) { + query.variableInstanceId(variableInstanceId); + } + if (variableTypeIn != null && variableTypeIn.length > 0) { + query.variableTypeIn(variableTypeIn); + } + if(variableNameLike != null) { + query.variableNameLike(variableNameLike); + } + if (taskId != null) { + query.taskId(taskId); + } + if (formFields != null) { + query.formFields(); + } + if (variableUpdates != null) { + query.variableUpdates(); + } + if (excludeTaskDetails != null) { + query.excludeTaskDetails(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (processInstanceIdIn != null && processInstanceIdIn.length > 0) { + query.processInstanceIdIn(processInstanceIdIn); + } + if (userOperationId != null) { + query.userOperationId(userOperationId); + } + if (occurredBefore != null) { + query.occurredBefore(occurredBefore); + } + if (occurredAfter != null) { + query.occurredAfter(occurredAfter); + } + if (TRUE.equals(initial)) { + query.initial(); + } + } + + @Override + protected void applySortBy(HistoricDetailQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_VARIABLE_NAME)) { + query.orderByVariableName(); + } else if (sortBy.equals(SORT_BY_VARIABLE_TYPE)) { + query.orderByVariableType(); + } else if (sortBy.equals(SORT_BY_VARIABLE_REVISION)) { + query.orderByVariableRevision(); + } else if (sortBy.equals(SORT_BY_FORM_PROPERTY_ID)) { + query.orderByFormPropertyId(); + } else if (sortBy.equals(SORT_BY_TIME)) { + query.orderByTime(); + } else if (sortBy.equals(SORT_PARTIALLY_BY_OCCURENCE)) { + query.orderPartiallyByOccurrence(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricExternalTaskLogDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricExternalTaskLogDto.java new file mode 100644 index 0000000000000000000000000000000000000000..286f2fb910ce6c514703daae4783ac847be7df92 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricExternalTaskLogDto.java @@ -0,0 +1,166 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricExternalTaskLog; + +import java.util.Date; + +public class HistoricExternalTaskLogDto { + + protected String id; + protected Date timestamp; + protected Date removalTime; + + protected String externalTaskId; + protected String topicName; + protected String workerId; + protected long priority; + protected Integer retries; + protected String errorMessage; + + protected String activityId; + protected String activityInstanceId; + protected String executionId; + + protected String processInstanceId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String tenantId; + protected String rootProcessInstanceId; + + protected boolean creationLog; + protected boolean failureLog; + protected boolean successLog; + protected boolean deletionLog; + + public String getId() { + return id; + } + + public Date getTimestamp() { + return timestamp; + } + + public String getExternalTaskId() { + return externalTaskId; + } + + public String getTopicName() { + return topicName; + } + + public String getWorkerId() { + return workerId; + } + + public long getPriority() { + return priority; + } + + public Integer getRetries() { + return retries; + } + + public String getErrorMessage() { + return errorMessage; + } + + public String getActivityId() { + return activityId; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getTenantId() { + return tenantId; + } + + public boolean isCreationLog() { + return creationLog; + } + + public boolean isFailureLog() { + return failureLog; + } + + public boolean isSuccessLog() { + return successLog; + } + + public boolean isDeletionLog() { + return deletionLog; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public static HistoricExternalTaskLogDto fromHistoricExternalTaskLog(HistoricExternalTaskLog historicExternalTaskLog) { + HistoricExternalTaskLogDto result = new HistoricExternalTaskLogDto(); + + result.id = historicExternalTaskLog.getId(); + result.timestamp = historicExternalTaskLog.getTimestamp(); + result.removalTime = historicExternalTaskLog.getRemovalTime(); + + result.externalTaskId = historicExternalTaskLog.getExternalTaskId(); + result.topicName = historicExternalTaskLog.getTopicName(); + result.workerId = historicExternalTaskLog.getWorkerId(); + result.priority = historicExternalTaskLog.getPriority(); + result.retries = historicExternalTaskLog.getRetries(); + result.errorMessage = historicExternalTaskLog.getErrorMessage(); + + result.activityId = historicExternalTaskLog.getActivityId(); + result.activityInstanceId = historicExternalTaskLog.getActivityInstanceId(); + result.executionId = historicExternalTaskLog.getExecutionId(); + + result.processInstanceId = historicExternalTaskLog.getProcessInstanceId(); + result.processDefinitionId = historicExternalTaskLog.getProcessDefinitionId(); + result.processDefinitionKey = historicExternalTaskLog.getProcessDefinitionKey(); + result.tenantId = historicExternalTaskLog.getTenantId(); + result.rootProcessInstanceId = historicExternalTaskLog.getRootProcessInstanceId(); + + result.creationLog = historicExternalTaskLog.isCreationLog(); + result.failureLog = historicExternalTaskLog.isFailureLog(); + result.successLog = historicExternalTaskLog.isSuccessLog(); + result.deletionLog = historicExternalTaskLog.isDeletionLog(); + + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricExternalTaskLogQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricExternalTaskLogQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ae8b5db74f29f727e7f9fa44f7d7918e2ee0b192 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricExternalTaskLogQueryDto.java @@ -0,0 +1,309 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricExternalTaskLogQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.LongConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import javax.ws.rs.core.MultivaluedMap; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class HistoricExternalTaskLogQueryDto extends AbstractQueryDto { + + protected static final String SORT_BY_TIMESTAMP = "timestamp"; + protected static final String SORT_BY_EXTERNAL_TASK_ID = "externalTaskId"; + protected static final String SORT_BY_RETRIES = "retries"; + protected static final String SORT_BY_PRIORITY = "priority"; + protected static final String SORT_BY_TOPIC_NAME = "topicName"; + protected static final String SORT_BY_WORKER_ID = "workerId"; + protected static final String SORT_BY_ACTIVITY_ID = "activityId"; + protected static final String SORT_BY_ACTIVITY_INSTANCE_ID = "activityInstanceId"; + protected static final String SORT_BY_EXECUTION_ID = "executionId"; + protected static final String SORT_BY_PROCESS_INSTANCE_ID = "processInstanceId"; + protected static final String SORT_BY_PROCESS_DEFINITION_ID = "processDefinitionId"; + protected static final String SORT_BY_PROCESS_DEFINITION_KEY = "processDefinitionKey"; + protected static final String SORT_BY_TENANT_ID = "tenantId"; + + protected static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + + VALID_SORT_BY_VALUES.add(SORT_BY_TIMESTAMP); + VALID_SORT_BY_VALUES.add(SORT_BY_EXTERNAL_TASK_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_RETRIES); + VALID_SORT_BY_VALUES.add(SORT_BY_PRIORITY); + VALID_SORT_BY_VALUES.add(SORT_BY_TOPIC_NAME); + VALID_SORT_BY_VALUES.add(SORT_BY_WORKER_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_INSTANCE_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_KEY); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String id; + protected String externalTaskId; + protected String topicName; + protected String workerId; + protected String errorMessage; + protected String[] activityIds; + protected String[] activityInstanceIds; + protected String[] executionIds; + protected String processInstanceId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected Long priorityHigherThanOrEquals; + protected Long priorityLowerThanOrEquals; + protected String[] tenantIds; + protected Boolean withoutTenantId; + protected Boolean creationLog; + protected Boolean failureLog; + protected Boolean successLog; + protected Boolean deletionLog; + + public HistoricExternalTaskLogQueryDto() {} + + public HistoricExternalTaskLogQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("logId") + public void setLogId(String id) { + this.id = id; + } + + @CamundaQueryParam("externalTaskId") + public void setExternalTaskId(String externalTaskId) { + this.externalTaskId = externalTaskId; + } + + @CamundaQueryParam("topicName") + public void setTopicName(String topicName) { + this.topicName = topicName; + } + + @CamundaQueryParam("workerId") + public void setWorkerId(String workerId) { + this.workerId = workerId; + } + + @CamundaQueryParam("errorMessage") + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + @CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class) + public void setActivityIdIn(String[] activityIds) { + this.activityIds = activityIds; + } + + @CamundaQueryParam(value="activityInstanceIdIn", converter = StringArrayConverter.class) + public void setActivityInstanceIdIn(String[] activityInstanceIds) { + this.activityInstanceIds = activityInstanceIds; + } + + @CamundaQueryParam(value="executionIdIn", converter = StringArrayConverter.class) + public void setExecutionIdIn(String[] executionIds) { + this.executionIds = executionIds; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam(value="priorityHigherThanOrEquals", converter = LongConverter.class) + public void setPriorityHigherThanOrEquals(Long priorityHigherThanOrEquals) { + this.priorityHigherThanOrEquals = priorityHigherThanOrEquals; + } + + @CamundaQueryParam(value="priorityLowerThanOrEquals", converter = LongConverter.class) + public void setPriorityLowerThanOrEquals(Long priorityLowerThanOrEquals) { + this.priorityLowerThanOrEquals = priorityLowerThanOrEquals; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringArrayConverter.class) + public void setTenantIdIn(String[] tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value="creationLog", converter = BooleanConverter.class) + public void setCreationLog(Boolean creationLog) { + this.creationLog = creationLog; + } + + @CamundaQueryParam(value="failureLog", converter = BooleanConverter.class) + public void setFailureLog(Boolean failureLog) { + this.failureLog = failureLog; + } + + @CamundaQueryParam(value="successLog", converter = BooleanConverter.class) + public void setSuccessLog(Boolean successLog) { + this.successLog = successLog; + } + + @CamundaQueryParam(value="deletionLog", converter = BooleanConverter.class) + public void setDeletionLog(Boolean deletionLog) { + this.deletionLog = deletionLog; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricExternalTaskLogQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricExternalTaskLogQuery(); + + } + + @Override + protected void applyFilters(HistoricExternalTaskLogQuery query) { + if (id != null) { + query.logId(id); + } + + if (externalTaskId != null) { + query.externalTaskId(externalTaskId); + } + + if (topicName != null) { + query.topicName(topicName); + } + + if (workerId != null) { + query.workerId(workerId); + } + + if (errorMessage != null) { + query.errorMessage(errorMessage); + } + + if (activityIds != null && activityIds.length > 0) { + query.activityIdIn(activityIds); + } + + if (activityInstanceIds != null && activityInstanceIds.length > 0) { + query.activityInstanceIdIn(activityInstanceIds); + } + + if (executionIds != null && executionIds.length > 0) { + query.executionIdIn(executionIds); + } + + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + + if (creationLog != null && creationLog) { + query.creationLog(); + } + + if (failureLog != null && failureLog) { + query.failureLog(); + } + + if (successLog != null && successLog) { + query.successLog(); + } + + if (deletionLog != null && deletionLog) { + query.deletionLog(); + } + + if (priorityHigherThanOrEquals != null) { + query.priorityHigherThanOrEquals(priorityHigherThanOrEquals); + } + + if (priorityLowerThanOrEquals != null) { + query.priorityLowerThanOrEquals(priorityLowerThanOrEquals); + } + if (tenantIds != null && tenantIds.length > 0) { + query.tenantIdIn(tenantIds); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + } + + @Override + protected void applySortBy(HistoricExternalTaskLogQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_TIMESTAMP)) { + query.orderByTimestamp(); + } else if (sortBy.equals(SORT_BY_EXTERNAL_TASK_ID)) { + query.orderByExternalTaskId(); + } else if (sortBy.equals(SORT_BY_RETRIES)) { + query.orderByRetries(); + } else if (sortBy.equals(SORT_BY_PRIORITY)) { + query.orderByPriority(); + } else if (sortBy.equals(SORT_BY_TOPIC_NAME)) { + query.orderByTopicName(); + } else if (sortBy.equals(SORT_BY_WORKER_ID)) { + query.orderByWorkerId(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { + query.orderByActivityId(); + }else if (sortBy.equals(SORT_BY_ACTIVITY_INSTANCE_ID)) { + query.orderByActivityInstanceId(); + } else if (sortBy.equals(SORT_BY_EXECUTION_ID)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricFormFieldDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricFormFieldDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bae7a585b0028a546e399f57267090fb852a089e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricFormFieldDto.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricFormField; + +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * @author Roman Smirnov + * + */ +@JsonTypeName("formField") +public class HistoricFormFieldDto extends HistoricDetailDto { + + protected String fieldId; + protected Object fieldValue; + + public String getFieldId() { + return fieldId; + } + + public Object getFieldValue() { + return fieldValue; + } + + public static HistoricFormFieldDto fromHistoricFormField(HistoricFormField historicFormField) { + + HistoricFormFieldDto dto = new HistoricFormFieldDto(); + + dto.fieldId = historicFormField.getFieldId(); + dto.fieldValue = historicFormField.getFieldValue(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIdentityLinkLogDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIdentityLinkLogDto.java new file mode 100644 index 0000000000000000000000000000000000000000..924ea07dfbb4cdf69809ee051445329d239cdfd3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIdentityLinkLogDto.java @@ -0,0 +1,112 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricIdentityLinkLog; + +import java.util.Date; + +public class HistoricIdentityLinkLogDto { + protected String id; + protected Date time; + protected String type; + protected String userId; + protected String groupId; + protected String taskId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String operationType; + protected String assignerId; + protected String tenantId; + protected Date removalTime; + protected String rootProcessInstanceId; + + public String getId() { + return id; + } + + public Date getTime() { + return time; + } + + public String getType() { + return type; + } + + public String getUserId() { + return userId; + } + + public String getGroupId() { + return groupId; + } + + public String getTaskId() { + return taskId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getOperationType() { + return operationType; + } + + public String getAssignerId() { + return assignerId; + } + + public String getTenantId() { + return tenantId; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public static HistoricIdentityLinkLogDto fromHistoricIdentityLink(HistoricIdentityLinkLog historicIdentityLink) { + HistoricIdentityLinkLogDto dto = new HistoricIdentityLinkLogDto(); + fromHistoricIdentityLink(dto, historicIdentityLink); + return dto; + } + + public static void fromHistoricIdentityLink(HistoricIdentityLinkLogDto dto, + HistoricIdentityLinkLog historicIdentityLink) { + dto.id = historicIdentityLink.getId(); + dto.assignerId = historicIdentityLink.getAssignerId(); + dto.groupId = historicIdentityLink.getGroupId(); + dto.operationType = historicIdentityLink.getOperationType(); + dto.taskId = historicIdentityLink.getTaskId(); + dto.time = historicIdentityLink.getTime(); + dto.type = historicIdentityLink.getType(); + dto.processDefinitionId = historicIdentityLink.getProcessDefinitionId(); + dto.processDefinitionKey = historicIdentityLink.getProcessDefinitionKey(); + dto.userId = historicIdentityLink.getUserId(); + dto.tenantId = historicIdentityLink.getTenantId(); + dto.removalTime = historicIdentityLink.getRemovalTime(); + dto.rootProcessInstanceId = historicIdentityLink.getRootProcessInstanceId(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIdentityLinkLogQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIdentityLinkLogQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..1c9f6ccbb6ef7932b590e47e0f8bc5ffe1799307 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIdentityLinkLogQueryDto.java @@ -0,0 +1,225 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricIdentityLinkLogQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * @author Deivarayan Azhagappan + * + */ +public class HistoricIdentityLinkLogQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_TIME = "time"; + private static final String SORT_BY_TYPE = "type"; + private static final String SORT_BY_USER_ID = "userId"; + private static final String SORT_BY_GROUP_ID = "groupId"; + private static final String SORT_BY_TASK_ID = "taskId"; + private static final String SORT_BY_PROCESS_DEFINITION_ID = "processDefinitionId"; + private static final String SORT_BY_PROCESS_DEFINITION_KEY = "processDefinitionKey"; + private static final String SORT_BY_OPERATION_TYPE = "operationType"; + private static final String SORT_BY_ASSIGNER_ID = "assignerId"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_TIME); + VALID_SORT_BY_VALUES.add(SORT_BY_TYPE); + VALID_SORT_BY_VALUES.add(SORT_BY_USER_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_GROUP_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_TASK_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_KEY); + VALID_SORT_BY_VALUES.add(SORT_BY_OPERATION_TYPE); + VALID_SORT_BY_VALUES.add(SORT_BY_ASSIGNER_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected Date dateBefore; + protected Date dateAfter; + protected String type; + protected String userId; + protected String groupId; + protected String taskId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String operationType; + protected String assignerId; + protected List tenantIds; + protected Boolean withoutTenantId; + + public HistoricIdentityLinkLogQueryDto() { + } + + public HistoricIdentityLinkLogQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricIdentityLinkLogQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricIdentityLinkLogQuery(); + } + + @CamundaQueryParam("type") + public void setType(String type) { + this.type = type; + } + + @CamundaQueryParam("userId") + public void setUserId(String userId) { + this.userId = userId; + } + + @CamundaQueryParam("groupId") + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + @CamundaQueryParam(value = "dateBefore", converter = DateConverter.class) + public void setDateBefore(Date dateBefore) { + this.dateBefore = dateBefore; + } + + @CamundaQueryParam(value = "dateAfter", converter = DateConverter.class) + public void setDateAfter(Date dateAfter) { + this.dateAfter = dateAfter; + } + + @CamundaQueryParam("taskId") + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("operationType") + public void setOperationType(String operationType) { + this.operationType = operationType; + } + + @CamundaQueryParam("assignerId") + public void setAssignerId(String assignerId) { + this.assignerId = assignerId; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @Override + protected void applyFilters(HistoricIdentityLinkLogQuery query) { + if (dateBefore != null) { + query.dateBefore(dateBefore); + } + if (dateAfter != null) { + query.dateAfter(dateAfter); + } + if (type != null) { + query.type(type); + } + if (userId != null) { + query.userId(userId); + } + if (groupId != null) { + query.groupId(groupId); + } + if (taskId != null) { + query.taskId(taskId); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (operationType != null) { + query.operationType(operationType); + } + if (assignerId != null) { + query.assignerId(assignerId); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + } + + @Override + protected void applySortBy(HistoricIdentityLinkLogQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_TIME)) { + query.orderByTime(); + } else if (sortBy.equals(SORT_BY_TYPE)) { + query.orderByType(); + } else if (sortBy.equals(SORT_BY_USER_ID)) { + query.orderByUserId(); + } else if (sortBy.equals(SORT_BY_GROUP_ID)) { + query.orderByGroupId(); + } else if (sortBy.equals(SORT_BY_TASK_ID)) { + query.orderByTaskId(); + } else if (sortBy.equals(SORT_BY_OPERATION_TYPE)) { + query.orderByOperationType(); + } else if (sortBy.equals(SORT_BY_ASSIGNER_ID)) { + query.orderByAssignerId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIncidentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIncidentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..1f2753b25fcedaa7cca64d4d76873d9a2e7b226c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIncidentDto.java @@ -0,0 +1,175 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricIncident; + +/** + * @author Roman Smirnov + * + */ +public class HistoricIncidentDto { + + protected String id; + protected String processDefinitionKey; + protected String processDefinitionId; + protected String processInstanceId; + protected String executionId; + protected String rootProcessInstanceId; + protected Date createTime; + protected Date endTime; + protected Date removalTime; + protected String incidentType; + protected String activityId; + protected String failedActivityId; + protected String causeIncidentId; + protected String rootCauseIncidentId; + protected String configuration; + protected String historyConfiguration; + protected String incidentMessage; + protected String tenantId; + protected String jobDefinitionId; + protected Boolean open; + protected Boolean deleted; + protected Boolean resolved; + protected String annotation; + + public String getId() { + return id; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public Date getCreateTime() { + return createTime; + } + + public Date getEndTime() { + return endTime; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getIncidentType() { + return incidentType; + } + + public String getActivityId() { + return activityId; + } + + public String getFailedActivityId() { + return failedActivityId; + } + + public String getCauseIncidentId() { + return causeIncidentId; + } + + public String getRootCauseIncidentId() { + return rootCauseIncidentId; + } + + public String getConfiguration() { + return configuration; + } + + public String getHistoryConfiguration() { + return historyConfiguration; + } + + public String getIncidentMessage() { + return incidentMessage; + } + + public String getTenantId() { + return tenantId; + } + + public String getJobDefinitionId() { + return jobDefinitionId; + } + + public Boolean isOpen() { + return open; + } + + public Boolean isDeleted() { + return deleted; + } + + public Boolean isResolved() { + return resolved; + } + + public String getAnnotation() { + return annotation; + } + + public static HistoricIncidentDto fromHistoricIncident(HistoricIncident historicIncident) { + HistoricIncidentDto dto = new HistoricIncidentDto(); + + dto.id = historicIncident.getId(); + dto.processDefinitionKey = historicIncident.getProcessDefinitionKey(); + dto.processDefinitionId = historicIncident.getProcessDefinitionId(); + dto.processInstanceId = historicIncident.getProcessInstanceId(); + dto.executionId = historicIncident.getExecutionId(); + dto.createTime = historicIncident.getCreateTime(); + dto.endTime = historicIncident.getEndTime(); + dto.incidentType = historicIncident.getIncidentType(); + dto.failedActivityId = historicIncident.getFailedActivityId(); + dto.activityId = historicIncident.getActivityId(); + dto.causeIncidentId = historicIncident.getCauseIncidentId(); + dto.rootCauseIncidentId = historicIncident.getRootCauseIncidentId(); + dto.configuration = historicIncident.getConfiguration(); + dto.historyConfiguration = historicIncident.getHistoryConfiguration(); + dto.incidentMessage = historicIncident.getIncidentMessage(); + dto.open = historicIncident.isOpen(); + dto.deleted = historicIncident.isDeleted(); + dto.resolved = historicIncident.isResolved(); + dto.tenantId = historicIncident.getTenantId(); + dto.jobDefinitionId = historicIncident.getJobDefinitionId(); + dto.removalTime = historicIncident.getRemovalTime(); + dto.rootProcessInstanceId = historicIncident.getRootProcessInstanceId(); + dto.annotation = historicIncident.getAnnotation(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIncidentQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIncidentQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2ec447cfc8adbb8996d4846454f77a14a5eb04ae --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricIncidentQueryDto.java @@ -0,0 +1,367 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Date; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricIncidentQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Roman Smirnov + * + */ +public class HistoricIncidentQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_INCIDENT_ID = "incidentId"; + private static final String SORT_BY_INCIDENT_MESSAGE = "incidentMessage"; + private static final String SORT_BY_CREATE_TIME = "createTime"; + private static final String SORT_BY_END_TIME = "endTime"; + private static final String SORT_BY_INCIDENT_TYPE = "incidentType"; + private static final String SORT_BY_EXECUTION_ID = "executionId"; + private static final String SORT_BY_ACTIVITY_ID = "activityId"; + private static final String SORT_BY_PROCESS_INSTANCE_ID = "processInstanceId"; + private static final String SORT_BY_PROCESS_DEFINITION_ID = "processDefinitionId"; + private static final String SORT_BY_PROCESS_DEFINITION_KEY = "processDefinitionKey"; + private static final String SORT_BY_CAUSE_INCIDENT_ID = "causeIncidentId"; + private static final String SORT_BY_ROOT_CAUSE_INCIDENT_ID = "rootCauseIncidentId"; + private static final String SORT_BY_CONFIGURATION = "configuration"; + private static final String SORT_BY_HISTORY_CONFIGURATION = "historyConfiguration"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + private static final String SORT_BY_INCIDENT_STATE = "incidentState"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_MESSAGE); + VALID_SORT_BY_VALUES.add(SORT_BY_CREATE_TIME); + VALID_SORT_BY_VALUES.add(SORT_BY_END_TIME); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_TYPE); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_KEY); + VALID_SORT_BY_VALUES.add(SORT_BY_CAUSE_INCIDENT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ROOT_CAUSE_INCIDENT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_CONFIGURATION); + VALID_SORT_BY_VALUES.add(SORT_BY_HISTORY_CONFIGURATION); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_STATE); + } + + protected String incidentId; + protected String incidentType; + protected String incidentMessage; + protected String incidentMessageLike; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String[] processDefinitionKeyIn; + protected String processInstanceId; + protected String executionId; + protected Date createTimeBefore; + protected Date createTimeAfter; + protected Date endTimeBefore; + protected Date endTimeAfter; + protected String activityId; + protected String failedActivityId; + protected String causeIncidentId; + protected String rootCauseIncidentId; + protected String configuration; + protected String historyConfiguration; + protected Boolean open; + protected Boolean resolved; + protected Boolean deleted; + protected List tenantIds; + protected Boolean withoutTenantId; + protected List jobDefinitionIds; + + + public HistoricIncidentQueryDto() {} + + public HistoricIncidentQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("incidentId") + public void setIncidentId(String incidentId) { + this.incidentId = incidentId; + } + + @CamundaQueryParam("incidentType") + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + @CamundaQueryParam("incidentMessage") + public void setIncidentMessage(String incidentMessage) { + this.incidentMessage = incidentMessage; + } + + @CamundaQueryParam("incidentMessageLike") + public void setIncidentMessageLike(String incidentMessageLike) { + this.incidentMessageLike = incidentMessageLike; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringArrayConverter.class) + public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) { + this.processDefinitionKeyIn = processDefinitionKeyIn; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam(value="createTimeBefore", converter= DateConverter.class) + public void setCreateTimeBefore(Date createTimeBefore) { + this.createTimeBefore = createTimeBefore; + } + + @CamundaQueryParam(value="createTimeAfter", converter= DateConverter.class) + public void setCreateTimeAfter(Date createTimeAfter) { + this.createTimeAfter = createTimeAfter; + } + + @CamundaQueryParam(value="endTimeBefore", converter= DateConverter.class) + public void setEndTimeBefore(Date endTimeBefore) { + this.endTimeBefore = endTimeBefore; + } + + @CamundaQueryParam(value="endTimeAfter", converter= DateConverter.class) + public void setEndTimeAfter(Date endTimeAfter) { + this.endTimeAfter = endTimeAfter; + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + @CamundaQueryParam("failedActivityId") + public void setFailedActivityId(String activityId) { + this.failedActivityId = activityId; + } + + @CamundaQueryParam("causeIncidentId") + public void setCauseIncidentId(String causeIncidentId) { + this.causeIncidentId = causeIncidentId; + } + + @CamundaQueryParam("rootCauseIncidentId") + public void setRootCauseIncidentId(String rootCauseIncidentId) { + this.rootCauseIncidentId = rootCauseIncidentId; + } + + @CamundaQueryParam("configuration") + public void setConfiguration(String configuration) { + this.configuration = configuration; + } + + @CamundaQueryParam("historyConfiguration") + public void setHistoryConfiguration(String historyConfiguration) { + this.historyConfiguration = historyConfiguration; + } + + @CamundaQueryParam(value = "open", converter = BooleanConverter.class) + public void setOpen(Boolean open) { + this.open = open; + } + + @CamundaQueryParam(value = "resolved", converter = BooleanConverter.class) + public void setResolved(Boolean resolved) { + this.resolved = resolved; + } + + @CamundaQueryParam(value = "deleted", converter = BooleanConverter.class) + public void setDeleted(Boolean deleted) { + this.deleted = deleted; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "jobDefinitionIdIn", converter = StringListConverter.class) + public void setJobDefinitionIdIn(List jobDefinitionIds) { + this.jobDefinitionIds = jobDefinitionIds; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricIncidentQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricIncidentQuery(); + } + + @Override + protected void applyFilters(HistoricIncidentQuery query) { + if (incidentId != null) { + query.incidentId(incidentId); + } + if (incidentType != null) { + query.incidentType(incidentType); + } + if (incidentMessage != null) { + query.incidentMessage(incidentMessage); + } + if (incidentMessageLike != null) { + query.incidentMessageLike(incidentMessageLike); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) { + query.processDefinitionKeyIn(processDefinitionKeyIn); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (executionId != null) { + query.executionId(executionId); + } + if (createTimeBefore != null) { + query.createTimeBefore(createTimeBefore); + } + if (createTimeAfter != null) { + query.createTimeAfter(createTimeAfter); + } + if (endTimeBefore != null) { + query.endTimeBefore(endTimeBefore); + } + if (endTimeAfter != null) { + query.endTimeAfter(endTimeAfter); + } + if (activityId != null) { + query.activityId(activityId); + } + if (failedActivityId != null) { + query.failedActivityId(failedActivityId); + } + if (causeIncidentId != null) { + query.causeIncidentId(causeIncidentId); + } + if (rootCauseIncidentId != null) { + query.rootCauseIncidentId(rootCauseIncidentId); + } + if (configuration != null) { + query.configuration(configuration); + } + if (historyConfiguration != null) { + query.historyConfiguration(historyConfiguration); + } + if (open != null) { + query.open(); + } + if (resolved != null && resolved) { + query.resolved(); + } + if (deleted != null && deleted) { + query.deleted(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (jobDefinitionIds != null && !jobDefinitionIds.isEmpty()) { + query.jobDefinitionIdIn(jobDefinitionIds.toArray(new String[jobDefinitionIds.size()])); + } + } + + @Override + protected void applySortBy(HistoricIncidentQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_INCIDENT_ID)) { + query.orderByIncidentId(); + } else if (sortBy.equals(SORT_BY_INCIDENT_MESSAGE)) { + query.orderByIncidentMessage(); + } else if (sortBy.equals(SORT_BY_CREATE_TIME)) { + query.orderByCreateTime(); + } else if (sortBy.equals(SORT_BY_END_TIME)) { + query.orderByEndTime(); + } else if (sortBy.equals(SORT_BY_INCIDENT_TYPE)) { + query.orderByIncidentType(); + } else if (sortBy.equals(SORT_BY_EXECUTION_ID)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { + query.orderByActivityId(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_CAUSE_INCIDENT_ID)) { + query.orderByCauseIncidentId(); + } else if (sortBy.equals(SORT_BY_ROOT_CAUSE_INCIDENT_ID)) { + query.orderByRootCauseIncidentId(); + } else if (sortBy.equals(SORT_BY_CONFIGURATION)) { + query.orderByConfiguration(); + } else if (sortBy.equals(SORT_BY_HISTORY_CONFIGURATION)) { + query.orderByHistoryConfiguration(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } else if (sortBy.equals(SORT_BY_INCIDENT_STATE)) { + query.orderByIncidentState(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricJobLogDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricJobLogDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b9bf50c4feb5f0b47bb19d41cf6bcb7b3654579b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricJobLogDto.java @@ -0,0 +1,201 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricJobLog; + +/** + * @author Roman Smirnov + * + */ +public class HistoricJobLogDto { + + protected String id; + protected Date timestamp; + protected Date removalTime; + + protected String jobId; + protected Date jobDueDate; + protected int jobRetries; + protected long jobPriority; + protected String jobExceptionMessage; + + protected String jobDefinitionId; + protected String jobDefinitionType; + protected String jobDefinitionConfiguration; + + protected String activityId; + protected String failedActivityId; + protected String executionId; + protected String processInstanceId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String deploymentId; + protected String tenantId; + protected String hostname; + protected String rootProcessInstanceId; + protected String batchId; + + protected boolean creationLog; + protected boolean failureLog; + protected boolean successLog; + protected boolean deletionLog; + + public String getId() { + return id; + } + + public Date getTimestamp() { + return timestamp; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getJobId() { + return jobId; + } + + public Date getJobDueDate() { + return jobDueDate; + } + + public int getJobRetries() { + return jobRetries; + } + + public long getJobPriority() { + return jobPriority; + } + + public String getJobExceptionMessage() { + return jobExceptionMessage; + } + + public String getJobDefinitionId() { + return jobDefinitionId; + } + + public String getJobDefinitionType() { + return jobDefinitionType; + } + + public String getJobDefinitionConfiguration() { + return jobDefinitionConfiguration; + } + + public String getActivityId() { + return activityId; + } + + public String getFailedActivityId() { + return failedActivityId; + } + + public String getExecutionId() { + return executionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getTenantId() { + return tenantId; + } + + public String getHostname() { + return hostname; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public String getBatchId() { + return batchId; + } + + public boolean isCreationLog() { + return creationLog; + } + + public boolean isFailureLog() { + return failureLog; + } + + public boolean isSuccessLog() { + return successLog; + } + + public boolean isDeletionLog() { + return deletionLog; + } + + public static HistoricJobLogDto fromHistoricJobLog(HistoricJobLog historicJobLog) { + HistoricJobLogDto result = new HistoricJobLogDto(); + + result.id = historicJobLog.getId(); + result.timestamp = historicJobLog.getTimestamp(); + result.removalTime = historicJobLog.getRemovalTime(); + + result.jobId = historicJobLog.getJobId(); + result.jobDueDate = historicJobLog.getJobDueDate(); + result.jobRetries = historicJobLog.getJobRetries(); + result.jobPriority = historicJobLog.getJobPriority(); + result.jobExceptionMessage = historicJobLog.getJobExceptionMessage(); + + result.jobDefinitionId = historicJobLog.getJobDefinitionId(); + result.jobDefinitionType = historicJobLog.getJobDefinitionType(); + result.jobDefinitionConfiguration = historicJobLog.getJobDefinitionConfiguration(); + + result.activityId = historicJobLog.getActivityId(); + result.failedActivityId = historicJobLog.getFailedActivityId(); + result.executionId = historicJobLog.getExecutionId(); + result.processInstanceId = historicJobLog.getProcessInstanceId(); + result.processDefinitionId = historicJobLog.getProcessDefinitionId(); + result.processDefinitionKey = historicJobLog.getProcessDefinitionKey(); + result.deploymentId = historicJobLog.getDeploymentId(); + result.tenantId = historicJobLog.getTenantId(); + result.hostname = historicJobLog.getHostname(); + result.rootProcessInstanceId = historicJobLog.getRootProcessInstanceId(); + result.batchId = historicJobLog.getBatchId(); + + result.creationLog = historicJobLog.isCreationLog(); + result.failureLog = historicJobLog.isFailureLog(); + result.successLog = historicJobLog.isSuccessLog(); + result.deletionLog = historicJobLog.isDeletionLog(); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricJobLogQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricJobLogQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..34497bb8a9e014522d5e52f0afe6ad008e4d2cd8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricJobLogQueryDto.java @@ -0,0 +1,353 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricJobLogQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.LongConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Roman Smirnov + * + */ +public class HistoricJobLogQueryDto extends AbstractQueryDto { + + protected static final String SORT_BY_TIMESTAMP = "timestamp"; + protected static final String SORT_BY_JOB_ID = "jobId"; + protected static final String SORT_BY_JOB_DUE_DATE = "jobDueDate"; + protected static final String SORT_BY_JOB_RETRIES = "jobRetries"; + protected static final String SORT_BY_JOB_PRIORITY = "jobPriority"; + protected static final String SORT_BY_JOB_DEFINITION_ID = "jobDefinitionId"; + protected static final String SORT_BY_ACTIVITY_ID = "activityId"; + protected static final String SORT_BY_EXECUTION_ID = "executionId"; + protected static final String SORT_BY_PROCESS_INSTANCE_ID = "processInstanceId"; + protected static final String SORT_BY_PROCESS_DEFINITION_ID = "processDefinitionId"; + protected static final String SORT_BY_PROCESS_DEFINITION_KEY = "processDefinitionKey"; + protected static final String SORT_BY_DEPLOYMENT_ID = "deploymentId"; + protected static final String SORT_PARTIALLY_BY_OCCURRENCE = "occurrence"; + protected static final String SORT_BY_TENANT_ID = "tenantId"; + protected static final String SORT_BY_HOSTNAME = "hostname"; + + protected static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + + VALID_SORT_BY_VALUES.add(SORT_BY_TIMESTAMP); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_DUE_DATE); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_RETRIES); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_PRIORITY); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_KEY); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOYMENT_ID); + VALID_SORT_BY_VALUES.add(SORT_PARTIALLY_BY_OCCURRENCE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_HOSTNAME); + } + + protected String id; + protected String jobId; + protected String jobExceptionMessage; + protected String jobDefinitionId; + protected String jobDefinitionType; + protected String jobDefinitionConfiguration; + protected String[] activityIds; + protected String[] failedActivityIds; + protected String[] executionIds; + protected String processInstanceId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String deploymentId; + protected Boolean creationLog; + protected Boolean failureLog; + protected Boolean successLog; + protected Boolean deletionLog; + protected Long jobPriorityHigherThanOrEquals; + protected Long jobPriorityLowerThanOrEquals; + protected List tenantIds; + protected Boolean withoutTenantId; + protected String hostname; + + public HistoricJobLogQueryDto() {} + + public HistoricJobLogQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("logId") + public void setLogId(String id) { + this.id = id; + } + + @CamundaQueryParam("jobId") + public void setJobId(String jobId) { + this.jobId = jobId; + } + + @CamundaQueryParam("jobExceptionMessage") + public void setJobExceptionMessage(String jobExceptionMessage) { + this.jobExceptionMessage = jobExceptionMessage; + } + + @CamundaQueryParam("jobDefinitionId") + public void setJobDefinitionId(String jobDefinitionId) { + this.jobDefinitionId = jobDefinitionId; + } + + @CamundaQueryParam("jobDefinitionType") + public void setJobDefinitionType(String jobDefinitionType) { + this.jobDefinitionType = jobDefinitionType; + } + + @CamundaQueryParam("jobDefinitionConfiguration") + public void setJobDefinitionConfiguration(String jobDefinitionConfiguration) { + this.jobDefinitionConfiguration = jobDefinitionConfiguration; + } + + @CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class) + public void setActivityIdIn(String[] activityIds) { + this.activityIds = activityIds; + } + + @CamundaQueryParam(value="failedActivityIdIn", converter = StringArrayConverter.class) + public void setFailedActivityIdIn(String[] activityIds) { + this.failedActivityIds = activityIds; + } + + @CamundaQueryParam(value="executionIdIn", converter = StringArrayConverter.class) + public void setExecutionIdIn(String[] executionIds) { + this.executionIds = executionIds; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + @CamundaQueryParam(value="creationLog", converter = BooleanConverter.class) + public void setCreationLog(Boolean creationLog) { + this.creationLog = creationLog; + } + + @CamundaQueryParam(value="failureLog", converter = BooleanConverter.class) + public void setFailureLog(Boolean failureLog) { + this.failureLog = failureLog; + } + + @CamundaQueryParam(value="successLog", converter = BooleanConverter.class) + public void setSuccessLog(Boolean successLog) { + this.successLog = successLog; + } + + @CamundaQueryParam(value="deletionLog", converter = BooleanConverter.class) + public void setDeletionLog(Boolean deletionLog) { + this.deletionLog = deletionLog; + } + + @CamundaQueryParam(value="jobPriorityHigherThanOrEquals", converter = LongConverter.class) + public void setJobPriorityHigherThanOrEquals(Long jobPriorityHigherThanOrEquals) { + this.jobPriorityHigherThanOrEquals = jobPriorityHigherThanOrEquals; + } + + @CamundaQueryParam(value="jobPriorityLowerThanOrEquals", converter = LongConverter.class) + public void setJobPriorityLowerThanOrEquals(Long jobPriorityLowerThanOrEquals) { + this.jobPriorityLowerThanOrEquals = jobPriorityLowerThanOrEquals; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "hostname") + public void setHostname(String hostname) { + this.hostname = hostname; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricJobLogQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricJobLogQuery(); + } + + @Override + protected void applyFilters(HistoricJobLogQuery query) { + if (id != null) { + query.logId(id); + } + + if (jobId != null) { + query.jobId(jobId); + } + + if (jobExceptionMessage != null) { + query.jobExceptionMessage(jobExceptionMessage); + } + + if (jobDefinitionId != null) { + query.jobDefinitionId(jobDefinitionId); + } + + if (jobDefinitionType != null) { + query.jobDefinitionType(jobDefinitionType); + } + + if (jobDefinitionConfiguration != null) { + query.jobDefinitionConfiguration(jobDefinitionConfiguration); + } + + if (activityIds != null && activityIds.length > 0) { + query.activityIdIn(activityIds); + } + + if (failedActivityIds != null && failedActivityIds.length > 0) { + query.failedActivityIdIn(failedActivityIds); + } + + if (executionIds != null && executionIds.length > 0) { + query.executionIdIn(executionIds); + } + + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + + if (deploymentId != null) { + query.deploymentId(deploymentId); + } + + if (creationLog != null && creationLog) { + query.creationLog(); + } + + if (failureLog != null && failureLog) { + query.failureLog(); + } + + if (successLog != null && successLog) { + query.successLog(); + } + + if (deletionLog != null && deletionLog) { + query.deletionLog(); + } + + if (jobPriorityLowerThanOrEquals != null) { + query.jobPriorityLowerThanOrEquals(jobPriorityLowerThanOrEquals); + } + + if (jobPriorityHigherThanOrEquals != null) { + query.jobPriorityHigherThanOrEquals(jobPriorityHigherThanOrEquals); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (hostname != null && !hostname.isEmpty()) { + query.hostname(hostname); + } + } + + @Override + protected void applySortBy(HistoricJobLogQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_TIMESTAMP)) { + query.orderByTimestamp(); + } else if (sortBy.equals(SORT_BY_JOB_ID)) { + query.orderByJobId(); + } else if (sortBy.equals(SORT_BY_JOB_DUE_DATE)) { + query.orderByJobDueDate(); + } else if (sortBy.equals(SORT_BY_JOB_RETRIES)) { + query.orderByJobRetries(); + } else if (sortBy.equals(SORT_BY_JOB_PRIORITY)) { + query.orderByJobPriority(); + } else if (sortBy.equals(SORT_BY_JOB_DEFINITION_ID)) { + query.orderByJobDefinitionId(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { + query.orderByActivityId(); + } else if (sortBy.equals(SORT_BY_EXECUTION_ID)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID)) { + query.orderByDeploymentId(); + } else if (sortBy.equals(SORT_PARTIALLY_BY_OCCURRENCE)) { + query.orderPartiallyByOccurrence(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } else if (sortBy.equals(SORT_BY_HOSTNAME)) { + query.orderByHostname(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..cf6e174a534d658fbf3156e83caf801bc3fb25b8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceDto.java @@ -0,0 +1,170 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; +import org.camunda.bpm.engine.history.HistoricProcessInstance; + +public class HistoricProcessInstanceDto { + + private String id; + private String businessKey; + private String processDefinitionId; + private String processDefinitionKey; + private String processDefinitionName; + private Integer processDefinitionVersion; + private Date startTime; + private Date endTime; + private Date removalTime; + private Long durationInMillis; + private String startUserId; + private String startActivityId; + private String deleteReason; + private String rootProcessInstanceId; + private String superProcessInstanceId; + private String superCaseInstanceId; + private String caseInstanceId; + private String tenantId; + private String state; + private String restartedProcessInstanceId; + + public String getId() { + return id; + } + + public String getBusinessKey() { + return businessKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionName() { + return processDefinitionName; + } + + public Integer getProcessDefinitionVersion() { + return processDefinitionVersion; + } + + public Date getStartTime() { + return startTime; + } + + public Date getEndTime() { + return endTime; + } + + public Long getDurationInMillis() { + return durationInMillis; + } + + public String getStartUserId() { + return startUserId; + } + + public String getStartActivityId() { + return startActivityId; + } + + public String getDeleteReason() { + return deleteReason; + } + + public String getSuperProcessInstanceId() { + return superProcessInstanceId; + } + + public String getSuperCaseInstanceId() { + return superCaseInstanceId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getTenantId() { + return tenantId; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public Date getRemovalTime() { + return removalTime; + } + + public void setRemovalTime(Date removalTime) { + this.removalTime = removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + + public String getRestartedProcessInstanceId() { + return restartedProcessInstanceId; + } + + public void setRestartedProcessInstanceId(String restartedProcessInstanceId) { + this.restartedProcessInstanceId = restartedProcessInstanceId; + } + + + public static HistoricProcessInstanceDto fromHistoricProcessInstance(HistoricProcessInstance historicProcessInstance) { + + HistoricProcessInstanceDto dto = new HistoricProcessInstanceDto(); + + dto.id = historicProcessInstance.getId(); + dto.businessKey = historicProcessInstance.getBusinessKey(); + dto.processDefinitionId = historicProcessInstance.getProcessDefinitionId(); + dto.processDefinitionKey = historicProcessInstance.getProcessDefinitionKey(); + dto.processDefinitionName = historicProcessInstance.getProcessDefinitionName(); + dto.processDefinitionVersion = historicProcessInstance.getProcessDefinitionVersion(); + dto.startTime = historicProcessInstance.getStartTime(); + dto.endTime = historicProcessInstance.getEndTime(); + dto.removalTime = historicProcessInstance.getRemovalTime(); + dto.durationInMillis = historicProcessInstance.getDurationInMillis(); + dto.startUserId = historicProcessInstance.getStartUserId(); + dto.startActivityId = historicProcessInstance.getStartActivityId(); + dto.deleteReason = historicProcessInstance.getDeleteReason(); + dto.rootProcessInstanceId = historicProcessInstance.getRootProcessInstanceId(); + dto.superProcessInstanceId = historicProcessInstance.getSuperProcessInstanceId(); + dto.superCaseInstanceId = historicProcessInstance.getSuperCaseInstanceId(); + dto.caseInstanceId = historicProcessInstance.getCaseInstanceId(); + dto.tenantId = historicProcessInstance.getTenantId(); + dto.state = historicProcessInstance.getState(); + dto.restartedProcessInstanceId = historicProcessInstance.getRestartedProcessInstanceId(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c9bbca59617c890d8c70bd6f19824825be576936 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceQueryDto.java @@ -0,0 +1,642 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringSetConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricProcessInstanceQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_PROCESS_INSTANCE_ID_VALUE = "instanceId"; + private static final String SORT_BY_PROCESS_DEFINITION_ID_VALUE = "definitionId"; + private static final String SORT_BY_PROCESS_INSTANCE_BUSINESS_KEY_VALUE = "businessKey"; + private static final String SORT_BY_PROCESS_INSTANCE_START_TIME_VALUE = "startTime"; + private static final String SORT_BY_PROCESS_INSTANCE_END_TIME_VALUE = "endTime"; + private static final String SORT_BY_PROCESS_INSTANCE_DURATION_VALUE = "duration"; + private static final String SORT_BY_PROCESS_DEFINITION_KEY_VALUE = "definitionKey"; + private static final String SORT_BY_PROCESS_DEFINITION_NAME_VALUE = "definitionName"; + private static final String SORT_BY_PROCESS_DEFINITION_VERSION_VALUE = "definitionVersion"; + + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_BUSINESS_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_START_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_END_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_DURATION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_VERSION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + private String processInstanceId; + private Set processInstanceIds; + private List processInstanceIdNotIn; + private String rootProcessInstanceId; + private String processDefinitionId; + private String processDefinitionKey; + private List processDefinitionKeys; + private String processDefinitionName; + private String processDefinitionNameLike; + private List processDefinitionKeyNotIn; + private String processInstanceBusinessKey; + private List processInstanceBusinessKeyIn; + private String processInstanceBusinessKeyLike; + private Boolean rootProcessInstances; + private Boolean finished; + private Boolean unfinished; + private Boolean withJobsRetrying; + private Boolean withIncidents; + private Boolean withRootIncidents; + private String incidentType; + private String incidentStatus; + private String incidentMessage; + private String incidentMessageLike; + private Date startedBefore; + private Date startedAfter; + private Date finishedBefore; + private Date finishedAfter; + private Date executedActivityAfter; + private Date executedActivityBefore; + private Date executedJobAfter; + private Date executedJobBefore; + private String startedBy; + private String superProcessInstanceId; + private String subProcessInstanceId; + private String superCaseInstanceId; + private String subCaseInstanceId; + private String caseInstanceId; + private List tenantIds; + private Boolean withoutTenantId; + private List executedActivityIdIn; + private List activeActivityIdIn; + private List activityIdIn; + private Boolean active; + private Boolean suspended; + private Boolean completed; + private Boolean externallyTerminated; + private Boolean internallyTerminated; + private List incidentIds; + + private List variables; + + protected Boolean variableNamesIgnoreCase; + protected Boolean variableValuesIgnoreCase; + + private List orQueries; + + public HistoricProcessInstanceQueryDto() {} + + public HistoricProcessInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("orQueries") + public void setOrQueries(List orQueries) { + this.orQueries = orQueries; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam(value = "processInstanceIds", converter = StringSetConverter.class) + public void setProcessInstanceIds(Set processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + @CamundaQueryParam(value = "processInstanceIdNotIn", converter = StringListConverter.class) + public void setProcessInstanceIdNotIn(List processInstanceIdNotIn) { + this.processInstanceIdNotIn = processInstanceIdNotIn; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + @CamundaQueryParam("rootProcessInstanceId") + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionName") + public void setProcessDefinitionName(String processDefinitionName) { + this.processDefinitionName = processDefinitionName; + } + + @CamundaQueryParam("processDefinitionNameLike") + public void setProcessDefinitionNameLike(String processDefinitionNameLike) { + this.processDefinitionNameLike = processDefinitionNameLike; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringListConverter.class) + public void setProcessDefinitionKeyIn(List processDefinitionKeys) { + this.processDefinitionKeys = processDefinitionKeys; + } + + @CamundaQueryParam(value = "processDefinitionKeyNotIn", converter = StringListConverter.class) + public void setProcessDefinitionKeyNotIn(List processDefinitionKeys) { + this.processDefinitionKeyNotIn = processDefinitionKeys; + } + + @CamundaQueryParam("processInstanceBusinessKey") + public void setProcessInstanceBusinessKey(String processInstanceBusinessKey) { + this.processInstanceBusinessKey = processInstanceBusinessKey; + } + + @CamundaQueryParam(value = "processInstanceBusinessKeyIn", converter = StringListConverter.class) + public void setProcessInstanceBusinessKeyIn(List processInstanceBusinessKeyIn) { + this.processInstanceBusinessKeyIn = processInstanceBusinessKeyIn; + } + + @CamundaQueryParam("processInstanceBusinessKeyLike") + public void setProcessInstanceBusinessKeyLike(String processInstanceBusinessKeyLike) { + this.processInstanceBusinessKeyLike = processInstanceBusinessKeyLike; + } + + @CamundaQueryParam(value = "rootProcessInstances", converter = BooleanConverter.class) + public void setRootProcessInstances(Boolean rootProcessInstances) { + this.rootProcessInstances = rootProcessInstances; + } + + @CamundaQueryParam(value = "finished", converter = BooleanConverter.class) + public void setFinished(Boolean finished) { + this.finished = finished; + } + + @CamundaQueryParam(value = "unfinished", converter = BooleanConverter.class) + public void setUnfinished(Boolean unfinished) { + this.unfinished = unfinished; + } + + @CamundaQueryParam(value = "withJobsRetrying", converter = BooleanConverter.class) + public void setWithJobsRetrying(Boolean withJobsRetrying) { + this.withJobsRetrying = withJobsRetrying; + } + + @CamundaQueryParam(value = "withIncidents", converter = BooleanConverter.class) + public void setWithIncidents(Boolean withIncidents) { + this.withIncidents = withIncidents; + } + + @CamundaQueryParam(value = "withRootIncidents", converter = BooleanConverter.class) + public void setWithRootIncidents(Boolean withRootIncidents) { + this.withRootIncidents = withRootIncidents; + } + + @CamundaQueryParam(value = "incidentStatus") + public void setIncidentStatus(String status) { + this.incidentStatus = status; + } + + @CamundaQueryParam(value = "incidentMessage") + public void setIncidentMessage(String incidentMessage) { + this.incidentMessage = incidentMessage; + } + + @CamundaQueryParam(value = "incidentMessageLike") + public void setIncidentMessageLike(String incidentMessageLike) { + this.incidentMessageLike = incidentMessageLike; + } + + @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) + public void setStartedBefore(Date startedBefore) { + this.startedBefore = startedBefore; + } + + @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) + public void setStartedAfter(Date startedAfter) { + this.startedAfter = startedAfter; + } + + @CamundaQueryParam(value = "finishedBefore", converter = DateConverter.class) + public void setFinishedBefore(Date finishedBefore) { + this.finishedBefore = finishedBefore; + } + + @CamundaQueryParam(value = "finishedAfter", converter = DateConverter.class) + public void setFinishedAfter(Date finishedAfter) { + this.finishedAfter = finishedAfter; + } + + @CamundaQueryParam("startedBy") + public void setStartedBy(String startedBy) { + this.startedBy = startedBy; + } + + @CamundaQueryParam("superProcessInstanceId") + public void setSuperProcessInstanceId(String superProcessInstanceId) { + this.superProcessInstanceId = superProcessInstanceId; + } + + @CamundaQueryParam("subProcessInstanceId") + public void setSubProcessInstanceId(String subProcessInstanceId) { + this.subProcessInstanceId = subProcessInstanceId; + } + + @CamundaQueryParam("superCaseInstanceId") + public void setSuperCaseInstanceId(String superCaseInstanceId) { + this.superCaseInstanceId = superCaseInstanceId; + } + + @CamundaQueryParam("subCaseInstanceId") + public void setSubCaseInstanceId(String subCaseInstanceId) { + this.subCaseInstanceId = subCaseInstanceId; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) + public void setVariables(List variables) { + this.variables = variables; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam(value = "variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + public String getIncidentType() { + return incidentType; + } + + @CamundaQueryParam(value = "incidentType") + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + @CamundaQueryParam(value = "incidentIdIn", converter = StringListConverter.class) + public void setIncidentIdIn(List incidentIds) { + this.incidentIds = incidentIds; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "executedActivityAfter", converter = DateConverter.class) + public void setExecutedActivityAfter(Date executedActivityAfter) { + this.executedActivityAfter = executedActivityAfter; + } + + @CamundaQueryParam(value = "executedActivityIdIn", converter = StringListConverter.class) + public void setExecutedActivityIdIn(List executedActivityIds) { + this.executedActivityIdIn = executedActivityIds; + } + + @CamundaQueryParam(value = "executedActivityBefore", converter = DateConverter.class) + public void setExecutedActivityBefore(Date executedActivityBefore) { + this.executedActivityBefore = executedActivityBefore; + } + + @CamundaQueryParam(value = "activeActivityIdIn", converter = StringListConverter.class) + public void setActiveActivityIdIn(List activeActivityIdIn) { + this.activeActivityIdIn = activeActivityIdIn; + } + + @CamundaQueryParam(value = "activityIdIn", converter = StringListConverter.class) + public void setActivityIdIn(List activityIdIn) { + this.activityIdIn = activityIdIn; + } + + @CamundaQueryParam(value = "executedJobAfter", converter = DateConverter.class) + public void setExecutedJobAfter(Date executedJobAfter) { + this.executedJobAfter = executedJobAfter; + } + + @CamundaQueryParam(value = "executedJobBefore", converter = DateConverter.class) + public void setExecutedJobBefore(Date executedJobBefore) { + this.executedJobBefore = executedJobBefore; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value = "completed", converter = BooleanConverter.class) + public void setCompleted(Boolean completed) { + this.completed = completed; + } + + @CamundaQueryParam(value = "externallyTerminated", converter = BooleanConverter.class) + public void setExternallyTerminated(Boolean externallyTerminated) { + this.externallyTerminated = externallyTerminated; + } + + @CamundaQueryParam(value = "internallyTerminated", converter = BooleanConverter.class) + public void setInternallyTerminated(Boolean internallyTerminated) { + this.internallyTerminated = internallyTerminated; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricProcessInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricProcessInstanceQuery(); + } + + public List getOrQueries() { + return orQueries; + } + + @Override + protected void applyFilters(HistoricProcessInstanceQuery query) { + if (orQueries != null) { + for (HistoricProcessInstanceQueryDto orQueryDto: orQueries) { + HistoricProcessInstanceQueryImpl orQuery = new HistoricProcessInstanceQueryImpl(); + orQuery.setOrQueryActive(); + orQueryDto.applyFilters(orQuery); + ((HistoricProcessInstanceQueryImpl) query).addOrQuery(orQuery); + } + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (processInstanceIds != null) { + query.processInstanceIds(processInstanceIds); + } + if (processInstanceIdNotIn != null && !processInstanceIdNotIn.isEmpty()) { + query.processInstanceIdNotIn(processInstanceIdNotIn.toArray(new String[0])); + } + if (rootProcessInstanceId != null) { + query.rootProcessInstanceId(rootProcessInstanceId); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processDefinitionKeys != null && !processDefinitionKeys.isEmpty()) { + query.processDefinitionKeyIn(processDefinitionKeys.toArray(new String[0])); + } + if (processDefinitionName != null) { + query.processDefinitionName(processDefinitionName); + } + if (processDefinitionNameLike != null) { + query.processDefinitionNameLike(processDefinitionNameLike); + } + if (processDefinitionKeyNotIn != null) { + query.processDefinitionKeyNotIn(processDefinitionKeyNotIn); + } + if (processInstanceBusinessKey != null) { + query.processInstanceBusinessKey(processInstanceBusinessKey); + } + if (processInstanceBusinessKeyIn != null && !processInstanceBusinessKeyIn.isEmpty()) { + query.processInstanceBusinessKeyIn(processInstanceBusinessKeyIn.toArray(new String[0])); + } + if (processInstanceBusinessKeyLike != null) { + query.processInstanceBusinessKeyLike(processInstanceBusinessKeyLike); + } + if (rootProcessInstances != null && rootProcessInstances) { + query.rootProcessInstances(); + } + if (finished != null && finished) { + query.finished(); + } + if (unfinished != null && unfinished) { + query.unfinished(); + } + if (withJobsRetrying != null && withJobsRetrying) { + query.withJobsRetrying(); + } + if (withIncidents != null && withIncidents) { + query.withIncidents(); + } + if (withRootIncidents != null && withRootIncidents) { + query.withRootIncidents(); + } + if (incidentIds != null && !incidentIds.isEmpty()) { + query.incidentIdIn(incidentIds.toArray(new String[0])); + } + if (incidentStatus != null) { + query.incidentStatus(incidentStatus); + } + if (incidentType != null) { + query.incidentType(incidentType); + } + if(incidentMessage != null) { + query.incidentMessage(incidentMessage); + } + if(incidentMessageLike != null) { + query.incidentMessageLike(incidentMessageLike); + } + if (startedBefore != null) { + query.startedBefore(startedBefore); + } + if (startedAfter != null) { + query.startedAfter(startedAfter); + } + if (finishedBefore != null) { + query.finishedBefore(finishedBefore); + } + if (finishedAfter != null) { + query.finishedAfter(finishedAfter); + } + if (startedBy != null) { + query.startedBy(startedBy); + } + if (superProcessInstanceId != null) { + query.superProcessInstanceId(superProcessInstanceId); + } + if (subProcessInstanceId != null) { + query.subProcessInstanceId(subProcessInstanceId); + } + if (superCaseInstanceId != null) { + query.superCaseInstanceId(superCaseInstanceId); + } + if (subCaseInstanceId != null) { + query.subCaseInstanceId(subCaseInstanceId); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[0])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if(TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + if(TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + if (variables != null) { + for (VariableQueryParameterDto variableQueryParam : variables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.variableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.variableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.variableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.variableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.variableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + + if (executedActivityAfter != null) { + query.executedActivityAfter(executedActivityAfter); + } + + if (executedActivityBefore != null) { + query.executedActivityBefore(executedActivityBefore); + } + + if (executedActivityIdIn != null && !executedActivityIdIn.isEmpty()) { + query.executedActivityIdIn(executedActivityIdIn.toArray(new String[0])); + } + + if (activeActivityIdIn != null && !activeActivityIdIn.isEmpty()) { + query.activeActivityIdIn(activeActivityIdIn.toArray(new String[0])); + } + + if(activityIdIn!= null && !activityIdIn.isEmpty()) { + query.activityIdIn(activityIdIn.toArray(new String[0])); + } + + if (executedJobAfter != null) { + query.executedJobAfter(executedJobAfter); + } + + if (executedJobBefore != null) { + query.executedJobBefore(executedJobBefore); + } + + if (active != null && active) { + query.active(); + } + if (suspended != null && suspended) { + query.suspended(); + } + if (completed != null && completed) { + query.completed(); + } + if (externallyTerminated != null && externallyTerminated) { + query.externallyTerminated(); + } + if (internallyTerminated != null && internallyTerminated) { + query.internallyTerminated(); + } + } + + @Override + protected void applySortBy(HistoricProcessInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID_VALUE)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID_VALUE)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY_VALUE)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_NAME_VALUE)) { + query.orderByProcessDefinitionName(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_VERSION_VALUE)) { + query.orderByProcessDefinitionVersion(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_BUSINESS_KEY_VALUE)) { + query.orderByProcessInstanceBusinessKey(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_START_TIME_VALUE)) { + query.orderByProcessInstanceStartTime(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_END_TIME_VALUE)) { + query.orderByProcessInstanceEndTime(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_DURATION_VALUE)) { + query.orderByProcessInstanceDuration(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c9086658f84fc66ab7bea72b84b0fe81469146f7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricProcessInstanceReportDto.java @@ -0,0 +1,104 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricProcessInstanceReport; +import org.camunda.bpm.engine.rest.dto.AbstractReportDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @author Roman Smirnov + * + */ +public class HistoricProcessInstanceReportDto extends AbstractReportDto { + + protected String[] processDefinitionIdIn; + protected String[] processDefinitionKeyIn; + protected Date startedAfter; + protected Date startedBefore; + + public static final String REPORT_TYPE_DURATION = "duration"; + + public static final List VALID_REPORT_TYPE_VALUES; + static { + VALID_REPORT_TYPE_VALUES = new ArrayList(); + VALID_REPORT_TYPE_VALUES.add(REPORT_TYPE_DURATION); + } + + public HistoricProcessInstanceReportDto() { + } + + public HistoricProcessInstanceReportDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam(value = "processDefinitionIdIn", converter = StringArrayConverter.class) + public void setProcessDefinitionIdIn(String[] processDefinitionIdIn) { + this.processDefinitionIdIn = processDefinitionIdIn; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringArrayConverter.class) + public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) { + this.processDefinitionKeyIn = processDefinitionKeyIn; + } + + @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) + public void setStartedAfter(Date startedAfter) { + this.startedAfter = startedAfter; + } + + @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) + public void setStartedBefore(Date startedBefore) { + this.startedBefore = startedBefore; + } + + @Override + protected HistoricProcessInstanceReport createNewReportQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricProcessInstanceReport(); + } + + @Override + protected void applyFilters(HistoricProcessInstanceReport reportQuery) { + if (processDefinitionIdIn != null && processDefinitionIdIn.length > 0) { + reportQuery.processDefinitionIdIn(processDefinitionIdIn); + } + if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) { + reportQuery.processDefinitionKeyIn(processDefinitionKeyIn); + } + if (startedAfter != null) { + reportQuery.startedAfter(startedAfter); + } + if (startedBefore != null) { + reportQuery.startedBefore(startedBefore); + } + if (!REPORT_TYPE_DURATION.equals(reportType)) { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Unknown report type " + reportType); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..da80d07b3ac99b20515c798c4dbcba7daf4e0330 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceDto.java @@ -0,0 +1,204 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricTaskInstance; + +/** + * @author Roman Smirnov + * + */ +public class HistoricTaskInstanceDto { + + protected String id; + protected String processDefinitionKey; + protected String processDefinitionId; + protected String processInstanceId; + protected String executionId; + protected String caseDefinitionKey; + protected String caseDefinitionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String activityInstanceId; + protected String name; + protected String description; + protected String deleteReason; + protected String owner; + protected String assignee; + protected Date startTime; + protected Date endTime; + protected Long duration; + protected String taskDefinitionKey; + protected int priority; + protected Date due; + protected String parentTaskId; + protected Date followUp; + private String tenantId; + protected Date removalTime; + protected String rootProcessInstanceId; + /** + * Returns task State of history tasks + */ + protected String taskState; + + public String getId() { + return id; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public String getDeleteReason() { + return deleteReason; + } + + public String getOwner() { + return owner; + } + + public String getAssignee() { + return assignee; + } + + public Date getStartTime() { + return startTime; + } + + public Date getEndTime() { + return endTime; + } + + public Long getDuration() { + return duration; + } + + public String getTaskDefinitionKey() { + return taskDefinitionKey; + } + + public int getPriority() { + return priority; + } + + public Date getDue() { + return due; + } + + public String getParentTaskId() { + return parentTaskId; + } + + public Date getFollowUp() { + return followUp; + } + + public String getTenantId() { + return tenantId; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + /** + * Returns task State of history tasks + */ + public String getTaskState() { return taskState; } + + public static HistoricTaskInstanceDto fromHistoricTaskInstance(HistoricTaskInstance taskInstance) { + + HistoricTaskInstanceDto dto = new HistoricTaskInstanceDto(); + + dto.id = taskInstance.getId(); + dto.processDefinitionKey = taskInstance.getProcessDefinitionKey(); + dto.processDefinitionId = taskInstance.getProcessDefinitionId(); + dto.processInstanceId = taskInstance.getProcessInstanceId(); + dto.executionId = taskInstance.getExecutionId(); + dto.caseDefinitionKey = taskInstance.getCaseDefinitionKey(); + dto.caseDefinitionId = taskInstance.getCaseDefinitionId(); + dto.caseInstanceId = taskInstance.getCaseInstanceId(); + dto.caseExecutionId = taskInstance.getCaseExecutionId(); + dto.activityInstanceId = taskInstance.getActivityInstanceId(); + dto.name = taskInstance.getName(); + dto.description = taskInstance.getDescription(); + dto.deleteReason = taskInstance.getDeleteReason(); + dto.owner = taskInstance.getOwner(); + dto.assignee = taskInstance.getAssignee(); + dto.startTime = taskInstance.getStartTime(); + dto.endTime = taskInstance.getEndTime(); + dto.duration = taskInstance.getDurationInMillis(); + dto.taskDefinitionKey = taskInstance.getTaskDefinitionKey(); + dto.priority = taskInstance.getPriority(); + dto.due = taskInstance.getDueDate(); + dto.parentTaskId = taskInstance.getParentTaskId(); + dto.followUp = taskInstance.getFollowUpDate(); + dto.tenantId = taskInstance.getTenantId(); + dto.removalTime = taskInstance.getRemovalTime(); + dto.rootProcessInstanceId = taskInstance.getRootProcessInstanceId(); + dto.taskState = taskInstance.getTaskState(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..73de0561763b6b6f98f5406c24250a1e68b937d6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceQueryDto.java @@ -0,0 +1,764 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; +import org.camunda.bpm.engine.impl.HistoricTaskInstanceQueryImpl; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Roman Smirnov + * + */ +public class HistoricTaskInstanceQueryDto extends AbstractQueryDto{ + + private static final String SORT_BY_TASK_ID= "taskId"; + private static final String SORT_BY_ACT_INSTANCE_ID = "activityInstanceId"; + private static final String SORT_BY_PROC_DEF_ID = "processDefinitionId"; + private static final String SORT_BY_PROC_INST_ID = "processInstanceId"; + private static final String SORT_BY_EXEC_ID = "executionId"; + private static final String SORT_BY_CASE_DEF_ID = "caseDefinitionId"; + private static final String SORT_BY_CASE_INST_ID = "caseInstanceId"; + private static final String SORT_BY_CASE_EXEC_ID = "caseExecutionId"; + private static final String SORT_BY_TASK_DURATION = "duration"; + private static final String SORT_BY_END_TIME = "endTime"; + private static final String SORT_BY_START_TIME = "startTime"; + private static final String SORT_BY_TASK_NAME = "taskName"; + private static final String SORT_BY_TASK_DESC = "taskDescription"; + private static final String SORT_BY_ASSIGNEE = "assignee"; + private static final String SORT_BY_OWNER = "owner"; + private static final String SORT_BY_DUE_DATE = "dueDate"; + private static final String SORT_BY_FOLLOW_UP_DATE = "followUpDate"; + private static final String SORT_BY_DELETE_REASON = "deleteReason"; + private static final String SORT_BY_TASK_DEF_KEY = "taskDefinitionKey"; + private static final String SORT_BY_PRIORITY = "priority"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_TASK_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ACT_INSTANCE_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROC_DEF_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROC_INST_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_EXEC_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_DEF_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INST_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_EXEC_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_TASK_DURATION); + VALID_SORT_BY_VALUES.add(SORT_BY_TASK_DURATION); + VALID_SORT_BY_VALUES.add(SORT_BY_END_TIME); + VALID_SORT_BY_VALUES.add(SORT_BY_START_TIME); + VALID_SORT_BY_VALUES.add(SORT_BY_TASK_NAME); + VALID_SORT_BY_VALUES.add(SORT_BY_TASK_DESC); + VALID_SORT_BY_VALUES.add(SORT_BY_ASSIGNEE); + VALID_SORT_BY_VALUES.add(SORT_BY_OWNER); + VALID_SORT_BY_VALUES.add(SORT_BY_DUE_DATE); + VALID_SORT_BY_VALUES.add(SORT_BY_FOLLOW_UP_DATE); + VALID_SORT_BY_VALUES.add(SORT_BY_DELETE_REASON); + VALID_SORT_BY_VALUES.add(SORT_BY_TASK_DEF_KEY); + VALID_SORT_BY_VALUES.add(SORT_BY_PRIORITY); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String taskId; + protected String taskParentTaskId; + protected String processInstanceId; + protected String rootProcessInstanceId; + protected String processInstanceBusinessKey; + protected String[] processInstanceBusinessKeyIn; + protected String processInstanceBusinessKeyLike; + protected String executionId; + protected String[] activityInstanceIdIn; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processDefinitionName; + protected String taskName; + protected String taskNameLike; + protected String taskDescription; + protected String taskDescriptionLike; + protected String taskDefinitionKey; + protected String[] taskDefinitionKeyIn; + protected String taskDeleteReason; + protected String taskDeleteReasonLike; + protected Boolean assigned; + protected Boolean unassigned; + protected String taskAssignee; + protected String taskAssigneeLike; + protected String taskOwner; + protected String taskOwnerLike; + protected Integer taskPriority; + protected Boolean finished; + protected Boolean unfinished; + protected Boolean processFinished; + protected Boolean processUnfinished; + protected Date taskDueDate; + protected Date taskDueDateBefore; + protected Date taskDueDateAfter; + protected Boolean withoutTaskDueDate; + protected Date taskFollowUpDate; + protected Date taskFollowUpDateBefore; + protected Date taskFollowUpDateAfter; + protected List tenantIds; + protected Boolean withoutTenantId; + + protected Date startedBefore; + protected Date startedAfter; + protected Date finishedBefore; + protected Date finishedAfter; + + protected String caseDefinitionId; + protected String caseDefinitionKey; + protected String caseDefinitionName; + protected String caseInstanceId; + protected String caseExecutionId; + protected String taskInvolvedUser; + protected String taskInvolvedGroup; + protected String taskHadCandidateUser; + protected String taskHadCandidateGroup; + protected Boolean withCandidateGroups; + protected Boolean withoutCandidateGroups; + protected List taskVariables; + protected List processVariables; + + protected Boolean variableValuesIgnoreCase; + protected Boolean variableNamesIgnoreCase; + + private List orQueries; + + public HistoricTaskInstanceQueryDto() {} + + public HistoricTaskInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("orQueries") + public void setOrQueries(List orQueries) { + this.orQueries = orQueries; + } + + @CamundaQueryParam("taskId") + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + @CamundaQueryParam("taskParentTaskId") + public void setTaskParentTaskId(String taskParentTaskId) { + this.taskParentTaskId = taskParentTaskId; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("rootProcessInstanceId") + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + + @CamundaQueryParam("processInstanceBusinessKey") + public void setProcessInstanceBusinessKey(String businessKey) { + this.processInstanceBusinessKey = businessKey; + } + + @CamundaQueryParam(value = "processInstanceBusinessKeyIn", converter = StringArrayConverter.class) + public void setProcessInstanceBusinessKeyIn(String[] processInstanceBusinessKeyIn) { + this.processInstanceBusinessKeyIn = processInstanceBusinessKeyIn; + } + + @CamundaQueryParam("processInstanceBusinessKeyLike") + public void setProcessInstanceBusinessKeyLike(String businessKeyLike) { + this.processInstanceBusinessKeyLike = businessKeyLike; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam(value="activityInstanceIdIn", converter=StringArrayConverter.class) + public void setActivityInstanceIdIn(String[] activityInstanceIdIn) { + this.activityInstanceIdIn = activityInstanceIdIn; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("processDefinitionName") + public void setProcessDefinitionName(String processDefinitionName) { + this.processDefinitionName = processDefinitionName; + } + + @CamundaQueryParam("taskName") + public void setTaskName(String taskName) { + this.taskName = taskName; + } + + @CamundaQueryParam("taskNameLike") + public void setTaskNameLike(String taskNameLike) { + this.taskNameLike = taskNameLike; + } + + @CamundaQueryParam("taskDescription") + public void setTaskDescription(String taskDescription) { + this.taskDescription = taskDescription; + } + + @CamundaQueryParam("taskDescriptionLike") + public void setTaskDescriptionLike(String taskDescriptionLike) { + this.taskDescriptionLike = taskDescriptionLike; + } + + @CamundaQueryParam("taskDefinitionKey") + public void setTaskDefinitionKey(String taskDefinitionKey) { + this.taskDefinitionKey = taskDefinitionKey; + } + + @CamundaQueryParam(value="taskDefinitionKeyIn", converter=StringArrayConverter.class) + public void setTaskDefinitionKeyIn(String[] taskDefinitionKeyIn) { + this.taskDefinitionKeyIn = taskDefinitionKeyIn; + } + + @CamundaQueryParam("taskDeleteReason") + public void setTaskDeleteReason(String taskDeleteReason) { + this.taskDeleteReason = taskDeleteReason; + } + + @CamundaQueryParam("taskDeleteReasonLike") + public void setTaskDeleteReasonLike(String taskDeleteReasonLike) { + this.taskDeleteReasonLike = taskDeleteReasonLike; + } + + @CamundaQueryParam(value="assigned", converter=BooleanConverter.class) + public void setAssigned(Boolean assigned) { + this.assigned = assigned; + } + + @CamundaQueryParam(value="unassigned", converter=BooleanConverter.class) + public void setUnassigned(Boolean unassigned) { + this.unassigned = unassigned; + } + + @CamundaQueryParam("taskAssignee") + public void setTaskAssignee(String taskAssignee) { + this.taskAssignee = taskAssignee; + } + + @CamundaQueryParam("taskAssigneeLike") + public void setTaskAssigneeLike(String taskAssigneeLike) { + this.taskAssigneeLike = taskAssigneeLike; + } + + @CamundaQueryParam("taskOwner") + public void setTaskOwner(String taskOwner) { + this.taskOwner = taskOwner; + } + + @CamundaQueryParam("taskOwnerLike") + public void setTaskOwnerLike(String taskOwnerLike) { + this.taskOwnerLike = taskOwnerLike; + } + + @CamundaQueryParam(value="taskPriority", converter=IntegerConverter.class) + public void setTaskPriority(Integer taskPriority) { + this.taskPriority = taskPriority; + } + + @CamundaQueryParam(value="finished", converter=BooleanConverter.class) + public void setFinished(Boolean finished) { + this.finished = finished; + } + + @CamundaQueryParam(value="unfinished", converter=BooleanConverter.class) + public void setUnfinished(Boolean unfinished) { + this.unfinished = unfinished; + } + + @CamundaQueryParam(value="processFinished", converter=BooleanConverter.class) + public void setProcessFinished(Boolean processFinished) { + this.processFinished = processFinished; + } + + @CamundaQueryParam(value="processUnfinished", converter=BooleanConverter.class) + public void setProcessUnfinished(Boolean processUnfinished) { + this.processUnfinished = processUnfinished; + } + + @CamundaQueryParam(value="taskDueDate", converter=DateConverter.class) + public void setTaskDueDate(Date taskDueDate) { + this.taskDueDate = taskDueDate; + } + + @CamundaQueryParam(value="taskDueDateBefore", converter=DateConverter.class) + public void setTaskDueDateBefore(Date taskDueDateBefore) { + this.taskDueDateBefore = taskDueDateBefore; + } + + @CamundaQueryParam(value="taskDueDateAfter", converter=DateConverter.class) + public void setTaskDueDateAfter(Date taskDueDateAfter) { + this.taskDueDateAfter = taskDueDateAfter; + } + + @CamundaQueryParam(value = "withoutTaskDueDate", converter = BooleanConverter.class) + public void setWithoutTaskDueDate(Boolean withoutTaskDueDate) { + this.withoutTaskDueDate = withoutTaskDueDate; + } + + @CamundaQueryParam(value="taskFollowUpDate", converter=DateConverter.class) + public void setTaskFollowUpDate(Date taskFollowUpDate) { + this.taskFollowUpDate = taskFollowUpDate; + } + + @CamundaQueryParam(value="taskFollowUpDateBefore", converter=DateConverter.class) + public void setTaskFollowUpDateBefore(Date taskFollowUpDateBefore) { + this.taskFollowUpDateBefore = taskFollowUpDateBefore; + } + + @CamundaQueryParam(value="taskFollowUpDateAfter", converter=DateConverter.class) + public void setTaskFollowUpDateAfter(Date taskFollowUpDateAfter) { + this.taskFollowUpDateAfter = taskFollowUpDateAfter; + } + + @CamundaQueryParam(value="taskVariables", converter = VariableListConverter.class) + public void setTaskVariables(List taskVariables) { + this.taskVariables = taskVariables; + } + + @CamundaQueryParam(value="processVariables", converter = VariableListConverter.class) + public void setProcessVariables(List processVariables) { + this.processVariables = processVariables; + } + + @CamundaQueryParam(value="variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + @CamundaQueryParam(value="variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("caseDefinitionKey") + public void setCaseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + } + + @CamundaQueryParam("caseDefinitionName") + public void setCaseDefinitionName(String caseDefinitionName) { + this.caseDefinitionName = caseDefinitionName; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam("caseExecutionId") + public void setCaseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam("taskInvolvedUser") + public void setTaskInvolvedUser(String taskInvolvedUser) { + this.taskInvolvedUser = taskInvolvedUser; + } + + @CamundaQueryParam("taskInvolvedGroup") + public void setTaskInvolvedGroup(String taskInvolvedGroup) { + this.taskInvolvedGroup = taskInvolvedGroup; + } + + @CamundaQueryParam("taskHadCandidateUser") + public void setTaskHadCandidateUser(String taskHadCandidateUser) { + this.taskHadCandidateUser = taskHadCandidateUser; + } + + @CamundaQueryParam("taskHadCandidateGroup") + public void setTaskHadCandidateGroup(String taskHadCandidateGroup) { + this.taskHadCandidateGroup = taskHadCandidateGroup; + } + + @CamundaQueryParam(value="withCandidateGroups", converter=BooleanConverter.class) + public void setWithCandidateGroups(Boolean withCandidateGroups) { + this.withCandidateGroups = withCandidateGroups; + } + + @CamundaQueryParam(value="withoutCandidateGroups", converter=BooleanConverter.class) + public void setWithoutCandidateGroups(Boolean withoutCandidateGroups) { + this.withoutCandidateGroups = withoutCandidateGroups; + } + + @CamundaQueryParam(value="startedBefore", converter=DateConverter.class) + public void setStartedBefore(Date startedBefore) { + this.startedBefore = startedBefore; + } + + @CamundaQueryParam(value="startedAfter", converter=DateConverter.class) + public void setStartedAfter(Date startedAfter) { + this.startedAfter = startedAfter; + } + + @CamundaQueryParam(value="finishedBefore", converter=DateConverter.class) + public void setFinishedBefore(Date finishedBefore) { + this.finishedBefore = finishedBefore; + } + + @CamundaQueryParam(value="finishedAfter", converter=DateConverter.class) + public void setFinishedAfter(Date finishedAfter) { + this.finishedAfter = finishedAfter; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricTaskInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricTaskInstanceQuery(); + } + + public List getOrQueries() { + return orQueries; + } + + @Override + protected void applyFilters(HistoricTaskInstanceQuery query) { + if (orQueries != null) { + for (HistoricTaskInstanceQueryDto orQueryDto: orQueries) { + HistoricTaskInstanceQueryImpl orQuery = new HistoricTaskInstanceQueryImpl(); + orQuery.setOrQueryActive(); + orQueryDto.applyFilters(orQuery); + ((HistoricTaskInstanceQueryImpl) query).addOrQuery(orQuery); + } + } + if (taskId != null) { + query.taskId(taskId); + } + if (taskParentTaskId != null) { + query.taskParentTaskId(taskParentTaskId); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (rootProcessInstanceId != null) { + query.rootProcessInstanceId(rootProcessInstanceId); + } + if (processInstanceBusinessKey != null) { + query.processInstanceBusinessKey(processInstanceBusinessKey); + } + if (processInstanceBusinessKeyIn != null && processInstanceBusinessKeyIn.length > 0) { + query.processInstanceBusinessKeyIn(processInstanceBusinessKeyIn); + } + if (processInstanceBusinessKeyLike != null) { + query.processInstanceBusinessKeyLike(processInstanceBusinessKeyLike); + } + if (executionId != null) { + query.executionId(executionId); + } + if (activityInstanceIdIn != null && activityInstanceIdIn.length > 0 ) { + query.activityInstanceIdIn(activityInstanceIdIn); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processDefinitionName != null) { + query.processDefinitionName(processDefinitionName); + } + if (taskName != null) { + query.taskName(taskName); + } + if (taskNameLike != null) { + query.taskNameLike(taskNameLike); + } + if (taskDescription != null) { + query.taskDescription(taskDescription); + } + if (taskDescriptionLike != null) { + query.taskDescriptionLike(taskDescriptionLike); + } + if (taskDefinitionKey != null) { + query.taskDefinitionKey(taskDefinitionKey); + } + if (taskDefinitionKeyIn != null && taskDefinitionKeyIn.length > 0) { + query.taskDefinitionKeyIn(taskDefinitionKeyIn); + } + if (taskDeleteReason != null) { + query.taskDeleteReason(taskDeleteReason); + } + if (taskDeleteReasonLike != null) { + query.taskDeleteReasonLike(taskDeleteReasonLike); + } + if (assigned != null) { + query.taskAssigned(); + } + if (unassigned != null) { + query.taskUnassigned(); + } + if (taskAssignee != null) { + query.taskAssignee(taskAssignee); + } + if (taskAssigneeLike != null) { + query.taskAssigneeLike(taskAssigneeLike); + } + if (taskOwner != null) { + query.taskOwner(taskOwner); + } + if (taskOwnerLike != null) { + query.taskOwnerLike(taskOwnerLike); + } + if (taskPriority != null) { + query.taskPriority(taskPriority); + } + if (finished != null) { + query.finished(); + } + if (unfinished != null) { + query.unfinished(); + } + if (processFinished != null) { + query.processFinished(); + } + if (processUnfinished != null) { + query.processUnfinished(); + } + if (taskDueDate != null) { + query.taskDueDate(taskDueDate); + } + if (taskDueDateBefore != null) { + query.taskDueBefore(taskDueDateBefore); + } + if (taskDueDateAfter != null) { + query.taskDueAfter(taskDueDateAfter); + } + if (TRUE.equals(withoutTaskDueDate)) { + query.withoutTaskDueDate(); + } + if (taskFollowUpDate != null) { + query.taskFollowUpDate(taskFollowUpDate); + } + if (taskFollowUpDateBefore != null) { + query.taskFollowUpBefore(taskFollowUpDateBefore); + } + if (taskFollowUpDateAfter != null) { + query.taskFollowUpAfter(taskFollowUpDateAfter); + } + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (caseDefinitionKey != null) { + query.caseDefinitionKey(caseDefinitionKey); + } + if (caseDefinitionName != null) { + query.caseDefinitionName(caseDefinitionName); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (caseExecutionId != null) { + query.caseExecutionId(caseExecutionId); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if(taskInvolvedUser != null){ + query.taskInvolvedUser(taskInvolvedUser); + } + if(taskInvolvedGroup != null){ + query.taskInvolvedGroup(taskInvolvedGroup); + } + if(taskHadCandidateUser != null){ + query.taskHadCandidateUser(taskHadCandidateUser); + } + if(taskHadCandidateGroup != null){ + query.taskHadCandidateGroup(taskHadCandidateGroup); + } + if (withCandidateGroups != null) { + query.withCandidateGroups(); + } + if (withoutCandidateGroups != null) { + query.withoutCandidateGroups(); + } + + if (finishedAfter != null) { + query.finishedAfter(finishedAfter); + } + + if (finishedBefore != null) { + query.finishedBefore(finishedBefore); + } + + if (startedAfter != null) { + query.startedAfter(startedAfter); + } + + if (startedBefore != null) { + query.startedBefore(startedBefore); + } + + if (TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + + if (TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + + if (taskVariables != null) { + for (VariableQueryParameterDto variableQueryParam : taskVariables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.taskVariableValueEquals(variableName, variableValue); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + + if (processVariables != null) { + for (VariableQueryParameterDto variableQueryParam : processVariables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.processVariableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.processVariableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.processVariableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.processVariableValueGreaterThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.processVariableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.processVariableValueLessThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.processVariableValueLike(variableName, String.valueOf(variableValue)); + } else if (op.equals(VariableQueryParameterDto.NOT_LIKE_OPERATOR_NAME)) { + query.processVariableValueNotLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid process variable comparator specified: " + op); + } + } + } + } + + @Override + protected void applySortBy(HistoricTaskInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_TASK_ID)) { + query.orderByTaskId(); + } else if (sortBy.equals(SORT_BY_ACT_INSTANCE_ID)) { + query.orderByHistoricActivityInstanceId(); + } else if (sortBy.equals(SORT_BY_PROC_DEF_ID)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_PROC_INST_ID)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_EXEC_ID)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_TASK_DURATION)) { + query.orderByHistoricTaskInstanceDuration(); + } else if (sortBy.equals(SORT_BY_END_TIME)) { + query.orderByHistoricTaskInstanceEndTime(); + } else if (sortBy.equals(SORT_BY_START_TIME)) { + query.orderByHistoricActivityInstanceStartTime(); + } else if (sortBy.equals(SORT_BY_TASK_NAME)) { + query.orderByTaskName(); + } else if (sortBy.equals(SORT_BY_TASK_DESC)) { + query.orderByTaskDescription(); + } else if (sortBy.equals(SORT_BY_ASSIGNEE)) { + query.orderByTaskAssignee(); + } else if (sortBy.equals(SORT_BY_OWNER)) { + query.orderByTaskOwner(); + } else if (sortBy.equals(SORT_BY_DUE_DATE)) { + query.orderByTaskDueDate(); + } else if (sortBy.equals(SORT_BY_FOLLOW_UP_DATE)) { + query.orderByTaskFollowUpDate(); + } else if (sortBy.equals(SORT_BY_DELETE_REASON)) { + query.orderByDeleteReason(); + } else if (sortBy.equals(SORT_BY_TASK_DEF_KEY)) { + query.orderByTaskDefinitionKey(); + } else if (sortBy.equals(SORT_BY_PRIORITY)) { + query.orderByTaskPriority(); + } else if (sortBy.equals(SORT_BY_CASE_DEF_ID)) { + query.orderByCaseDefinitionId(); + } else if (sortBy.equals(SORT_BY_CASE_INST_ID)) { + query.orderByCaseInstanceId(); + } else if (sortBy.equals(SORT_BY_CASE_EXEC_ID)) { + query.orderByCaseExecutionId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} + diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceReportQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceReportQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..13649b0a7086453e3bbf1e1d6ac67b0d906e97b1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceReportQueryDto.java @@ -0,0 +1,111 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricTaskInstanceReport; +import org.camunda.bpm.engine.history.HistoricTaskInstanceReportResult; +import org.camunda.bpm.engine.rest.dto.AbstractReportDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.util.Date; +import java.util.List; + +/** + * @author Stefan Hentschel. + */ +public class HistoricTaskInstanceReportQueryDto extends AbstractReportDto { + + public static final String PROCESS_DEFINITION = "processDefinition"; + public static final String TASK_NAME = "taskName"; + + protected Date completedBefore; + protected Date completedAfter; + protected String groupby; + + + public HistoricTaskInstanceReportQueryDto() {} + + public HistoricTaskInstanceReportQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + public Date getCompletedBefore() { + return completedBefore; + } + + public Date getCompletedAfter() { + return completedAfter; + } + + public String getGroupBy() { + return groupby; + } + + @CamundaQueryParam(value = "completedAfter", converter = DateConverter.class) + public void setCompletedAfter(Date completedAfter) { + this.completedAfter = completedAfter; + } + + @CamundaQueryParam(value = "completedBefore", converter = DateConverter.class) + public void setCompletedBefore(Date completedBefore) { + this.completedBefore = completedBefore; + } + + @CamundaQueryParam("groupBy") + public void setGroupBy(String groupby) { + this.groupby = groupby; + } + + protected void applyFilters(HistoricTaskInstanceReport reportQuery) { + if (completedBefore != null) { + reportQuery.completedBefore(completedBefore); + } + if (completedAfter != null) { + reportQuery.completedAfter(completedAfter); + } + + if(REPORT_TYPE_DURATION.equals(reportType)) { + if(periodUnit == null) { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "periodUnit is null"); + } + } + + } + + protected HistoricTaskInstanceReport createNewReportQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricTaskInstanceReport(); + } + + public List executeCompletedReport(ProcessEngine engine) { + HistoricTaskInstanceReport reportQuery = createNewReportQuery(engine); + applyFilters(reportQuery); + + if(PROCESS_DEFINITION.equals(groupby)) { + return reportQuery.countByProcessDefinitionKey(); + } else if( TASK_NAME.equals(groupby) ){ + return reportQuery.countByTaskName(); + } else { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupby); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceReportResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceReportResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..7ae6bdc725ca35c80f2dfbb59a46fcf9f7abbaa8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricTaskInstanceReportResultDto.java @@ -0,0 +1,93 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.HistoricTaskInstanceReportResult; + +/** + * @author Stefan Hentschel. + */ +public class HistoricTaskInstanceReportResultDto { + + protected Long count; + protected String processDefinitionKey; + protected String processDefinitionId; + protected String processDefinitionName; + protected String taskName; + protected String tenantId; + + public Long getCount() { + return count; + } + + public void setCount(Long count) { + this.count = count; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public String getProcessDefinitionName() { + return processDefinitionName; + } + + public void setProcessDefinitionName(String processDefinitionName) { + this.processDefinitionName = processDefinitionName; + } + + public String getTaskName() { + return taskName; + } + + public void setTaskName(String taskName) { + this.taskName = taskName; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public static HistoricTaskInstanceReportResultDto fromHistoricTaskInstanceReportResult(HistoricTaskInstanceReportResult taskReportResult) { + HistoricTaskInstanceReportResultDto dto = new HistoricTaskInstanceReportResultDto(); + + dto.count = taskReportResult.getCount(); + dto.processDefinitionKey = taskReportResult.getProcessDefinitionKey(); + dto.processDefinitionId = taskReportResult.getProcessDefinitionId(); + dto.processDefinitionName = taskReportResult.getProcessDefinitionName(); + dto.taskName = taskReportResult.getTaskName(); + dto.tenantId = taskReportResult.getTenantId(); + + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..13121bb4276a6caf1a0bd31d6e2acb61ca23cd4e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableInstanceDto.java @@ -0,0 +1,150 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +public class HistoricVariableInstanceDto extends VariableValueDto { + + private String id; + private String name; + private String processDefinitionKey; + private String processDefinitionId; + private String processInstanceId; + private String executionId; + private String activityInstanceId; + private String caseDefinitionKey; + private String caseDefinitionId; + private String caseInstanceId; + private String caseExecutionId; + private String taskId; + private String errorMessage; + private String tenantId; + private String state; + private Date createTime; + private Date removalTime; + private String rootProcessInstanceId; + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getTaskId() { + return taskId; + } + + public String getErrorMessage() { + return errorMessage; + } + + public String getTenantId() { + return tenantId; + } + + public String getState() { + return state; + } + + public Date getCreateTime() { + return createTime; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public static HistoricVariableInstanceDto fromHistoricVariableInstance(HistoricVariableInstance historicVariableInstance) { + + HistoricVariableInstanceDto dto = new HistoricVariableInstanceDto(); + + dto.id = historicVariableInstance.getId(); + dto.name = historicVariableInstance.getName(); + dto.processDefinitionKey = historicVariableInstance.getProcessDefinitionKey(); + dto.processDefinitionId = historicVariableInstance.getProcessDefinitionId(); + dto.processInstanceId = historicVariableInstance.getProcessInstanceId(); + dto.executionId = historicVariableInstance.getExecutionId(); + dto.activityInstanceId = historicVariableInstance.getActivityInstanceId(); + dto.caseDefinitionKey = historicVariableInstance.getCaseDefinitionKey(); + dto.caseDefinitionId = historicVariableInstance.getCaseDefinitionId(); + dto.caseInstanceId = historicVariableInstance.getCaseInstanceId(); + dto.caseExecutionId = historicVariableInstance.getCaseExecutionId(); + dto.taskId = historicVariableInstance.getTaskId(); + dto.tenantId = historicVariableInstance.getTenantId(); + dto.state = historicVariableInstance.getState(); + dto.createTime = historicVariableInstance.getCreateTime(); + dto.removalTime = historicVariableInstance.getRemovalTime(); + dto.rootProcessInstanceId = historicVariableInstance.getRootProcessInstanceId(); + + if(historicVariableInstance.getErrorMessage() == null) { + VariableValueDto.fromTypedValue(dto, historicVariableInstance.getTypedValue()); + } + else { + dto.errorMessage = historicVariableInstance.getErrorMessage(); + dto.type = VariableValueDto.toRestApiTypeName(historicVariableInstance.getTypeName()); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c14c4d57748f9763e606fb97eb12d46a33cf45e7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableInstanceQueryDto.java @@ -0,0 +1,274 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricVariableInstanceQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_PROCESS_INSTANCE_ID_VALUE = "instanceId"; + private static final String SORT_BY_VARIABLE_NAME_VALUE = "variableName"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_VARIABLE_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String processInstanceId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String caseInstanceId; + protected String variableName; + protected String variableNameLike; + protected Object variableValue; + protected Boolean variableValuesIgnoreCase; + protected Boolean variableNamesIgnoreCase; + protected String[] variableTypeIn; + protected String[] executionIdIn; + protected String[] taskIdIn; + protected String[] activityInstanceIdIn; + protected String[] caseExecutionIdIn; + protected String[] caseActivityIdIn; + protected String[] processInstanceIdIn; + protected List tenantIds; + protected Boolean withoutTenantId; + protected boolean includeDeleted; + protected String[] variableNameIn; + + public HistoricVariableInstanceQueryDto() { + } + + public HistoricVariableInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam("variableName") + public void setVariableName(String variableName) { + this.variableName = variableName; + } + + @CamundaQueryParam("variableNameLike") + public void setVariableNameLike(String variableNameLike) { + this.variableNameLike = variableNameLike; + } + + @CamundaQueryParam("variableValue") + public void setVariableValue(Object variableValue) { + this.variableValue = variableValue; + } + + @CamundaQueryParam(value="variableTypeIn", converter = StringArrayConverter.class) + public void setVariableTypeIn(String[] variableTypeIn) { + this.variableTypeIn = variableTypeIn; + } + + @CamundaQueryParam(value="variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + @CamundaQueryParam(value="variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam(value="executionIdIn", converter = StringArrayConverter.class) + public void setExecutionIdIn(String[] executionIdIn) { + this.executionIdIn = executionIdIn; + } + + @CamundaQueryParam(value="taskIdIn", converter = StringArrayConverter.class) + public void setTaskIdIn(String[] taskIdIn) { + this.taskIdIn = taskIdIn; + } + + @CamundaQueryParam(value="processInstanceIdIn", converter = StringArrayConverter.class) + public void setProcessInstanceIdIn(String[] processInstanceIdIn) { + this.processInstanceIdIn = processInstanceIdIn; + } + + @CamundaQueryParam(value="activityInstanceIdIn", converter = StringArrayConverter.class) + public void setActivityInstanceIdIn(String[] activityInstanceIdIn) { + this.activityInstanceIdIn = activityInstanceIdIn; + } + + @CamundaQueryParam(value="caseExecutionIdIn", converter = StringArrayConverter.class) + public void setCaseExecutionIdIn(String[] caseExecutionIdIn) { + this.caseExecutionIdIn = caseExecutionIdIn; + } + + @CamundaQueryParam(value="caseActivityIdIn", converter = StringArrayConverter.class) + public void setCaseActivityIdIn(String[] caseActivityIdIn) { + this.caseActivityIdIn = caseActivityIdIn; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + public boolean isIncludeDeleted() { + return includeDeleted; + } + + @CamundaQueryParam(value = "includeDeleted", converter = BooleanConverter.class) + public void setIncludeDeleted(boolean includeDeleted) { + this.includeDeleted = includeDeleted; + } + + @CamundaQueryParam(value = "variableNameIn", converter = StringArrayConverter.class) + public void setVariableNameIn(String[] variableNameIn) { + this.variableNameIn = variableNameIn; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected HistoricVariableInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricVariableInstanceQuery(); + } + + @Override + protected void applyFilters(HistoricVariableInstanceQuery query) { + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (variableName != null) { + query.variableName(variableName); + } + if (variableNameLike != null) { + query.variableNameLike(variableNameLike); + } + if (variableValue != null) { + if (variableName != null) { + query.variableValueEquals(variableName, variableValue); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, + "Only a single variable value parameter specified: variable name and value are required to be able to query after a specific variable value."); + } + } + if (variableTypeIn != null && variableTypeIn.length > 0) { + query.variableTypeIn(variableTypeIn); + } + if (TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + if (TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + if (executionIdIn != null && executionIdIn.length > 0) { + query.executionIdIn(executionIdIn); + } + if (taskIdIn != null && taskIdIn.length > 0) { + query.taskIdIn(taskIdIn); + } + if (processInstanceIdIn != null && processInstanceIdIn.length > 0) { + query.processInstanceIdIn(processInstanceIdIn); + } + if (activityInstanceIdIn != null && activityInstanceIdIn.length > 0) { + query.activityInstanceIdIn(activityInstanceIdIn); + } + if (caseExecutionIdIn != null && caseExecutionIdIn.length > 0) { + query.caseExecutionIdIn(caseExecutionIdIn); + } + if (caseActivityIdIn != null && caseActivityIdIn.length > 0) { + query.caseActivityIdIn(caseActivityIdIn); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (includeDeleted) { + query.includeDeleted(); + } + if (variableNameIn != null && variableNameIn.length > 0) { + query.variableNameIn(variableNameIn); + } + } + + @Override + protected void applySortBy(HistoricVariableInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID_VALUE)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_VARIABLE_NAME_VALUE)) { + query.orderByVariableName(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableUpdateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableUpdateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d09fdb0c8bc53b0fbc7d9eb9dd2cadb2e066d3c4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoricVariableUpdateDto.java @@ -0,0 +1,106 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Map; + +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * @author Roman Smirnov + * + */ +@JsonTypeName("variableUpdate") +public class HistoricVariableUpdateDto extends HistoricDetailDto { + + protected String variableName; + protected String variableInstanceId; + protected String variableType; + protected Object value; + protected Map valueInfo; + protected Boolean initial; + + protected int revision; + protected String errorMessage; + + public String getVariableName() { + return variableName; + } + + public String getVariableInstanceId() { + return variableInstanceId; + } + + public String getVariableType() { + return variableType; + } + + public Object getValue() { + return value; + } + + public Boolean getInitial() { + return initial; + } + + public int getRevision() { + return revision; + } + + public String getErrorMessage() { + return errorMessage; + } + + public Map getValueInfo() { + return valueInfo; + } + + public static HistoricVariableUpdateDto fromHistoricVariableUpdate(HistoricVariableUpdate historicVariableUpdate) { + + HistoricVariableUpdateDto dto = new HistoricVariableUpdateDto(); + fromHistoricVariableUpdate(dto, historicVariableUpdate); + return dto; + } + + protected static void fromHistoricVariableUpdate(HistoricVariableUpdateDto dto, + HistoricVariableUpdate historicVariableUpdate) { + dto.revision = historicVariableUpdate.getRevision(); + dto.variableName = historicVariableUpdate.getVariableName(); + dto.variableInstanceId = historicVariableUpdate.getVariableInstanceId(); + dto.initial = historicVariableUpdate.isInitial(); + + if (historicVariableUpdate.getErrorMessage() == null) { + try { + VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(historicVariableUpdate.getTypedValue()); + dto.value = variableValueDto.getValue(); + dto.variableType = variableValueDto.getType(); + dto.valueInfo = variableValueDto.getValueInfo(); + } catch (RuntimeException e) { + dto.errorMessage = e.getMessage(); + dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName()); + } + } + else { + dto.errorMessage = historicVariableUpdate.getErrorMessage(); + dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoryCleanupConfigurationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoryCleanupConfigurationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..75f38d13d7265e02a1bcec07ea12738fa4fe28e1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/HistoryCleanupConfigurationDto.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; + +public class HistoryCleanupConfigurationDto { + + protected Date batchWindowStartTime; + protected Date batchWindowEndTime; + protected boolean enabled; + + public Date getBatchWindowStartTime() { + return batchWindowStartTime; + } + + public void setBatchWindowStartTime(Date batchWindowStartTime) { + this.batchWindowStartTime = batchWindowStartTime; + } + + public Date getBatchWindowEndTime() { + return batchWindowEndTime; + } + + public void setBatchWindowEndTime(Date batchWindowEndTime) { + this.batchWindowEndTime = batchWindowEndTime; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/ReportResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/ReportResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c5495d8756c9a92313d9649f1a5c455835780ab0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/ReportResultDto.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.DurationReportResult; +import org.camunda.bpm.engine.history.ReportResult; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonSubTypes.Type; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +/** + * @author Roman Smirnov + * + */ +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type" +) +@JsonSubTypes({ + @Type(value = DurationReportResultDto.class) +}) +public abstract class ReportResultDto { + + protected int period; + protected String periodUnit; + + public int getPeriod() { + return period; + } + + public String getPeriodUnit() { + return periodUnit; + } + + public static ReportResultDto fromReportResult(ReportResult reportResult) { + + ReportResultDto dto = null; + + if (reportResult instanceof DurationReportResult) { + DurationReportResult durationReport = (DurationReportResult) reportResult; + dto = DurationReportResultDto.fromDurationReportResult(durationReport); + } + + dto.period = reportResult.getPeriod(); + dto.periodUnit = reportResult.getPeriodUnit().toString(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/UserOperationLogEntryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/UserOperationLogEntryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ffba244b198a5d698087293d61182b3f28d56ec2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/UserOperationLogEntryDto.java @@ -0,0 +1,202 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import org.camunda.bpm.engine.history.UserOperationLogEntry; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @author Danny Gräf + */ +public class UserOperationLogEntryDto { + + protected String id; + protected String deploymentId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processInstanceId; + protected String executionId; + protected String caseDefinitionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String taskId; + protected String jobId; + protected String jobDefinitionId; + protected String batchId; + protected String userId; + protected Date timestamp; + protected String operationId; + protected String externalTaskId; + protected String operationType; + protected String entityType; + protected String property; + protected String orgValue; + protected String newValue; + protected Date removalTime; + protected String rootProcessInstanceId; + protected String category; + protected String annotation; + + public static UserOperationLogEntryDto map(UserOperationLogEntry entry) { + UserOperationLogEntryDto dto = new UserOperationLogEntryDto(); + + dto.id = entry.getId(); + dto.deploymentId = entry.getDeploymentId(); + dto.processDefinitionId = entry.getProcessDefinitionId(); + dto.processDefinitionKey = entry.getProcessDefinitionKey(); + dto.processInstanceId = entry.getProcessInstanceId(); + dto.executionId = entry.getExecutionId(); + dto.caseDefinitionId = entry.getCaseDefinitionId(); + dto.caseInstanceId = entry.getCaseInstanceId(); + dto.caseExecutionId = entry.getCaseExecutionId(); + dto.taskId = entry.getTaskId(); + dto.jobId = entry.getJobId(); + dto.jobDefinitionId = entry.getJobDefinitionId(); + dto.batchId = entry.getBatchId(); + dto.userId = entry.getUserId(); + dto.timestamp = entry.getTimestamp(); + dto.operationId = entry.getOperationId(); + dto.externalTaskId = entry.getExternalTaskId(); + dto.operationType = entry.getOperationType(); + dto.entityType = entry.getEntityType(); + dto.property = entry.getProperty(); + dto.orgValue = entry.getOrgValue(); + dto.newValue = entry.getNewValue(); + dto.removalTime = entry.getRemovalTime(); + dto.rootProcessInstanceId = entry.getRootProcessInstanceId(); + dto.category = entry.getCategory(); + dto.annotation = entry.getAnnotation(); + + return dto; + } + + public static List map(List entries) { + List result = new ArrayList(); + for (UserOperationLogEntry entry : entries) { + result.add(map(entry)); + } + return result; + } + + public String getId() { + return id; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getTaskId() { + return taskId; + } + + public String getJobId() { + return jobId; + } + + public String getJobDefinitionId() { + return jobDefinitionId; + } + + public String getBatchId() { + return batchId; + } + + public String getUserId() { + return userId; + } + + public Date getTimestamp() { + return timestamp; + } + + public String getOperationId() { + return operationId; + } + + public String getExternalTaskId() { + return externalTaskId; + } + + public String getOperationType() { + return operationType; + } + + public String getEntityType() { + return entityType; + } + + public String getProperty() { + return property; + } + + public String getOrgValue() { + return orgValue; + } + + public String getNewValue() { + return newValue; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public String getCategory() { + return category; + } + + public String getAnnotation() { + return annotation; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/UserOperationLogQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/UserOperationLogQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..8c338aeaf9fe3b709e1f80549394c558e9911dbe --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/UserOperationLogQueryDto.java @@ -0,0 +1,273 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history; + +import java.util.Date; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.UserOperationLogQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Danny Gräf + */ +public class UserOperationLogQueryDto extends AbstractQueryDto { + + public static final String TIMESTAMP = "timestamp"; + + protected String deploymentId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processInstanceId; + protected String executionId; + protected String caseDefinitionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String taskId; + protected String jobId; + protected String jobDefinitionId; + protected String batchId; + protected String userId; + protected String operationId; + protected String externalTaskId; + protected String operationType; + protected String entityType; + protected String property; + protected String category; + protected Date afterTimestamp; + protected Date beforeTimestamp; + + protected String[] entityTypes; + protected String[] categories; + + public UserOperationLogQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @Override + protected boolean isValidSortByValue(String value) { + return TIMESTAMP.equals(value); + } + + @Override + protected UserOperationLogQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createUserOperationLogQuery(); + } + + @Override + protected void applyFilters(UserOperationLogQuery query) { + if (deploymentId != null) { + query.deploymentId(deploymentId); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (executionId != null) { + query.executionId(executionId); + } + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (caseExecutionId != null) { + query.caseExecutionId(caseExecutionId); + } + if (taskId != null) { + query.taskId(taskId); + } + if (jobId != null) { + query.jobId(jobId); + } + if (jobDefinitionId != null) { + query.jobDefinitionId(jobDefinitionId); + } + if (batchId != null) { + query.batchId(batchId); + } + if (userId != null) { + query.userId(userId); + } + if (operationId != null) { + query.operationId(operationId); + } + if (externalTaskId != null) { + query.externalTaskId(externalTaskId); + } + if (operationType != null) { + query.operationType(operationType); + } + if (entityType != null) { + query.entityType(entityType); + } + if (entityTypes != null) { + query.entityTypeIn(entityTypes); + } + if (category != null) { + query.category(category); + } + if (categories != null) { + query.categoryIn(categories); + } + if (property != null) { + query.property(property); + } + if (afterTimestamp != null) { + query.afterTimestamp(afterTimestamp); + } + if (beforeTimestamp != null) { + query.beforeTimestamp(beforeTimestamp); + } + } + + @Override + protected void applySortBy(UserOperationLogQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (TIMESTAMP.equals(sortBy)) { + query.orderByTimestamp(); + } + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam("caseExecutionId") + public void setCaseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + } + + @CamundaQueryParam("taskId") + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + @CamundaQueryParam("jobId") + public void setJobId(String jobId) { + this.jobId = jobId; + } + + @CamundaQueryParam("jobDefinitionId") + public void setJobDefinitionId(String jobDefinitionId) { + this.jobDefinitionId = jobDefinitionId; + } + + @CamundaQueryParam("batchId") + public void setBatchId(String batchId) { + this.batchId = batchId; + } + + @CamundaQueryParam("userId") + public void setUserId(String userId) { + this.userId = userId; + } + + @CamundaQueryParam("operationId") + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + @CamundaQueryParam("externalTaskId") + public void setExternalTaskId(String externalTaskId) { + this.externalTaskId = externalTaskId; + } + + @CamundaQueryParam("operationType") + public void setOperationType(String operationType) { + this.operationType = operationType; + } + + @CamundaQueryParam("entityType") + public void setEntityType(String entityType) { + this.entityType = entityType; + } + + @CamundaQueryParam(value = "entityTypeIn", converter = StringArrayConverter.class) + public void setEntityTypeIn(String[] entityTypes) { + this.entityTypes = entityTypes; + } + + @CamundaQueryParam("category") + public void setcategory(String category) { + this.category = category; + } + + @CamundaQueryParam(value = "categoryIn", converter = StringArrayConverter.class) + public void setCategoryIn(String[] categories) { + this.categories = categories; + } + + @CamundaQueryParam("property") + public void setProperty(String property) { + this.property = property; + } + + @CamundaQueryParam(value = "afterTimestamp", converter = DateConverter.class) + public void setAfterTimestamp(Date after) { + this.afterTimestamp = after; + } + + @CamundaQueryParam(value = "beforeTimestamp", converter = DateConverter.class) + public void setBeforeTimestamp(Date before) { + this.beforeTimestamp = before; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/CleanableHistoricBatchReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/CleanableHistoricBatchReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c68b509a921913e86cda50f41b32fac008b79ccb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/CleanableHistoricBatchReportDto.java @@ -0,0 +1,67 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricBatchReport; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CleanableHistoricBatchReportDto extends AbstractQueryDto { + + protected static final String SORT_BY_FINISHED_VALUE = "finished"; + + public static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_FINISHED_VALUE); + } + + public CleanableHistoricBatchReportDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected CleanableHistoricBatchReport createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createCleanableHistoricBatchReport(); + } + + @Override + protected void applyFilters(CleanableHistoricBatchReport query) { + } + + @Override + protected void applySortBy(CleanableHistoricBatchReport query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_FINISHED_VALUE)) { + query.orderByFinishedBatchOperation(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/CleanableHistoricBatchReportResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/CleanableHistoricBatchReportResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0ccd8ac4b3ca844c4551901a96226dce670921a3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/CleanableHistoricBatchReportResultDto.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricBatchReport; +import org.camunda.bpm.engine.history.CleanableHistoricBatchReportResult; + +public class CleanableHistoricBatchReportResultDto { + + protected String batchType; + protected Integer historyTimeToLive; + protected long finishedBatchesCount; + protected long cleanableBatchesCount; + + public String getBatchType() { + return batchType; + } + + public void setBatchType(String batchType) { + this.batchType = batchType; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public void setHistoryTimeToLive(Integer historyTimeToLive) { + this.historyTimeToLive = historyTimeToLive; + } + + public long getFinishedBatchesCount() { + return finishedBatchesCount; + } + + public void setFinishedBatchesCount(long finishedBatchCount) { + this.finishedBatchesCount = finishedBatchCount; + } + + public long getCleanableBatchesCount() { + return cleanableBatchesCount; + } + + public void setCleanableBatchesCount(long cleanableBatchCount) { + this.cleanableBatchesCount = cleanableBatchCount; + } + + protected CleanableHistoricBatchReport createNewReportQuery(ProcessEngine engine) { + return engine.getHistoryService().createCleanableHistoricBatchReport(); + } + public static List convert(List reportResult) { + List dtos = new ArrayList(); + for (CleanableHistoricBatchReportResult current : reportResult) { + CleanableHistoricBatchReportResultDto dto = new CleanableHistoricBatchReportResultDto(); + dto.setBatchType(current.getBatchType()); + dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); + dto.setFinishedBatchesCount(current.getFinishedBatchesCount()); + dto.setCleanableBatchesCount(current.getCleanableBatchesCount()); + dtos.add(dto); + } + return dtos; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/DeleteHistoricDecisionInstancesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/DeleteHistoricDecisionInstancesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..cae3aeb9924485fa819491221afb7adce1f8a950 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/DeleteHistoricDecisionInstancesDto.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch; + +import java.util.List; + +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceQueryDto; + +public class DeleteHistoricDecisionInstancesDto { + + protected List historicDecisionInstanceIds; + protected HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery; + protected String deleteReason; + + public List getHistoricDecisionInstanceIds() { + return historicDecisionInstanceIds; + } + + public void setHistoricDecisionInstanceIds(List historicDecisionInstanceIds) { + this.historicDecisionInstanceIds = historicDecisionInstanceIds; + } + + public HistoricDecisionInstanceQueryDto getHistoricDecisionInstanceQuery() { + return historicDecisionInstanceQuery; + } + + public void setHistoricDecisionInstanceQuery(HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery) { + this.historicDecisionInstanceQuery = historicDecisionInstanceQuery; + } + + public String getDeleteReason() { + return deleteReason; + } + + public void setDeleteReason(String deleteReason) { + this.deleteReason = deleteReason; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/HistoricBatchDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/HistoricBatchDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e590d1508d58bc57405fa16a1ef24dda2c27f34b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/HistoricBatchDto.java @@ -0,0 +1,119 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch; + +import java.util.Date; + +import org.camunda.bpm.engine.batch.history.HistoricBatch; + +public class HistoricBatchDto { + + protected String id; + protected String type; + protected int totalJobs; + protected int batchJobsPerSeed; + protected int invocationsPerBatchJob; + protected String seedJobDefinitionId; + protected String monitorJobDefinitionId; + protected String batchJobDefinitionId; + protected String tenantId; + protected String createUserId; + protected Date startTime; + protected Date endTime; + protected Date removalTime; + protected Date executionStartTime; + + public String getId() { + return id; + } + + public String getType() { + return type; + } + + public int getTotalJobs() { + return totalJobs; + } + + public int getBatchJobsPerSeed() { + return batchJobsPerSeed; + } + + public int getInvocationsPerBatchJob() { + return invocationsPerBatchJob; + } + + public String getSeedJobDefinitionId() { + return seedJobDefinitionId; + } + + public String getMonitorJobDefinitionId() { + return monitorJobDefinitionId; + } + + public String getBatchJobDefinitionId() { + return batchJobDefinitionId; + } + + public String getTenantId() { + return tenantId; + } + + public String getCreateUserId() { + return createUserId; + } + + public Date getStartTime() { + return startTime; + } + + public Date getEndTime() { + return endTime; + } + + public Date getRemovalTime() { + return removalTime; + } + + public Date getExecutionStartTime() { + return executionStartTime; + } + + public void setExecutionStartTime(final Date executionStartTime) { + this.executionStartTime = executionStartTime; + } + + public static HistoricBatchDto fromBatch(HistoricBatch historicBatch) { + HistoricBatchDto dto = new HistoricBatchDto(); + dto.id = historicBatch.getId(); + dto.type = historicBatch.getType(); + dto.totalJobs = historicBatch.getTotalJobs(); + dto.batchJobsPerSeed = historicBatch.getBatchJobsPerSeed(); + dto.invocationsPerBatchJob = historicBatch.getInvocationsPerBatchJob(); + dto.seedJobDefinitionId = historicBatch.getSeedJobDefinitionId(); + dto.monitorJobDefinitionId = historicBatch.getMonitorJobDefinitionId(); + dto.batchJobDefinitionId = historicBatch.getBatchJobDefinitionId(); + dto.tenantId = historicBatch.getTenantId(); + dto.createUserId = historicBatch.getCreateUserId(); + dto.startTime = historicBatch.getStartTime(); + dto.endTime = historicBatch.getEndTime(); + dto.removalTime = historicBatch.getRemovalTime(); + dto.executionStartTime = historicBatch.getExecutionStartTime(); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/HistoricBatchQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/HistoricBatchQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..84ef08e50251492fb93154b47391b7e38c0a4906 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/HistoricBatchQueryDto.java @@ -0,0 +1,129 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.history.HistoricBatchQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricBatchQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_BATCH_ID_VALUE = "batchId"; + private static final String SORT_BY_BATCH_START_TIME_VALUE = "startTime"; + private static final String SORT_BY_BATCH_END_TIME_VALUE = "endTime"; + private static final String SORT_BY_TENANT_ID_VALUE = "tenantId"; + + protected String batchId; + protected String type; + protected Boolean completed; + protected List tenantIds; + protected Boolean withoutTenantId; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_BATCH_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_BATCH_START_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_BATCH_END_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID_VALUE); + } + + public HistoricBatchQueryDto() { + } + + public HistoricBatchQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("batchId") + public void setBatchId(String batchId) { + this.batchId = batchId; + } + + @CamundaQueryParam("type") + public void setType(String type) { + this.type = type; + } + + @CamundaQueryParam(value = "completed", converter = BooleanConverter.class) + public void setCompleted(Boolean completed) { + this.completed = completed; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + protected HistoricBatchQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricBatchQuery(); + } + + protected void applyFilters(HistoricBatchQuery query) { + if (batchId != null) { + query.batchId(batchId); + } + if (type != null) { + query.type(type); + } + if (completed != null) { + query.completed(completed); + } + if (Boolean.TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + } + + protected void applySortBy(HistoricBatchQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { + query.orderById(); + } + if (sortBy.equals(SORT_BY_BATCH_START_TIME_VALUE)) { + query.orderByStartTime(); + } + if (sortBy.equals(SORT_BY_BATCH_END_TIME_VALUE)) { + query.orderByEndTime(); + } + if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/AbstractSetRemovalTimeDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/AbstractSetRemovalTimeDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4d238907785fb953e4c17004b4ff0051528402e3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/AbstractSetRemovalTimeDto.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch.removaltime; + +import java.util.Date; + +/** + * @author Tassilo Weidner + */ +public abstract class AbstractSetRemovalTimeDto { + + protected Date absoluteRemovalTime; + protected boolean clearedRemovalTime; + protected boolean calculatedRemovalTime; + + public Date getAbsoluteRemovalTime() { + return absoluteRemovalTime; + } + + public boolean isClearedRemovalTime() { + return clearedRemovalTime; + } + + public void setClearedRemovalTime(boolean clearedRemovalTime) { + this.clearedRemovalTime = clearedRemovalTime; + } + + public boolean isCalculatedRemovalTime() { + return calculatedRemovalTime; + } + + public void setCalculatedRemovalTime(boolean calculatedRemovalTime) { + this.calculatedRemovalTime = calculatedRemovalTime; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricBatchesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricBatchesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ee583811fda1891edf3ff4d690e5975d68e26c31 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricBatchesDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch.removaltime; + +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchQueryDto; + +/** + * @author Tassilo Weidner + */ +public class SetRemovalTimeToHistoricBatchesDto extends AbstractSetRemovalTimeDto { + + protected String[] historicBatchIds; + protected HistoricBatchQueryDto historicBatchQuery; + protected boolean hierarchical; + + public String[] getHistoricBatchIds() { + return historicBatchIds; + } + + public void setHistoricBatchIds(String[] historicBatchIds) { + this.historicBatchIds = historicBatchIds; + } + + public HistoricBatchQueryDto getHistoricBatchQuery() { + return historicBatchQuery; + } + + public void setHistoricBatchQuery(HistoricBatchQueryDto historicBatchQuery) { + this.historicBatchQuery = historicBatchQuery; + } + + public boolean isHierarchical() { + return hierarchical; + } + + public void setHierarchical(boolean hierarchical) { + this.hierarchical = hierarchical; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricDecisionInstancesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricDecisionInstancesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..1f3c2280750350067909735c05b7608cfefb0b0a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricDecisionInstancesDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch.removaltime; + +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceQueryDto; + +/** + * @author Tassilo Weidner + */ +public class SetRemovalTimeToHistoricDecisionInstancesDto extends AbstractSetRemovalTimeDto { + + protected String[] historicDecisionInstanceIds; + protected HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery; + protected boolean hierarchical; + + public String[] getHistoricDecisionInstanceIds() { + return historicDecisionInstanceIds; + } + + public void setHistoricDecisionInstanceIds(String[] historicDecisionInstanceIds) { + this.historicDecisionInstanceIds = historicDecisionInstanceIds; + } + + public HistoricDecisionInstanceQueryDto getHistoricDecisionInstanceQuery() { + return historicDecisionInstanceQuery; + } + + public void setHistoricDecisionInstanceQuery(HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery) { + this.historicDecisionInstanceQuery = historicDecisionInstanceQuery; + } + + public boolean isHierarchical() { + return hierarchical; + } + + public void setHierarchical(boolean hierarchical) { + this.hierarchical = hierarchical; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricProcessInstancesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricProcessInstancesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d7045a24a01de20a167342ef9973f12d2aa42ed6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/batch/removaltime/SetRemovalTimeToHistoricProcessInstancesDto.java @@ -0,0 +1,71 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.batch.removaltime; + +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; + +/** + * @author Tassilo Weidner + */ +public class SetRemovalTimeToHistoricProcessInstancesDto extends AbstractSetRemovalTimeDto { + + protected String[] historicProcessInstanceIds; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + protected boolean hierarchical; + protected boolean updateInChunks; + protected Integer updateChunkSize; + + public String[] getHistoricProcessInstanceIds() { + return historicProcessInstanceIds; + } + + public void setHistoricProcessInstanceIds(String[] historicProcessInstanceIds) { + this.historicProcessInstanceIds = historicProcessInstanceIds; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } + + public boolean isHierarchical() { + return hierarchical; + } + + public void setHierarchical(boolean hierarchical) { + this.hierarchical = hierarchical; + } + + public boolean isUpdateInChunks() { + return updateInChunks; + } + + public void setUpdateInChunks(boolean updateInChunks) { + this.updateInChunks = updateInChunks; + } + + public Integer getUpdateChunkSize() { + return updateChunkSize; + } + + public void setUpdateChunkSize(Integer updateChunkSize) { + this.updateChunkSize = updateChunkSize; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricActivityInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricActivityInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0fa17601d6689a10b6b92a353e05e09d9774c241 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricActivityInstanceDto.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.optimize; + +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.impl.history.event.HistoryEvent; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityInstanceDto; + +public class OptimizeHistoricActivityInstanceDto extends HistoricActivityInstanceDto { + + private long sequenceCounter; + + public long getSequenceCounter() { + return sequenceCounter; + } + + public static OptimizeHistoricActivityInstanceDto fromHistoricActivityInstance(HistoricActivityInstance historicActivityInstance) { + OptimizeHistoricActivityInstanceDto dto = new OptimizeHistoricActivityInstanceDto(); + HistoricActivityInstanceDto.fromHistoricActivityInstance(dto, historicActivityInstance); + + if (historicActivityInstance instanceof HistoryEvent) { + HistoryEvent historyEvent = (HistoryEvent) historicActivityInstance; + dto.sequenceCounter = historyEvent.getSequenceCounter(); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricIdentityLinkLogDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricIdentityLinkLogDto.java new file mode 100644 index 0000000000000000000000000000000000000000..3a46d72d6223dd76f3baef45511ab5076d1d4c60 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricIdentityLinkLogDto.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.optimize; + +import org.camunda.bpm.engine.impl.persistence.entity.optimize.OptimizeHistoricIdentityLinkLogEntity; +import org.camunda.bpm.engine.rest.dto.history.HistoricIdentityLinkLogDto; + +public class OptimizeHistoricIdentityLinkLogDto extends HistoricIdentityLinkLogDto { + + protected String processInstanceId; + + public String getProcessInstanceId() { + return processInstanceId; + } + + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + + public static OptimizeHistoricIdentityLinkLogDto fromHistoricIdentityLink(OptimizeHistoricIdentityLinkLogEntity historicIdentityLink) { + OptimizeHistoricIdentityLinkLogDto dto = new OptimizeHistoricIdentityLinkLogDto(); + HistoricIdentityLinkLogDto.fromHistoricIdentityLink(dto, historicIdentityLink); + dto.setProcessInstanceId(historicIdentityLink.getProcessInstanceId()); + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricVariableUpdateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricVariableUpdateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b27505cf6b7f3f3a47a44411f5b9d0db0b184825 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/history/optimize/OptimizeHistoricVariableUpdateDto.java @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.history.optimize; + +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.impl.history.event.HistoryEvent; +import org.camunda.bpm.engine.rest.dto.history.HistoricVariableUpdateDto; + +public class OptimizeHistoricVariableUpdateDto extends HistoricVariableUpdateDto { + + protected long sequenceCounter; + + public long getSequenceCounter() { + return sequenceCounter; + } + + public void setSequenceCounter(long sequenceCounter) { + this.sequenceCounter = sequenceCounter; + } + + public static OptimizeHistoricVariableUpdateDto fromHistoricVariableUpdate(HistoricVariableUpdate historicVariableUpdate) { + OptimizeHistoricVariableUpdateDto dto = new OptimizeHistoricVariableUpdateDto(); + fromHistoricVariableUpdate(dto, historicVariableUpdate); + fromHistoricDetail(historicVariableUpdate, dto); + if (historicVariableUpdate instanceof HistoryEvent) { + HistoryEvent historyEvent = (HistoryEvent) historicVariableUpdate; + dto.setSequenceCounter(historyEvent.getSequenceCounter()); + } + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/BasicUserCredentialsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/BasicUserCredentialsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d319b414b459a0f57531582162da6000af37e240 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/BasicUserCredentialsDto.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +/** + * Represent username\password pair for user verification + * + * @author Askar Akhmerov + */ +public class BasicUserCredentialsDto extends UserCredentialsDto { + + protected String username; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/CheckPasswordPolicyResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/CheckPasswordPolicyResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..17052bda7898789428e2546552a7195c20ba9c7f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/CheckPasswordPolicyResultDto.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import org.camunda.bpm.engine.identity.PasswordPolicyResult; +import org.camunda.bpm.engine.identity.PasswordPolicyRule; + +/** + * @author Miklas Boskamp + * + */ +public class CheckPasswordPolicyResultDto extends PasswordPolicyDto { + + protected boolean valid = true; + + public static CheckPasswordPolicyResultDto fromPasswordPolicyResult(PasswordPolicyResult result) { + CheckPasswordPolicyResultDto dto = new CheckPasswordPolicyResultDto(); + for (PasswordPolicyRule rule : result.getFulfilledRules()) { + dto.rules.add(new CheckPasswordPolicyRuleDto(rule, true)); + } + if(result.getViolatedRules().size() > 0) { + dto.valid = false; + for (PasswordPolicyRule rule : result.getViolatedRules()) { + dto.rules.add(new CheckPasswordPolicyRuleDto(rule, false)); + } + } + return dto; + } + + public boolean isValid() { + return valid; + } + + public void setValid(boolean valid) { + this.valid = valid; + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/CheckPasswordPolicyRuleDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/CheckPasswordPolicyRuleDto.java new file mode 100644 index 0000000000000000000000000000000000000000..624fcf9058988e553ebf33e477425ee09bf51574 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/CheckPasswordPolicyRuleDto.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import org.camunda.bpm.engine.identity.PasswordPolicyRule; + +/** + * @author Tassilo Weidner + */ +public class CheckPasswordPolicyRuleDto extends PasswordPolicyRuleDto { + + protected boolean valid; + + public CheckPasswordPolicyRuleDto(PasswordPolicyRule rule, boolean valid) { + super(rule); + this.valid = valid; + } + + public boolean isValid() { + return valid; + } + + public void setValid(boolean valid) { + this.valid = valid; + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/GroupDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/GroupDto.java new file mode 100644 index 0000000000000000000000000000000000000000..84a9400b3928adcb5e9174c39f6942ed4268582f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/GroupDto.java @@ -0,0 +1,79 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import org.camunda.bpm.engine.identity.Group; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Daniel Meyer + * + */ +public class GroupDto { + + protected String id; + protected String name; + protected String type; + + // Transformers //////////////////////////////// + + public static GroupDto fromGroup(Group dbGroup) { + GroupDto groupDto = new GroupDto(); + groupDto.setId(dbGroup.getId()); + groupDto.setName(dbGroup.getName()); + groupDto.setType(dbGroup.getType()); + return groupDto; + } + + public void update(Group dbGroup) { + dbGroup.setId(id); + dbGroup.setName(name); + dbGroup.setType(type); + } + + public static List fromGroupList(List dbGroupList) { + List resultList = new ArrayList(); + for (Group group : dbGroupList) { + resultList.add(fromGroup(group)); + } + return resultList; + } + + // Getters / Setters /////////////////////////// + + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/GroupQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/GroupQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9728ce30dac1fc56f2bb02ecdf40b08cffe33731 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/GroupQueryDto.java @@ -0,0 +1,148 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * @author Daniel Meyer + */ +public class GroupQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_GROUP_ID_VALUE = "id"; + private static final String SORT_BY_GROUP_NAME_VALUE = "name"; + private static final String SORT_BY_GROUP_TYPE_VALUE = "type"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_GROUP_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_GROUP_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_GROUP_TYPE_VALUE); + } + + protected String id; + protected String[] ids; + protected String name; + protected String nameLike; + protected String type; + protected String member; + protected String tenantId; + + public GroupQueryDto() { + + } + + public GroupQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("id") + public void setId(String groupId) { + this.id = groupId; + } + + @CamundaQueryParam(value = "idIn", converter = StringArrayConverter.class) + public void setIdIn(String[] groupIds) { + this.ids = groupIds; + } + + @CamundaQueryParam("name") + public void setName(String groupName) { + this.name = groupName; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String groupNameLike) { + this.nameLike = groupNameLike; + } + + @CamundaQueryParam("type") + public void setType(String groupType) { + this.type = groupType; + } + + @CamundaQueryParam("member") + public void setMember(String member) { + this.member = member; + } + + @CamundaQueryParam("memberOfTenant") + public void setMemberOfTenant(String tenantId) { + this.tenantId = tenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected GroupQuery createNewQuery(ProcessEngine engine) { + return engine.getIdentityService().createGroupQuery(); + } + + @Override + protected void applyFilters(GroupQuery query) { + if (id != null) { + query.groupId(id); + } + if (ids != null) { + query.groupIdIn(ids); + } + if (name != null) { + query.groupName(name); + } + if (nameLike != null) { + query.groupNameLike(nameLike); + } + if (type != null) { + query.groupType(type); + } + if (member != null) { + query.groupMember(member); + } + if (tenantId != null) { + query.memberOfTenant(tenantId); + } + } + + @Override + protected void applySortBy(GroupQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_GROUP_ID_VALUE)) { + query.orderByGroupId(); + } else if (sortBy.equals(SORT_BY_GROUP_NAME_VALUE)) { + query.orderByGroupName(); + } else if (sortBy.equals(SORT_BY_GROUP_TYPE_VALUE)) { + query.orderByGroupType(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2345a7cae9069cc36892e697c336c54c4a7f46f9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyDto.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.identity.PasswordPolicy; +import org.camunda.bpm.engine.identity.PasswordPolicyRule; + +/** + * @author Miklas Boskamp + */ +public class PasswordPolicyDto { + protected List rules = new ArrayList(); + + // transformers + + public static PasswordPolicyDto fromPasswordPolicy(PasswordPolicy policy) { + PasswordPolicyDto policyDto = new PasswordPolicyDto(); + for (PasswordPolicyRule rule : policy.getRules()) { + policyDto.rules.add(new PasswordPolicyRuleDto(rule)); + } + return policyDto; + } + + // getters / setters + + public List getRules() { + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyRequestDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyRequestDto.java new file mode 100644 index 0000000000000000000000000000000000000000..61bd81d11483efa1c01b79a6fc0d5a2cfa18d984 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyRequestDto.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +/** + * @author Miklas Boskamp + */ +public class PasswordPolicyRequestDto { + + protected String password; + protected UserProfileDto profile; + + public UserProfileDto getProfile() { + return profile; + } + + public void setProfile(UserProfileDto profile) { + this.profile = profile; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyRuleDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyRuleDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0fcd77dcbd2398200a9da278e5d3ed7c72928564 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/PasswordPolicyRuleDto.java @@ -0,0 +1,56 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import java.util.Map; + +import org.camunda.bpm.engine.identity.PasswordPolicyRule; + +/** + * @author Miklas Boskamp + */ +public class PasswordPolicyRuleDto { + + protected String placeholder; + protected Map parameter; + + // transformers + + public PasswordPolicyRuleDto(PasswordPolicyRule rule) { + this.placeholder = rule.getPlaceholder(); + this.parameter = rule.getParameters(); + } + + // getters / setters + + public String getPlaceholder() { + return placeholder; + } + + public void setPlaceholder(String placeholder) { + this.placeholder = placeholder; + } + + public Map getParameter() { + return parameter; + } + + public void setParameter(Map parameter) { + this.parameter = parameter; + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/TenantDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/TenantDto.java new file mode 100644 index 0000000000000000000000000000000000000000..6f11998ace2d63b588ebdec35ac4602dda61cae1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/TenantDto.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.identity.Tenant; + +public class TenantDto { + + protected String id; + protected String name; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public static TenantDto fromTenant(Tenant tenant) { + TenantDto dto = new TenantDto(); + dto.id = tenant.getId(); + dto.name = tenant.getName(); + return dto; + } + + public static List fromTenantList(List tenants) { + List dtos = new ArrayList(); + for (Tenant tenant : tenants) { + dtos.add(fromTenant(tenant)); + } + return dtos; + } + + public void update(Tenant tenant) { + tenant.setId(id); + tenant.setName(name); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/TenantQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/TenantQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..27013848fdfe04a6e6748c5dc3386f33f8e872e9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/TenantQueryDto.java @@ -0,0 +1,131 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.TenantQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TenantQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_TENANT_ID_VALUE = "id"; + private static final String SORT_BY_TENANT_NAME_VALUE = "name"; + + private static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_NAME_VALUE); + } + + protected String id; + protected String name; + protected String nameLike; + protected String userId; + protected String groupId; + protected Boolean includingGroupsOfUser; + + public TenantQueryDto() { + } + + public TenantQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("id") + public void setId(String id) { + this.id = id; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("userMember") + public void setUserMember(String userId) { + this.userId = userId; + } + + @CamundaQueryParam("groupMember") + public void setGroupMember(String groupId) { + this.groupId = groupId; + } + + @CamundaQueryParam(value = "includingGroupsOfUser", converter = BooleanConverter.class) + public void setIncludingGroupsOfUser(Boolean includingGroupsOfUser) { + this.includingGroupsOfUser = includingGroupsOfUser; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected TenantQuery createNewQuery(ProcessEngine engine) { + return engine.getIdentityService().createTenantQuery(); + } + + @Override + protected void applyFilters(TenantQuery query) { + if (id != null) { + query.tenantId(id); + } + if (name != null) { + query.tenantName(name); + } + if (nameLike != null) { + query.tenantNameLike(nameLike); + } + if (userId != null) { + query.userMember(userId); + } + if (groupId != null) { + query.groupMember(groupId); + } + if (Boolean.TRUE.equals(includingGroupsOfUser)) { + query.includingGroupsOfUser(true); + } + } + + @Override + protected void applySortBy(TenantQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { + query.orderByTenantId(); + } else if (sortBy.equals(SORT_BY_TENANT_NAME_VALUE)) { + query.orderByTenantName(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserCreateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserCreateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f7d9b0eac49cfe59fe0697e3161b85456b6c1e71 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserCreateDto.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + + +/** + * + * @author Daniel Meyer + * + */ +public class UserCreateDto extends UserDto { + + protected String password; + + // getter / setters //////////////////////////////////// + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserCredentialsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserCredentialsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e64411a6bd388bab9f205a7f3681d6a47578df2d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserCredentialsDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import org.camunda.bpm.engine.identity.User; + +/** + * @author Daniel Meyer + * + */ +public class UserCredentialsDto { + + protected String password; + protected String authenticatedUserPassword; + + // transformers ////////////////////////////////// + + public static UserCredentialsDto fromUser(User user) { + UserCredentialsDto result = new UserCredentialsDto(); + result.setPassword(user.getPassword()); + return result; + } + + // getters / setters ///////////////////////////// + + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + public String getAuthenticatedUserPassword() { + return authenticatedUserPassword; + } + public void setAuthenticatedUserPassword(String authenticatedUserPassword) { + this.authenticatedUserPassword = authenticatedUserPassword; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e7e2b7443e0116be636e261fbd85ea17e8eb4bdd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserDto.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import org.camunda.bpm.engine.identity.User; + +/** + * @author Daniel Meyer + * + */ +public class UserDto { + + protected UserProfileDto profile; + + protected UserCredentialsDto credentials; + + // transformers ////////////////////////////////// + + public static UserDto fromUser(User user, boolean isIncludeCredentials) { + UserDto userDto = new UserDto(); + userDto.setProfile(UserProfileDto.fromUser(user)); + if(isIncludeCredentials) { + userDto.setCredentials(UserCredentialsDto.fromUser(user)); + } + return userDto; + } + + // getters / setters ///////////////////////////// + + public UserProfileDto getProfile() { + return profile; + } + + public void setProfile(UserProfileDto profile) { + this.profile = profile; + } + + public UserCredentialsDto getCredentials() { + return credentials; + } + + public void setCredentials(UserCredentialsDto credentials) { + this.credentials = credentials; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserProfileDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserProfileDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4008a000eae21de247ba9d4d01d5f4a7b8a1a757 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserProfileDto.java @@ -0,0 +1,94 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import org.camunda.bpm.engine.identity.User; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Daniel Meyer + * + */ +public class UserProfileDto { + + protected String id; + protected String firstName; + protected String lastName; + protected String email; + + // transformers //////////////////////////////////////// + + public static UserProfileDto fromUser(User user) { + UserProfileDto result = new UserProfileDto(); + result.id = user.getId(); + result.firstName = user.getFirstName(); + result.lastName = user.getLastName(); + result.email = user.getEmail(); + return result; + } + + public static List fromUserList(List sourceList) { + List resultList = new ArrayList(); + for (User user : sourceList) { + resultList.add(fromUser(user)); + } + return resultList; + } + + public void update(User dbUser) { + dbUser.setId(getId()); + dbUser.setFirstName(getFirstName()); + dbUser.setLastName(getLastName()); + dbUser.setEmail(getEmail()); + } + + // getter / setters //////////////////////////////////// + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..1caecb936aeda505c2e03757506e0ec3afe21c98 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/identity/UserQueryDto.java @@ -0,0 +1,188 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.identity; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * @author Daniel Meyer + */ +public class UserQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_USER_ID_VALUE = "userId"; + private static final String SORT_BY_USER_FIRSTNAME_VALUE = "firstName"; + private static final String SORT_BY_USER_LASTNAME_VALUE = "lastName"; + private static final String SORT_BY_USER_EMAIL_VALUE = "email"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_USER_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_USER_FIRSTNAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_USER_LASTNAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_USER_EMAIL_VALUE); + } + + protected String id; + protected String[] idIn; + protected String firstName; + protected String firstNameLike; + protected String lastName; + protected String lastNameLike; + protected String email; + protected String emailLike; + protected String memberOfGroup; + protected String potentialStarter; + protected String tenantId; + + public UserQueryDto() { + + } + + public UserQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("id") + public void setId(String userId) { + this.id = userId; + } + + @CamundaQueryParam(value = "idIn", converter = StringArrayConverter.class) + public void setIdIn(String[] ids) { + this.idIn = ids; + } + + @CamundaQueryParam("firstName") + public void setFirstName(String userFirstName) { + this.firstName = userFirstName; + } + + @CamundaQueryParam("firstNameLike") + public void setFirstNameLike(String userFirstNameLike) { + this.firstNameLike = userFirstNameLike; + } + + @CamundaQueryParam("lastName") + public void setLastName(String userLastName) { + this.lastName = userLastName; + } + + @CamundaQueryParam("lastNameLike") + public void setLastNameLike(String userLastNameLike) { + this.lastNameLike = userLastNameLike; + } + + @CamundaQueryParam("email") + public void setEmail(String userEmail) { + this.email = userEmail; + } + + @CamundaQueryParam("emailLike") + public void setEmailLike(String userEmailLike) { + this.emailLike = userEmailLike; + } + + @CamundaQueryParam("memberOfGroup") + public void setMemberOfGroup(String memberOfGroup) { + this.memberOfGroup = memberOfGroup; + } + + @CamundaQueryParam("potentialStarter") + public void setPotentialStarter(String potentialStarter) { + this.potentialStarter = potentialStarter; + } + + @CamundaQueryParam("memberOfTenant") + public void setMemberOfTenant(String tenantId) { + this.tenantId = tenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected UserQuery createNewQuery(ProcessEngine engine) { + return engine.getIdentityService().createUserQuery(); + } + + @Override + protected void applyFilters(UserQuery query) { + if (id != null) { + query.userId(id); + } + if(idIn != null) { + query.userIdIn(idIn); + } + if (firstName != null) { + query.userFirstName(firstName); + } + if (firstNameLike != null) { + query.userFirstNameLike(firstNameLike); + } + if (lastName != null) { + query.userLastName(lastName); + } + if (lastNameLike != null) { + query.userLastNameLike(lastNameLike); + } + if (email != null) { + query.userEmail(email); + } + if (emailLike != null) { + query.userEmailLike(emailLike); + } + if (memberOfGroup != null) { + query.memberOfGroup(memberOfGroup); + } + if (potentialStarter != null) { + query.potentialStarter(potentialStarter); + } + if (tenantId != null) { + query.memberOfTenant(tenantId); + } + } + + @Override + protected void applySortBy(UserQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_USER_ID_VALUE)) { + query.orderByUserId(); + } else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) { + query.orderByUserFirstName(); + } else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) { + query.orderByUserLastName(); + } else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) { + query.orderByUserEmail(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9943b1df46f81fdf70875ac316f448e7e552a3ee --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionDto.java @@ -0,0 +1,89 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.management; + +import org.camunda.bpm.engine.management.JobDefinition; + +/** + * @author roman.smirnov + */ +public class JobDefinitionDto { + + protected String id; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String jobType; + protected String jobConfiguration; + protected String activityId; + protected boolean suspended; + protected Long overridingJobPriority; + protected String tenantId; + protected String deploymentId; + + public JobDefinitionDto() { } + + public String getId() { + return id; + } + public String getProcessDefinitionId() { + return processDefinitionId; + } + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + public String getJobType() { + return jobType; + } + public String getJobConfiguration() { + return jobConfiguration; + } + public String getActivityId() { + return activityId; + } + public boolean isSuspended() { + return suspended; + } + public Long getOverridingJobPriority() { + return overridingJobPriority; + } + + public String getTenantId() { + return tenantId; + } + + public String getDeploymentId() { + return deploymentId; + } + + public static JobDefinitionDto fromJobDefinition(JobDefinition definition) { + JobDefinitionDto dto = new JobDefinitionDto(); + + dto.id = definition.getId(); + dto.processDefinitionId = definition.getProcessDefinitionId(); + dto.processDefinitionKey = definition.getProcessDefinitionKey(); + dto.jobType = definition.getJobType(); + dto.jobConfiguration = definition.getJobConfiguration(); + dto.activityId = definition.getActivityId(); + dto.suspended = definition.isSuspended(); + dto.overridingJobPriority = definition.getOverridingJobPriority(); + dto.tenantId = definition.getTenantId(); + dto.deploymentId = definition.getDeploymentId(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..a8ac000a5d7de94f6b240f2be1954457412190f0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionQueryDto.java @@ -0,0 +1,220 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.management; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.management.JobDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author roman.smirnov + */ +public class JobDefinitionQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_JOB_DEFINITION_ID = "jobDefinitionId"; + private static final String SORT_BY_ACTIVITY_ID = "activityId"; + private static final String SORT_BY_PROCESS_DEFINITION_ID = "processDefinitionId"; + private static final String SORT_BY_PROCESS_DEFINITION_KEY = "processDefinitionKey"; + private static final String SORT_BY_JOB_TYPE = "jobType"; + private static final String SORT_BY_JOB_CONFIGURATION = "jobConfiguration"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_KEY); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_TYPE); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_CONFIGURATION); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String jobDefinitionId; + protected String[] activityIdIn; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String jobType; + protected String jobConfiguration; + protected Boolean active; + protected Boolean suspended; + protected Boolean withOverridingJobPriority; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean includeJobDefinitionsWithoutTenantId; + + public JobDefinitionQueryDto() {} + + public JobDefinitionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("jobDefinitionId") + public void setJobDefinitionId(String jobDefinitionId) { + this.jobDefinitionId = jobDefinitionId; + } + + @CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class) + public void setActivityIdIn(String[] activityIdIn) { + this.activityIdIn = activityIdIn; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("jobType") + public void setJobType(String jobType) { + this.jobType = jobType; + } + + @CamundaQueryParam("jobConfiguration") + public void setJobConfiguration(String jobConfiguration) { + this.jobConfiguration = jobConfiguration; + } + + @CamundaQueryParam(value="active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value="suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value="withOverridingJobPriority", converter = BooleanConverter.class) + public void setWithOverridingJobPriority(Boolean withOverridingJobPriority) { + this.withOverridingJobPriority = withOverridingJobPriority; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "includeJobDefinitionsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeJobDefinitionsWithoutTenantId(Boolean includeJobDefinitionsWithoutTenantId) { + this.includeJobDefinitionsWithoutTenantId = includeJobDefinitionsWithoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected JobDefinitionQuery createNewQuery(ProcessEngine engine) { + return engine.getManagementService().createJobDefinitionQuery(); + } + + @Override + protected void applyFilters(JobDefinitionQuery query) { + if (jobDefinitionId != null) { + query.jobDefinitionId(jobDefinitionId); + } + + if (activityIdIn != null && activityIdIn.length > 0) { + query.activityIdIn(activityIdIn); + } + + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + + if (jobType != null) { + query.jobType(jobType); + } + + if (jobConfiguration != null) { + query.jobConfiguration(jobConfiguration); + } + + if (TRUE.equals(active)) { + query.active(); + } + + if (TRUE.equals(suspended)) { + query.suspended(); + } + + if (TRUE.equals(withOverridingJobPriority)) { + query.withOverridingJobPriority(); + } + + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeJobDefinitionsWithoutTenantId)) { + query.includeJobDefinitionsWithoutTenantId(); + } + } + + @Override + protected void applySortBy(JobDefinitionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_JOB_DEFINITION_ID)) { + query.orderByJobDefinitionId(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { + query.orderByActivityId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_JOB_TYPE)) { + query.orderByJobType(); + } else if (sortBy.equals(SORT_BY_JOB_CONFIGURATION)) { + query.orderByJobConfiguration(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionSuspensionStateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionSuspensionStateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..fd11cce4523f2557422495b17252ffc8bd4d83b1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/management/JobDefinitionSuspensionStateDto.java @@ -0,0 +1,132 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.management; + +import java.util.Date; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.management.UpdateJobDefinitionSuspensionStateBuilder; +import org.camunda.bpm.engine.management.UpdateJobDefinitionSuspensionStateSelectBuilder; +import org.camunda.bpm.engine.management.UpdateJobDefinitionSuspensionStateTenantBuilder; +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +/** + * @author roman.smirnov + */ +public class JobDefinitionSuspensionStateDto extends SuspensionStateDto { + + private String executionDate; + private boolean includeJobs; + private String jobDefinitionId; + private String processDefinitionId; + private String processDefinitionKey; + + private String processDefinitionTenantId; + private boolean processDefinitionWithoutTenantId; + + public String getJobDefinitionId() { + return jobDefinitionId; + } + + public void setJobDefinitionId(String jobDefinitionId) { + this.jobDefinitionId = jobDefinitionId; + } + + public void setExecutionDate(String executionDate) { + this.executionDate = executionDate; + } + + public void setIncludeJobs(boolean includeJobs) { + this.includeJobs = includeJobs; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + public void setProcessDefinitionTenantId(String processDefinitionTenantId) { + this.processDefinitionTenantId = processDefinitionTenantId; + } + + public void setProcessDefinitionWithoutTenantId(boolean processDefinitionWithoutTenantId) { + this.processDefinitionWithoutTenantId = processDefinitionWithoutTenantId; + } + + @Override + public void updateSuspensionState(ProcessEngine engine) { + int params = (jobDefinitionId != null ? 1 : 0) + + (processDefinitionId != null ? 1 : 0) + + (processDefinitionKey != null ? 1 : 0); + + if (params > 1) { + String message = "Only one of jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + + } else if (params == 0) { + String message = "Either jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + UpdateJobDefinitionSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateBuilder(engine); + + if (executionDate != null && !executionDate.equals("")) { + Date delayedExecutionDate = DateTimeUtil.parseDate(executionDate); + + updateSuspensionStateBuilder.executionDate(delayedExecutionDate); + } + + updateSuspensionStateBuilder.includeJobs(includeJobs); + + if (getSuspended()) { + updateSuspensionStateBuilder.suspend(); + } else { + updateSuspensionStateBuilder.activate(); + } + } + + protected UpdateJobDefinitionSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) { + UpdateJobDefinitionSuspensionStateSelectBuilder selectBuilder = engine.getManagementService().updateJobDefinitionSuspensionState(); + + if (jobDefinitionId != null) { + return selectBuilder.byJobDefinitionId(jobDefinitionId); + + } else if (processDefinitionId != null) { + return selectBuilder.byProcessDefinitionId(processDefinitionId); + + } else { + UpdateJobDefinitionSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey); + + if (processDefinitionTenantId != null) { + tenantBuilder.processDefinitionTenantId(processDefinitionTenantId); + + } else if (processDefinitionWithoutTenantId) { + tenantBuilder.processDefinitionWithoutTenantId(); + } + + return tenantBuilder; + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/CorrelationMessageDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/CorrelationMessageDto.java new file mode 100644 index 0000000000000000000000000000000000000000..7a828fff15ecd244b5f4e0527a35f1b5bdb3ae16 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/CorrelationMessageDto.java @@ -0,0 +1,143 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.message; + +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +public class CorrelationMessageDto { + + private String messageName; + private String businessKey; + private Map correlationKeys; + private Map localCorrelationKeys; + private Map processVariables; + private Map processVariablesLocal; + private Map processVariablesToTriggeredScope; + private String tenantId; + private boolean withoutTenantId; + private String processInstanceId; + + private boolean all = false; + private boolean resultEnabled = false; + private boolean variablesInResultEnabled = false; + + public String getMessageName() { + return messageName; + } + + public void setMessageName(String messageName) { + this.messageName = messageName; + } + + public String getBusinessKey() { + return businessKey; + } + + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + + public Map getCorrelationKeys() { + return correlationKeys; + } + + public void setCorrelationKeys(Map correlationKeys) { + this.correlationKeys = correlationKeys; + } + + public Map getLocalCorrelationKeys() { + return localCorrelationKeys; + } + + public void setLocalCorrelationKeys(Map localCorrelationKeys) { + this.localCorrelationKeys = localCorrelationKeys; + } + + public Map getProcessVariables() { + return processVariables; + } + + public void setProcessVariables(Map processVariables) { + this.processVariables = processVariables; + } + + public Map getProcessVariablesLocal() { + return processVariablesLocal; + } + + public void setProcessVariablesLocal(Map processVariablesLocal) { + this.processVariablesLocal = processVariablesLocal; + } + + public Map getProcessVariablesToTriggeredScope() { + return processVariablesToTriggeredScope; + } + + public void setProcessVariablesToTriggeredScope(Map processVariablesToTriggeredScope) { + this.processVariablesToTriggeredScope = processVariablesToTriggeredScope; + } + + public boolean isAll() { + return all; + } + + public void setAll(boolean all) { + this.all = all; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public boolean isWithoutTenantId() { + return withoutTenantId; + } + + public void setWithoutTenantId(boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public boolean isResultEnabled() { + return resultEnabled; + } + + public void setResultEnabled(boolean resultEnabled) { + this.resultEnabled = resultEnabled; + } + + public boolean isVariablesInResultEnabled() { + return variablesInResultEnabled; + } + + public void setVariablesInResultEnabled(boolean variablesInResultEnabled) { + this.variablesInResultEnabled = variablesInResultEnabled; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/MessageCorrelationResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/MessageCorrelationResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e85a83c3198316b8ae6fc7b90463bb8a1ce85ccc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/MessageCorrelationResultDto.java @@ -0,0 +1,79 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.message; + +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.runtime.MessageCorrelationResult; +import org.camunda.bpm.engine.runtime.MessageCorrelationResultType; + +/** + * + * @author Christopher Zell + */ +public class MessageCorrelationResultDto { + + private MessageCorrelationResultType resultType; + + //restul type execution + private ExecutionDto execution; + + //result type process definition + private ProcessInstanceDto processInstance; + + public static MessageCorrelationResultDto fromMessageCorrelationResult(MessageCorrelationResult result) { + MessageCorrelationResultDto dto = new MessageCorrelationResultDto(); + return setExecutionAndProcessInstance(dto, result); + } + + public static MessageCorrelationResultDto setExecutionAndProcessInstance(MessageCorrelationResultDto dto, MessageCorrelationResult result) { + if (result != null) { + dto.setResultType(result.getResultType()); + if (result.getResultType() == MessageCorrelationResultType.Execution && result.getExecution() != null) { + dto.setExecution(ExecutionDto.fromExecution(result.getExecution())); + } else if (result.getResultType() == MessageCorrelationResultType.ProcessDefinition && result.getProcessInstance() != null) { + dto.setProcessInstance(ProcessInstanceDto.fromProcessInstance(result.getProcessInstance())); + } + } + return dto; + } + + public MessageCorrelationResultType getResultType() { + return resultType; + } + + public void setResultType(MessageCorrelationResultType resultType) { + this.resultType = resultType; + } + + public ExecutionDto getExecution() { + return execution; + } + + public void setExecution(ExecutionDto execution) { + this.execution = execution; + } + + public ProcessInstanceDto getProcessInstance() { + return processInstance; + } + + public void setProcessInstance(ProcessInstanceDto processInstance) { + this.processInstance = processInstance; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/MessageCorrelationResultWithVariableDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/MessageCorrelationResultWithVariableDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bd2cbc309e33f41375a11c4a660a1de86e68ed7d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/message/MessageCorrelationResultWithVariableDto.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.message; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.runtime.MessageCorrelationResultWithVariables; + +public class MessageCorrelationResultWithVariableDto extends MessageCorrelationResultDto { + + private Map variables; + + public static MessageCorrelationResultWithVariableDto fromMessageCorrelationResultWithVariables(MessageCorrelationResultWithVariables result) { + MessageCorrelationResultWithVariableDto dto = new MessageCorrelationResultWithVariableDto(); + setExecutionAndProcessInstance(dto, result); + if (result != null) { + dto.variables = VariableValueDto.fromMap(result.getVariables(), true); + } + return dto; + } + + public Map getVariables() { + return variables; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/metrics/MetricsIntervalResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/metrics/MetricsIntervalResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..cf080567ea32fa07a9f80b0bf0a342864d4f2014 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/metrics/MetricsIntervalResultDto.java @@ -0,0 +1,85 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.metrics; + +import java.util.Date; +import org.camunda.bpm.engine.management.MetricIntervalValue; + +/** + * + * @author Christopher Zell + */ +public class MetricsIntervalResultDto { + + protected Date timestamp; + + protected String name; + + protected String reporter; + + protected long value; + + public MetricsIntervalResultDto(MetricIntervalValue metric) { + this.timestamp = metric.getTimestamp(); + this.name = metric.getName(); + this.reporter = metric.getReporter(); + this.value = metric.getValue(); + } + + public MetricsIntervalResultDto(Date timestamp, String name, String reporter, long value) { + this.timestamp = timestamp; + this.name = name; + this.reporter = reporter; + this.value = value; + } + + public MetricsIntervalResultDto() { + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getReporter() { + return reporter; + } + + public void setReporter(String reporter) { + this.reporter = reporter; + } + + public long getValue() { + return value; + } + + public void setValue(long value) { + this.value = value; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/metrics/MetricsResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/metrics/MetricsResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bc00571f9a1c66072f633480fc1d1bb60e89879e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/metrics/MetricsResultDto.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.metrics; + +/** + * @author Daniel Meyer + * + */ +public class MetricsResultDto { + + protected Number result; + + public MetricsResultDto(Number result) { + this.result = result; + } + + public MetricsResultDto() { + } + + public Number getResult() { + return result; + } + + public void setResult(Number result) { + this.result = result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingActivityInstanceValidationReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingActivityInstanceValidationReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..24020670191fd3259183b371134428f4333fc9ef --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingActivityInstanceValidationReportDto.java @@ -0,0 +1,80 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.migration.MigratingActivityInstanceValidationReport; + +public class MigratingActivityInstanceValidationReportDto { + + protected MigrationInstructionDto migrationInstruction; + protected String activityInstanceId; + protected String sourceScopeId; + protected List failures; + + public MigrationInstructionDto getMigrationInstruction() { + return migrationInstruction; + } + + public void setMigrationInstruction(MigrationInstructionDto migrationInstruction) { + this.migrationInstruction = migrationInstruction; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public void setActivityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + } + + public List getFailures() { + return failures; + } + + public void setFailures(List failures) { + this.failures = failures; + } + + public String getSourceScopeId() { + return sourceScopeId; + } + + public void setSourceScopeId(String sourceScopeId) { + this.sourceScopeId = sourceScopeId; + } + + public static List from(List reports) { + ArrayList dtos = new ArrayList(); + for (MigratingActivityInstanceValidationReport report : reports) { + dtos.add(MigratingActivityInstanceValidationReportDto.from(report)); + } + return dtos; + } + + public static MigratingActivityInstanceValidationReportDto from(MigratingActivityInstanceValidationReport report) { + MigratingActivityInstanceValidationReportDto dto = new MigratingActivityInstanceValidationReportDto(); + dto.setMigrationInstruction(MigrationInstructionDto.from(report.getMigrationInstruction())); + dto.setActivityInstanceId(report.getActivityInstanceId()); + dto.setFailures(report.getFailures()); + dto.setSourceScopeId(report.getSourceScopeId()); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingProcessInstanceValidationExceptionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingProcessInstanceValidationExceptionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..746124d7a99ec154ef94449a4f390848262541c8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingProcessInstanceValidationExceptionDto.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import org.camunda.bpm.engine.migration.MigratingProcessInstanceValidationException; +import org.camunda.bpm.engine.rest.dto.ExceptionDto; + +public class MigratingProcessInstanceValidationExceptionDto extends ExceptionDto { + + protected MigratingProcessInstanceValidationReportDto validationReport; + + public MigratingProcessInstanceValidationReportDto getValidationReport() { + return validationReport; + } + + public void setValidationReport(MigratingProcessInstanceValidationReportDto validationReport) { + this.validationReport = validationReport; + } + + public static MigratingProcessInstanceValidationExceptionDto from(MigratingProcessInstanceValidationException exception) { + MigratingProcessInstanceValidationExceptionDto dto = new MigratingProcessInstanceValidationExceptionDto(); + dto.message = exception.getMessage(); + dto.type = exception.getClass().getSimpleName(); + dto.setValidationReport(MigratingProcessInstanceValidationReportDto.from(exception.getValidationReport())); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingProcessInstanceValidationReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingProcessInstanceValidationReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..33d9c311c31a1fced488c12bbdc480fb1605d8bf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingProcessInstanceValidationReportDto.java @@ -0,0 +1,71 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.List; + +import org.camunda.bpm.engine.migration.MigratingProcessInstanceValidationReport; + +public class MigratingProcessInstanceValidationReportDto { + + protected String processInstanceId; + protected List failures; + protected List activityInstanceValidationReports; + protected List transitionInstanceValidationReports; + + public String getProcessInstanceId() { + return processInstanceId; + } + + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public List getFailures() { + return failures; + } + + public void setFailures(List failures) { + this.failures = failures; + } + + public List getActivityInstanceValidationReports() { + return activityInstanceValidationReports; + } + + public void setActivityInstanceValidationReports(List activityInstanceValidationReports) { + this.activityInstanceValidationReports = activityInstanceValidationReports; + } + + public List getTransitionInstanceValidationReports() { + return transitionInstanceValidationReports; + } + + public void setTransitionInstanceValidationReports(List transitionInstanceValidationReports) { + this.transitionInstanceValidationReports = transitionInstanceValidationReports; + } + + public static MigratingProcessInstanceValidationReportDto from(MigratingProcessInstanceValidationReport validationReport) { + MigratingProcessInstanceValidationReportDto dto = new MigratingProcessInstanceValidationReportDto(); + dto.setProcessInstanceId(validationReport.getProcessInstanceId()); + dto.setFailures(validationReport.getFailures()); + dto.setActivityInstanceValidationReports(MigratingActivityInstanceValidationReportDto.from(validationReport.getActivityInstanceReports())); + dto.setTransitionInstanceValidationReports(MigratingTransitionInstanceValidationReportDto.from(validationReport.getTransitionInstanceReports())); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingTransitionInstanceValidationReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingTransitionInstanceValidationReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f70cdcebe300b12d233be2127696e152e3c4c540 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigratingTransitionInstanceValidationReportDto.java @@ -0,0 +1,80 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.migration.MigratingTransitionInstanceValidationReport; + +public class MigratingTransitionInstanceValidationReportDto { + + protected MigrationInstructionDto migrationInstruction; + protected String transitionInstanceId; + protected String sourceScopeId; + protected List failures; + + public MigrationInstructionDto getMigrationInstruction() { + return migrationInstruction; + } + + public void setMigrationInstruction(MigrationInstructionDto migrationInstruction) { + this.migrationInstruction = migrationInstruction; + } + + public String getTransitionInstanceId() { + return transitionInstanceId; + } + + public void setTransitionInstanceId(String transitionInstanceId) { + this.transitionInstanceId = transitionInstanceId; + } + + public List getFailures() { + return failures; + } + + public void setFailures(List failures) { + this.failures = failures; + } + + public String getSourceScopeId() { + return sourceScopeId; + } + + public void setSourceScopeId(String sourceScopeId) { + this.sourceScopeId = sourceScopeId; + } + + public static List from(List reports) { + ArrayList dtos = new ArrayList(); + for (MigratingTransitionInstanceValidationReport report : reports) { + dtos.add(MigratingTransitionInstanceValidationReportDto.from(report)); + } + return dtos; + } + + public static MigratingTransitionInstanceValidationReportDto from(MigratingTransitionInstanceValidationReport report) { + MigratingTransitionInstanceValidationReportDto dto = new MigratingTransitionInstanceValidationReportDto(); + dto.setMigrationInstruction(MigrationInstructionDto.from(report.getMigrationInstruction())); + dto.setTransitionInstanceId(report.getTransitionInstanceId()); + dto.setFailures(report.getFailures()); + dto.setSourceScopeId(report.getSourceScopeId()); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationExecutionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationExecutionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..02bac051c8b71592ac0c5ee2484ea7fb573e6a38 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationExecutionDto.java @@ -0,0 +1,71 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.List; + +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; + +public class MigrationExecutionDto { + + protected MigrationPlanDto migrationPlan; + protected List processInstanceIds; + protected ProcessInstanceQueryDto processInstanceQuery; + protected boolean skipIoMappings; + protected boolean skipCustomListeners; + + public MigrationPlanDto getMigrationPlan() { + return migrationPlan; + } + + public void setMigrationPlan(MigrationPlanDto migrationPlan) { + this.migrationPlan = migrationPlan; + } + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { + this.processInstanceQuery = processInstanceQuery; + } + + public boolean isSkipIoMappings() { + return skipIoMappings; + } + + public void setSkipIoMappings(boolean skipIoMappings) { + this.skipIoMappings = skipIoMappings; + } + + public boolean isSkipCustomListeners() { + return skipCustomListeners; + } + + public void setSkipCustomListeners(boolean skipCustomListeners) { + this.skipCustomListeners = skipCustomListeners; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationInstructionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationInstructionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..1d19304fd8228a1d100a3a06c2f4b5f09853a3f0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationInstructionDto.java @@ -0,0 +1,69 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.Collections; +import java.util.List; + +import org.camunda.bpm.engine.migration.MigrationInstruction; + +public class MigrationInstructionDto { + + protected List sourceActivityIds; + protected List targetActivityIds; + protected Boolean updateEventTrigger; + + public List getSourceActivityIds() { + return sourceActivityIds; + } + + public void setSourceActivityIds(List sourceActivityIds) { + this.sourceActivityIds = sourceActivityIds; + } + + public List getTargetActivityIds() { + return targetActivityIds; + } + + public void setTargetActivityIds(List targetActivityIds) { + this.targetActivityIds = targetActivityIds; + } + + public void setUpdateEventTrigger(Boolean isUpdateEventTrigger) { + this.updateEventTrigger = isUpdateEventTrigger; + } + + public Boolean isUpdateEventTrigger() { + return updateEventTrigger; + } + + public static MigrationInstructionDto from(MigrationInstruction migrationInstruction) { + if (migrationInstruction != null) { + MigrationInstructionDto dto = new MigrationInstructionDto(); + + dto.setSourceActivityIds(Collections.singletonList(migrationInstruction.getSourceActivityId())); + dto.setTargetActivityIds(Collections.singletonList(migrationInstruction.getTargetActivityId())); + dto.setUpdateEventTrigger(migrationInstruction.isUpdateEventTrigger()); + + return dto; + } + else { + return null; + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationInstructionValidationReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationInstructionValidationReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2d5ebbf62956e5be77213cfe5700ce1cdedc340d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationInstructionValidationReportDto.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.migration.MigrationInstructionValidationReport; + +/** + * @author Thorben Lindhauer + * + */ +public class MigrationInstructionValidationReportDto { + + protected MigrationInstructionDto instruction; + protected List failures; + + public MigrationInstructionDto getInstruction() { + return instruction; + } + + public void setInstruction(MigrationInstructionDto instruction) { + this.instruction = instruction; + } + + public List getFailures() { + return failures; + } + + public void setFailures(List failures) { + this.failures = failures; + } + + public static List from(List instructionReports) { + List dtos = new ArrayList(); + for (MigrationInstructionValidationReport instructionReport : instructionReports) { + dtos.add(MigrationInstructionValidationReportDto.from(instructionReport)); + } + return dtos; + } + + public static MigrationInstructionValidationReportDto from(MigrationInstructionValidationReport instructionReport) { + MigrationInstructionValidationReportDto dto = new MigrationInstructionValidationReportDto(); + dto.setInstruction(MigrationInstructionDto.from(instructionReport.getMigrationInstruction())); + dto.setFailures(instructionReport.getFailures()); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanDto.java new file mode 100644 index 0000000000000000000000000000000000000000..8413813e259a3436d423dfe6b7c9b864166a5a8b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanDto.java @@ -0,0 +1,120 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.migration.MigrationPlanBuilder; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.migration.MigrationInstruction; +import org.camunda.bpm.engine.migration.MigrationInstructionBuilder; +import org.camunda.bpm.engine.migration.MigrationPlan; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.variable.VariableMap; + +public class MigrationPlanDto { + + protected String sourceProcessDefinitionId; + protected String targetProcessDefinitionId; + protected List instructions; + protected Map variables; + + public String getSourceProcessDefinitionId() { + return sourceProcessDefinitionId; + } + + public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) { + this.sourceProcessDefinitionId = sourceProcessDefinitionId; + } + + public String getTargetProcessDefinitionId() { + return targetProcessDefinitionId; + } + + public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { + this.targetProcessDefinitionId = targetProcessDefinitionId; + } + + public List getInstructions() { + return instructions; + } + + public void setInstructions(List instructions) { + this.instructions = instructions; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public static MigrationPlanDto from(MigrationPlan migrationPlan) { + MigrationPlanDto dto = new MigrationPlanDto(); + + VariableMap variables = migrationPlan.getVariables(); + if (variables != null) { + dto.setVariables(VariableValueDto.fromMap(variables)); + } + + dto.setSourceProcessDefinitionId(migrationPlan.getSourceProcessDefinitionId()); + dto.setTargetProcessDefinitionId(migrationPlan.getTargetProcessDefinitionId()); + + ArrayList instructionDtos = new ArrayList(); + if (migrationPlan.getInstructions() != null) { + for (MigrationInstruction migrationInstruction : migrationPlan.getInstructions()) { + MigrationInstructionDto migrationInstructionDto = MigrationInstructionDto.from(migrationInstruction); + instructionDtos.add(migrationInstructionDto); + } + } + dto.setInstructions(instructionDtos); + + return dto; + } + + public static MigrationPlan toMigrationPlan(ProcessEngine processEngine, + ObjectMapper objectMapper, + MigrationPlanDto migrationPlanDto) { + MigrationPlanBuilder migrationPlanBuilder = processEngine.getRuntimeService().createMigrationPlan(migrationPlanDto.getSourceProcessDefinitionId(), migrationPlanDto.getTargetProcessDefinitionId()); + + Map variableDtos = migrationPlanDto.getVariables(); + if (variableDtos != null) { + Map variables = + VariableValueDto.toMap(variableDtos, processEngine, objectMapper); + migrationPlanBuilder.setVariables(variables); + } + + if (migrationPlanDto.getInstructions() != null) { + for (MigrationInstructionDto migrationInstructionDto : migrationPlanDto.getInstructions()) { + MigrationInstructionBuilder migrationInstructionBuilder = migrationPlanBuilder.mapActivities(migrationInstructionDto.getSourceActivityIds().get(0), migrationInstructionDto.getTargetActivityIds().get(0)); + if (Boolean.TRUE.equals(migrationInstructionDto.isUpdateEventTrigger())) { + migrationInstructionBuilder = migrationInstructionBuilder.updateEventTrigger(); + } + + migrationPlanBuilder = migrationInstructionBuilder; + } + } + + return migrationPlanBuilder.build(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanGenerationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanGenerationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d37e3f1aa5e1f89d96e48cf28fedf82c430d81c8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanGenerationDto.java @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +import java.util.Map; + +/** + * @author Thorben Lindhauer + * + */ +public class MigrationPlanGenerationDto { + + protected String sourceProcessDefinitionId; + protected String targetProcessDefinitionId; + protected boolean updateEventTriggers; + protected Map variables; + + public String getSourceProcessDefinitionId() { + return sourceProcessDefinitionId; + } + + public void setSourceProcessDefinitionId(String sourceProcessDefinitionId) { + this.sourceProcessDefinitionId = sourceProcessDefinitionId; + } + + public String getTargetProcessDefinitionId() { + return targetProcessDefinitionId; + } + + public void setTargetProcessDefinitionId(String targetProcessDefinitionId) { + this.targetProcessDefinitionId = targetProcessDefinitionId; + } + + public boolean isUpdateEventTriggers() { + return updateEventTriggers; + } + + public void setUpdateEventTriggers(boolean updateEventTriggers) { + this.updateEventTriggers = updateEventTriggers; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public Map getVariables() { + return variables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4ec5597df45eb32ea2cb6edd5dc9d9dd6ea6dab5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanReportDto.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.migration.MigrationPlanValidationReport; + +public class MigrationPlanReportDto { + + protected List instructionReports; + protected Map variableReports; + + public List getInstructionReports() { + return instructionReports; + } + + public void setInstructionReports(List instructionReports) { + this.instructionReports = instructionReports; + } + + public Map getVariableReports() { + return variableReports; + } + + public void setVariableReports(Map variableReports) { + this.variableReports = variableReports; + } + + public static MigrationPlanReportDto form(MigrationPlanValidationReport validationReport) { + MigrationPlanReportDto dto = new MigrationPlanReportDto(); + dto.setInstructionReports(MigrationInstructionValidationReportDto.from(validationReport.getInstructionReports())); + dto.setVariableReports(MigrationVariableValidationReportDto.from(validationReport.getVariableReports())); + return dto; + } + + public static MigrationPlanReportDto emptyReport() { + MigrationPlanReportDto dto = new MigrationPlanReportDto(); + dto.setInstructionReports(Collections.emptyList()); + dto.setVariableReports(Collections.emptyMap()); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanValidationExceptionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanValidationExceptionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0652b6931061aee8b5521ad9e729171e912b38ac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationPlanValidationExceptionDto.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import org.camunda.bpm.engine.migration.MigrationPlanValidationException; +import org.camunda.bpm.engine.rest.dto.ExceptionDto; + +public class MigrationPlanValidationExceptionDto extends ExceptionDto { + + protected MigrationPlanReportDto validationReport; + + public MigrationPlanReportDto getValidationReport() { + return validationReport; + } + + public void setValidationReport(MigrationPlanReportDto validationReport) { + this.validationReport = validationReport; + } + + public static MigrationPlanValidationExceptionDto from(MigrationPlanValidationException exception) { + MigrationPlanValidationExceptionDto dto = new MigrationPlanValidationExceptionDto(); + dto.message = exception.getMessage(); + dto.type = exception.getClass().getSimpleName(); + dto.setValidationReport(MigrationPlanReportDto.form(exception.getValidationReport())); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationVariableValidationReportDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationVariableValidationReportDto.java new file mode 100644 index 0000000000000000000000000000000000000000..50c9ab79e36f8eb5be43f9f0e550813186e912b0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/migration/MigrationVariableValidationReportDto.java @@ -0,0 +1,56 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.migration; + +import org.camunda.bpm.engine.migration.MigrationVariableValidationReport; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MigrationVariableValidationReportDto extends VariableValueDto { + + protected List failures; + + public List getFailures() { + return failures; + } + + public void setFailures(List failures) { + this.failures = failures; + } + + public static Map from(Map variableReports) { + Map dtos = new HashMap<>(); + variableReports.forEach((name, report) -> + dtos.put(name, MigrationVariableValidationReportDto.from(report))); + return dtos; + } + + public static MigrationVariableValidationReportDto from(MigrationVariableValidationReport variableReport) { + MigrationVariableValidationReportDto dto = new MigrationVariableValidationReportDto(); + VariableValueDto valueDto = VariableValueDto.fromTypedValue(variableReport.getTypedValue()); + dto.setType(valueDto.getType()); + dto.setValue(valueDto.getValue()); + dto.setValueInfo(valueDto.getValueInfo()); + dto.setFailures(variableReport.getFailures()); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ActivityStatisticsResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ActivityStatisticsResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..6adaccf4976221b4b2a799ace4d56a470900bc48 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ActivityStatisticsResultDto.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.management.ActivityStatistics; +import org.camunda.bpm.engine.management.IncidentStatistics; +import org.camunda.bpm.engine.rest.dto.StatisticsResultDto; + +import java.util.ArrayList; + +public class ActivityStatisticsResultDto extends StatisticsResultDto { + + public static ActivityStatisticsResultDto fromActivityStatistics(ActivityStatistics statistics) { + ActivityStatisticsResultDto dto = new ActivityStatisticsResultDto(); + + dto.id = statistics.getId(); + dto.instances = statistics.getInstances(); + dto.failedJobs = statistics.getFailedJobs(); + + dto.incidents = new ArrayList(); + for (IncidentStatistics incident : statistics.getIncidentStatistics()) { + IncidentStatisticsResultDto incidentDto = IncidentStatisticsResultDto.fromIncidentStatistics(incident); + dto.incidents.add(incidentDto); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CalledProcessDefinitionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CalledProcessDefinitionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c25739244341f84dc8b3d04f0f3966582c2bdc7a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CalledProcessDefinitionDto.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import java.util.List; + +import org.camunda.bpm.engine.repository.CalledProcessDefinition; + +public class CalledProcessDefinitionDto extends ProcessDefinitionDto { + + protected List calledFromActivityIds; + protected String callingProcessDefinitionId; + + public List getCalledFromActivityIds() { + return calledFromActivityIds; + } + + public String getCallingProcessDefinitionId() { + return callingProcessDefinitionId; + } + + public static CalledProcessDefinitionDto from(CalledProcessDefinition definition){ + CalledProcessDefinitionDto dto = new CalledProcessDefinitionDto(); + dto.callingProcessDefinitionId = definition.getCallingProcessDefinitionId(); + dto.calledFromActivityIds = definition.getCalledFromActivityIds(); + + dto.id = definition.getId(); + dto.key = definition.getKey(); + dto.category = definition.getCategory(); + dto.description = definition.getDescription(); + dto.name = definition.getName(); + dto.version = definition.getVersion(); + dto.resource = definition.getResourceName(); + dto.deploymentId = definition.getDeploymentId(); + dto.diagram = definition.getDiagramResourceName(); + dto.suspended = definition.isSuspended(); + dto.tenantId = definition.getTenantId(); + dto.versionTag = definition.getVersionTag(); + dto.historyTimeToLive = definition.getHistoryTimeToLive(); + dto.isStartableInTasklist = definition.isStartableInTasklist(); + + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionDiagramDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionDiagramDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2e3e014f522dc0c04b380e3df80b98cbba7db79b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionDiagramDto.java @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseDefinitionDiagramDto { + + protected String id; + protected String cmmnXml; + + public String getId() { + return id; + } + + public String getCmmnXml() { + return cmmnXml; + } + + public static CaseDefinitionDiagramDto create(String id, String cmmnXml) { + CaseDefinitionDiagramDto dto = new CaseDefinitionDiagramDto(); + + dto.id = id; + dto.cmmnXml = cmmnXml; + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e0cd64286da78b3b32eaaa3a06dd0ece2b89c307 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionDto.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.repository.CaseDefinition; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseDefinitionDto { + + protected String id; + protected String key; + protected String category; + protected String name; + protected int version; + protected String resource; + protected String deploymentId; + protected String tenantId; + protected Integer historyTimeToLive; + + public String getId() { + return id; + } + + public String getKey() { + return key; + } + + public String getCategory() { + return category; + } + + public String getName() { + return name; + } + + public int getVersion() { + return version; + } + + public String getResource() { + return resource; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getTenantId() { + return tenantId; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public static CaseDefinitionDto fromCaseDefinition(CaseDefinition definition) { + CaseDefinitionDto dto = new CaseDefinitionDto(); + + dto.id = definition.getId(); + dto.key = definition.getKey(); + dto.category = definition.getCategory(); + dto.name = definition.getName(); + dto.version = definition.getVersion(); + dto.resource = definition.getResourceName(); + dto.deploymentId = definition.getDeploymentId(); + dto.tenantId = definition.getTenantId(); + dto.historyTimeToLive = definition.getHistoryTimeToLive(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d144746fede6c45f6eb5e1da474d220f426aea69 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/CaseDefinitionQueryDto.java @@ -0,0 +1,259 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseDefinitionQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_ID_VALUE = "id"; + private static final String SORT_BY_KEY_VALUE = "key"; + private static final String SORT_BY_NAME_VALUE = "name"; + private static final String SORT_BY_VERSION_VALUE = "version"; + private static final String SORT_BY_DEPLOYMENT_ID_VALUE = "deploymentId"; + private static final String SORT_BY_CATEGORY_VALUE = "category"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + + VALID_SORT_BY_VALUES.add(SORT_BY_CATEGORY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_VERSION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOYMENT_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String caseDefinitionId; + protected List caseDefinitionIdIn; + protected String category; + protected String categoryLike; + protected String name; + protected String nameLike; + protected String deploymentId; + protected String key; + protected String keyLike; + protected String resourceName; + protected String resourceNameLike; + protected Integer version; + protected Boolean latestVersion; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean includeDefinitionsWithoutTenantId; + + public CaseDefinitionQueryDto() {} + + public CaseDefinitionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam(value = "caseDefinitionIdIn", converter = StringListConverter.class) + public void setCaseDefinitionIdIn(List caseDefinitionIdIn) { + this.caseDefinitionIdIn = caseDefinitionIdIn; + } + + @CamundaQueryParam("category") + public void setCategory(String category) { + this.category = category; + } + + @CamundaQueryParam("categoryLike") + public void setCategoryLike(String categoryLike) { + this.categoryLike = categoryLike; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + @CamundaQueryParam("key") + public void setKey(String key) { + this.key = key; + } + + @CamundaQueryParam("keyLike") + public void setKeyLike(String keyLike) { + this.keyLike = keyLike; + } + + @CamundaQueryParam("resourceName") + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + @CamundaQueryParam("resourceNameLike") + public void setResourceNameLike(String resourceNameLike) { + this.resourceNameLike = resourceNameLike; + } + + @CamundaQueryParam(value = "version", converter = IntegerConverter.class) + public void setVersion(Integer version) { + this.version = version; + } + + /** + * @deprecated use {@link #setLatestVersion(Boolean)} + */ + @Deprecated + @CamundaQueryParam(value = "latest", converter = BooleanConverter.class) + public void setLatest(Boolean latest) { + setLatestVersion(latest); + } + + @CamundaQueryParam(value = "latestVersion", converter = BooleanConverter.class) + public void setLatestVersion(Boolean latestVersion) { + this.latestVersion = latestVersion; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "includeCaseDefinitionsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeCaseDefinitionsWithoutTenantId(Boolean includeDefinitionsWithoutTenantId) { + this.includeDefinitionsWithoutTenantId = includeDefinitionsWithoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected CaseDefinitionQuery createNewQuery(ProcessEngine engine) { + return engine.getRepositoryService().createCaseDefinitionQuery(); + } + + @Override + protected void applyFilters(CaseDefinitionQuery query) { + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (caseDefinitionIdIn != null && !caseDefinitionIdIn.isEmpty()) { + query.caseDefinitionIdIn(caseDefinitionIdIn.toArray(new String[caseDefinitionIdIn.size()])); + } + if (category != null) { + query.caseDefinitionCategory(category); + } + if (categoryLike != null) { + query.caseDefinitionCategoryLike(categoryLike); + } + if (name != null) { + query.caseDefinitionName(name); + } + if (nameLike != null) { + query.caseDefinitionNameLike(nameLike); + } + if (deploymentId != null) { + query.deploymentId(deploymentId); + } + if (key != null) { + query.caseDefinitionKey(key); + } + if (keyLike != null) { + query.caseDefinitionKeyLike(keyLike); + } + if (resourceName != null) { + query.caseDefinitionResourceName(resourceName); + } + if (resourceNameLike != null) { + query.caseDefinitionResourceNameLike(resourceNameLike); + } + if (version != null) { + query.caseDefinitionVersion(version); + } + if (TRUE.equals(latestVersion)) { + query.latestVersion(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeDefinitionsWithoutTenantId)) { + query.includeCaseDefinitionsWithoutTenantId(); + } + } + + @Override + protected void applySortBy(CaseDefinitionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { + query.orderByCaseDefinitionCategory(); + } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { + query.orderByCaseDefinitionKey(); + } else if (sortBy.equals(SORT_BY_ID_VALUE)) { + query.orderByCaseDefinitionId(); + } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { + query.orderByCaseDefinitionVersion(); + } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { + query.orderByCaseDefinitionName(); + } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { + query.orderByDeploymentId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionDiagramDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionDiagramDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c07818c1d73b29e6a8d730629b02c887d8727601 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionDiagramDto.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +public class DecisionDefinitionDiagramDto { + + protected String id; + protected String dmnXml; + + public String getId() { + return id; + } + + public String getDmnXml() { + return dmnXml; + } + + public static DecisionDefinitionDiagramDto create(String id, String dmnXml) { + DecisionDefinitionDiagramDto dto = new DecisionDefinitionDiagramDto(); + + dto.id = id; + dto.dmnXml = dmnXml; + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b4ce0ae39d188a7d500a6029c3092f489050690e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionDto.java @@ -0,0 +1,103 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.repository.DecisionDefinition; + +public class DecisionDefinitionDto { + + protected String id; + protected String key; + protected String category; + protected String name; + protected int version; + protected String resource; + protected String deploymentId; + protected String tenantId; + protected String decisionRequirementsDefinitionId; + protected String decisionRequirementsDefinitionKey; + protected Integer historyTimeToLive; + protected String versionTag; + + public String getId() { + return id; + } + + public String getKey() { + return key; + } + + public String getCategory() { + return category; + } + + public String getName() { + return name; + } + + public int getVersion() { + return version; + } + + public String getResource() { + return resource; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getTenantId() { + return tenantId; + } + + public String getDecisionRequirementsDefinitionId() { + return decisionRequirementsDefinitionId; + } + + public String getDecisionRequirementsDefinitionKey() { + return decisionRequirementsDefinitionKey; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public String getVersionTag(){ + return versionTag; + } + + public static DecisionDefinitionDto fromDecisionDefinition(DecisionDefinition definition) { + DecisionDefinitionDto dto = new DecisionDefinitionDto(); + + dto.id = definition.getId(); + dto.key = definition.getKey(); + dto.category = definition.getCategory(); + dto.name = definition.getName(); + dto.version = definition.getVersion(); + dto.resource = definition.getResourceName(); + dto.deploymentId = definition.getDeploymentId(); + dto.decisionRequirementsDefinitionId = definition.getDecisionRequirementsDefinitionId(); + dto.decisionRequirementsDefinitionKey = definition.getDecisionRequirementsDefinitionKey(); + dto.tenantId = definition.getTenantId(); + dto.historyTimeToLive = definition.getHistoryTimeToLive(); + dto.versionTag = definition.getVersionTag(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..7b65722a15a85e5dde40d9c1fe7a15ddbb7b093f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionDefinitionQueryDto.java @@ -0,0 +1,322 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.DecisionDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class DecisionDefinitionQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_ID_VALUE = "id"; + private static final String SORT_BY_KEY_VALUE = "key"; + private static final String SORT_BY_NAME_VALUE = "name"; + private static final String SORT_BY_VERSION_VALUE = "version"; + private static final String SORT_BY_DEPLOYMENT_ID_VALUE = "deploymentId"; + private static final String SORT_BY_DEPLOY_TIME_VALUE = "deployTime"; + private static final String SORT_BY_CATEGORY_VALUE = "category"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + private static final String SORT_BY_VERSION_TAG = "versionTag"; + private static final String SORT_BY_DECISION_REQUIREMENTS_DEFINITION_KEY = "decisionRequirementsDefinitionKey"; + + private static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + + VALID_SORT_BY_VALUES.add(SORT_BY_CATEGORY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_VERSION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOYMENT_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOY_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_VERSION_TAG); + VALID_SORT_BY_VALUES.add(SORT_BY_DECISION_REQUIREMENTS_DEFINITION_KEY); + } + + protected String decisionDefinitionId; + protected List decisionDefinitionIdIn; + protected String category; + protected String categoryLike; + protected String name; + protected String nameLike; + protected String deploymentId; + protected Date deployedAfter; + protected Date deployedAt; + protected String key; + protected String keyLike; + protected String resourceName; + protected String resourceNameLike; + protected Integer version; + protected Boolean latestVersion; + protected String decisionRequirementsDefinitionId; + protected String decisionRequirementsDefinitionKey; + protected Boolean withoutDecisionRequirementsDefinition; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean includeDefinitionsWithoutTenantId; + private String versionTag; + private String versionTagLike; + + public DecisionDefinitionQueryDto() {} + + public DecisionDefinitionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("decisionDefinitionId") + public void setDecisionDefinitionId(String decisionDefinitionId) { + this.decisionDefinitionId = decisionDefinitionId; + } + + @CamundaQueryParam(value = "decisionDefinitionIdIn", converter = StringListConverter.class) + public void setDecisionDefinitionIdIn(List decisionDefinitionIdIn) { + this.decisionDefinitionIdIn = decisionDefinitionIdIn; + } + + @CamundaQueryParam("category") + public void setCategory(String category) { + this.category = category; + } + + @CamundaQueryParam("categoryLike") + public void setCategoryLike(String categoryLike) { + this.categoryLike = categoryLike; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + @CamundaQueryParam(value = "deployedAfter", converter = DateConverter.class) + public void setDeployedAfter(Date deployedAfter) { + this.deployedAfter = deployedAfter; + } + + @CamundaQueryParam(value = "deployedAt", converter = DateConverter.class) + public void setDeployedAt(Date deployedAt) { + this.deployedAt = deployedAt; + } + + @CamundaQueryParam("key") + public void setKey(String key) { + this.key = key; + } + + @CamundaQueryParam("keyLike") + public void setKeyLike(String keyLike) { + this.keyLike = keyLike; + } + + @CamundaQueryParam("resourceName") + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + @CamundaQueryParam("resourceNameLike") + public void setResourceNameLike(String resourceNameLike) { + this.resourceNameLike = resourceNameLike; + } + + @CamundaQueryParam(value = "version", converter = IntegerConverter.class) + public void setVersion(Integer version) { + this.version = version; + } + + @CamundaQueryParam(value = "latestVersion", converter = BooleanConverter.class) + public void setLatestVersion(Boolean latestVersion) { + this.latestVersion = latestVersion; + } + + @CamundaQueryParam(value = "decisionRequirementsDefinitionId") + public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { + this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; + } + + @CamundaQueryParam(value = "decisionRequirementsDefinitionKey") + public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { + this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; + } + + @CamundaQueryParam(value = "withoutDecisionRequirementsDefinition", converter = BooleanConverter.class) + public void setWithoutDecisionRequirementsDefinition(Boolean withoutDecisionRequirementsDefinition) { + this.withoutDecisionRequirementsDefinition = withoutDecisionRequirementsDefinition; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "includeDecisionDefinitionsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeDecisionDefinitionsWithoutTenantId(Boolean includeDefinitionsWithoutTenantId) { + this.includeDefinitionsWithoutTenantId = includeDefinitionsWithoutTenantId; + } + + @CamundaQueryParam(value = "versionTag") + public void setVersionTag(String versionTag) { + this.versionTag = versionTag; + } + + @CamundaQueryParam(value = "versionTagLike") + public void setVersionTagLike(String versionTagLike) { + this.versionTagLike = versionTagLike; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected DecisionDefinitionQuery createNewQuery(ProcessEngine engine) { + return engine.getRepositoryService().createDecisionDefinitionQuery(); + } + + @Override + protected void applyFilters(DecisionDefinitionQuery query) { + if (decisionDefinitionId != null) { + query.decisionDefinitionId(decisionDefinitionId); + } + if (decisionDefinitionIdIn != null && !decisionDefinitionIdIn.isEmpty()) { + query.decisionDefinitionIdIn(decisionDefinitionIdIn.toArray(new String[decisionDefinitionIdIn.size()])); + } + if (category != null) { + query.decisionDefinitionCategory(category); + } + if (categoryLike != null) { + query.decisionDefinitionCategoryLike(categoryLike); + } + if (name != null) { + query.decisionDefinitionName(name); + } + if (nameLike != null) { + query.decisionDefinitionNameLike(nameLike); + } + if (deploymentId != null) { + query.deploymentId(deploymentId); + } + if (deployedAfter != null) { + query.deployedAfter(deployedAfter); + } + if (deployedAt != null) { + query.deployedAt(deployedAt); + } + if (key != null) { + query.decisionDefinitionKey(key); + } + if (keyLike != null) { + query.decisionDefinitionKeyLike(keyLike); + } + if (resourceName != null) { + query.decisionDefinitionResourceName(resourceName); + } + if (resourceNameLike != null) { + query.decisionDefinitionResourceNameLike(resourceNameLike); + } + if (version != null) { + query.decisionDefinitionVersion(version); + } + if (TRUE.equals(latestVersion)) { + query.latestVersion(); + } + if (decisionRequirementsDefinitionId != null) { + query.decisionRequirementsDefinitionId(decisionRequirementsDefinitionId); + } + if (decisionRequirementsDefinitionKey != null) { + query.decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey); + } + if (TRUE.equals(withoutDecisionRequirementsDefinition)) { + query.withoutDecisionRequirementsDefinition(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeDefinitionsWithoutTenantId)) { + query.includeDecisionDefinitionsWithoutTenantId(); + } + if( versionTag != null) { + query.versionTag(versionTag); + } + if( versionTagLike != null) { + query.versionTagLike(versionTagLike); + } + } + + @Override + protected void applySortBy(DecisionDefinitionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { + query.orderByDecisionDefinitionCategory(); + } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { + query.orderByDecisionDefinitionKey(); + } else if (sortBy.equals(SORT_BY_ID_VALUE)) { + query.orderByDecisionDefinitionId(); + } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { + query.orderByDecisionDefinitionVersion(); + } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { + query.orderByDecisionDefinitionName(); + } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { + query.orderByDeploymentId(); + } else if (sortBy.equals(SORT_BY_DEPLOY_TIME_VALUE)) { + query.orderByDeploymentTime(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } else if (sortBy.equals(SORT_BY_VERSION_TAG)) { + query.orderByVersionTag(); + } else if (sortBy.equals(SORT_BY_DECISION_REQUIREMENTS_DEFINITION_KEY)) { + query.orderByDecisionRequirementsDefinitionKey(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5b50111771abd1a1884ec79c4c7947e5d9e0885a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionDto.java @@ -0,0 +1,79 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinition; + +public class DecisionRequirementsDefinitionDto { + + protected String id; + protected String key; + protected String category; + protected String name; + protected int version; + protected String resource; + protected String deploymentId; + protected String tenantId; + + public String getId() { + return id; + } + + public String getKey() { + return key; + } + + public String getCategory() { + return category; + } + + public String getName() { + return name; + } + + public int getVersion() { + return version; + } + + public String getResource() { + return resource; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getTenantId() { + return tenantId; + } + + public static DecisionRequirementsDefinitionDto fromDecisionRequirementsDefinition(DecisionRequirementsDefinition definition) { + DecisionRequirementsDefinitionDto dto = new DecisionRequirementsDefinitionDto(); + + dto.id = definition.getId(); + dto.key = definition.getKey(); + dto.category = definition.getCategory(); + dto.name = definition.getName(); + dto.version = definition.getVersion(); + dto.resource = definition.getResourceName(); + dto.deploymentId = definition.getDeploymentId(); + dto.tenantId = definition.getTenantId(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..77741a83f3fbac433dc9e68d0f2baa8915730780 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionQueryDto.java @@ -0,0 +1,246 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class DecisionRequirementsDefinitionQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_ID_VALUE = "id"; + private static final String SORT_BY_KEY_VALUE = "key"; + private static final String SORT_BY_NAME_VALUE = "name"; + private static final String SORT_BY_VERSION_VALUE = "version"; + private static final String SORT_BY_DEPLOYMENT_ID_VALUE = "deploymentId"; + private static final String SORT_BY_CATEGORY_VALUE = "category"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + + static { + VALID_SORT_BY_VALUES = new ArrayList(); + + VALID_SORT_BY_VALUES.add(SORT_BY_CATEGORY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_VERSION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOYMENT_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + + } + + protected String decisionRequirementsDefinitionId; + protected List decisionRequirementsDefinitionIdIn; + protected String category; + protected String categoryLike; + protected String name; + protected String nameLike; + protected String deploymentId; + protected String key; + protected String keyLike; + protected String resourceName; + protected String resourceNameLike; + protected Integer version; + protected Boolean latestVersion; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean includeDefinitionsWithoutTenantId; + + public DecisionRequirementsDefinitionQueryDto() {} + + public DecisionRequirementsDefinitionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("decisionRequirementsDefinitionId") + public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { + this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; + } + + @CamundaQueryParam(value = "decisionRequirementsDefinitionIdIn", converter = StringListConverter.class) + public void setDecisionRequirementsDefinitionIdIn(List decisionRequirementsDefinitionIdIn) { + this.decisionRequirementsDefinitionIdIn = decisionRequirementsDefinitionIdIn; + } + + @CamundaQueryParam("category") + public void setCategory(String category) { + this.category = category; + } + + @CamundaQueryParam("categoryLike") + public void setCategoryLike(String categoryLike) { + this.categoryLike = categoryLike; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + @CamundaQueryParam("key") + public void setKey(String key) { + this.key = key; + } + + @CamundaQueryParam("keyLike") + public void setKeyLike(String keyLike) { + this.keyLike = keyLike; + } + + @CamundaQueryParam("resourceName") + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + @CamundaQueryParam("resourceNameLike") + public void setResourceNameLike(String resourceNameLike) { + this.resourceNameLike = resourceNameLike; + } + + @CamundaQueryParam(value = "version", converter = IntegerConverter.class) + public void setVersion(Integer version) { + this.version = version; + } + + @CamundaQueryParam(value = "latestVersion", converter = BooleanConverter.class) + public void setLatestVersion(Boolean latestVersion) { + this.latestVersion = latestVersion; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "includeDecisionRequirementsDefinitionsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeDecisionRequirementsDefinitionsWithoutTenantId(Boolean includeDefinitionsWithoutTenantId) { + this.includeDefinitionsWithoutTenantId = includeDefinitionsWithoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected DecisionRequirementsDefinitionQuery createNewQuery(ProcessEngine engine) { + return engine.getRepositoryService().createDecisionRequirementsDefinitionQuery(); + } + + @Override + protected void applyFilters(DecisionRequirementsDefinitionQuery query) { + if (decisionRequirementsDefinitionId != null) { + query.decisionRequirementsDefinitionId(decisionRequirementsDefinitionId); + } + if (decisionRequirementsDefinitionIdIn != null && !decisionRequirementsDefinitionIdIn.isEmpty()) { + query.decisionRequirementsDefinitionIdIn(decisionRequirementsDefinitionIdIn.toArray(new String[decisionRequirementsDefinitionIdIn.size()])); + } + if (category != null) { + query.decisionRequirementsDefinitionCategory(category); + } + if (categoryLike != null) { + query.decisionRequirementsDefinitionCategoryLike(categoryLike); + } + if (name != null) { + query.decisionRequirementsDefinitionName(name); + } + if (nameLike != null) { + query.decisionRequirementsDefinitionNameLike(nameLike); + } + if (deploymentId != null) { + query.deploymentId(deploymentId); + } + if (key != null) { + query.decisionRequirementsDefinitionKey(key); + } + if (keyLike != null) { + query.decisionRequirementsDefinitionKeyLike(keyLike); + } + if (resourceName != null) { + query.decisionRequirementsDefinitionResourceName(resourceName); + } + if (resourceNameLike != null) { + query.decisionRequirementsDefinitionResourceNameLike(resourceNameLike); + } + if (version != null) { + query.decisionRequirementsDefinitionVersion(version); + } + if (TRUE.equals(latestVersion)) { + query.latestVersion(); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeDefinitionsWithoutTenantId)) { + query.includeDecisionRequirementsDefinitionsWithoutTenantId(); + } + } + + @Override + protected void applySortBy(DecisionRequirementsDefinitionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { + query.orderByDecisionRequirementsDefinitionCategory(); + } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { + query.orderByDecisionRequirementsDefinitionKey(); + } else if (sortBy.equals(SORT_BY_ID_VALUE)) { + query.orderByDecisionRequirementsDefinitionId(); + } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { + query.orderByDecisionRequirementsDefinitionVersion(); + } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { + query.orderByDecisionRequirementsDefinitionName(); + } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { + query.orderByDeploymentId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionXmlDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionXmlDto.java new file mode 100644 index 0000000000000000000000000000000000000000..7d4df03dd0d10b049bffeb9bc6a5870c166679ff --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DecisionRequirementsDefinitionXmlDto.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +public class DecisionRequirementsDefinitionXmlDto { + + protected String id; + protected String dmnXml; + + public String getId() { + return id; + } + + public String getDmnXml() { + return dmnXml; + } + + public static DecisionRequirementsDefinitionXmlDto create(String id, String dmnXml) { + DecisionRequirementsDefinitionXmlDto dto = new DecisionRequirementsDefinitionXmlDto(); + + dto.id = id; + dto.dmnXml = dmnXml; + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e66dbc884509b56898c55e3a1e4c60f37ba422ed --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentDto.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import java.util.*; + +import org.camunda.bpm.engine.repository.*; +import org.camunda.bpm.engine.rest.dto.LinkableDto; + +public class DeploymentDto extends LinkableDto { + + protected String id; + protected String name; + protected String source; + protected Date deploymentTime; + protected String tenantId; + + public DeploymentDto() { + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getSource() { + return source; + } + + public Date getDeploymentTime() { + return deploymentTime; + } + + public String getTenantId() { + return tenantId; + } + + public static DeploymentDto fromDeployment(Deployment deployment) { + DeploymentDto dto = new DeploymentDto(); + dto.id = deployment.getId(); + dto.name = deployment.getName(); + dto.source = deployment.getSource(); + dto.deploymentTime = deployment.getDeploymentTime(); + dto.tenantId = deployment.getTenantId(); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bd2e38b69fb0318360c9dc4fa7eeb4201f3a2946 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentQueryDto.java @@ -0,0 +1,185 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.DeploymentQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class DeploymentQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_ID_VALUE = "id"; + private static final String SORT_BY_NAME_VALUE = "name"; + private static final String SORT_BY_DEPLOYMENT_TIME_VALUE = "deploymentTime"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOYMENT_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + private String id; + private String name; + private String nameLike; + private String source; + private Boolean withoutSource; + private Date before; + private Date after; + private List tenantIds; + private Boolean withoutTenantId; + private Boolean includeDeploymentsWithoutTenantId; + + public DeploymentQueryDto() { + } + + public DeploymentQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("id") + public void setId(String id) { + this.id = id; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("source") + public void setSource(String source) { + this.source = source; + } + + @CamundaQueryParam(value = "withoutSource", converter = BooleanConverter.class) + public void setWithoutSource(Boolean withoutSource) { + this.withoutSource = withoutSource; + } + + @CamundaQueryParam(value = "before", converter = DateConverter.class) + public void setDeploymentBefore(Date deploymentBefore) { + this.before = deploymentBefore; + } + + @CamundaQueryParam(value = "after", converter = DateConverter.class) + public void setDeploymentAfter(Date deploymentAfter) { + this.after = deploymentAfter; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "includeDeploymentsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeDeploymentsWithoutTenantId(Boolean includeDeploymentsWithoutTenantId) { + this.includeDeploymentsWithoutTenantId = includeDeploymentsWithoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected DeploymentQuery createNewQuery(ProcessEngine engine) { + return engine.getRepositoryService().createDeploymentQuery(); + } + + @Override + protected void applyFilters(DeploymentQuery query) { + if (withoutSource != null && withoutSource && source != null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "The query parameters \"withoutSource\" and \"source\" cannot be used in combination."); + } + + if (id != null) { + query.deploymentId(id); + } + if (name != null) { + query.deploymentName(name); + } + if (nameLike != null) { + query.deploymentNameLike(nameLike); + } + if (TRUE.equals(withoutSource)) { + query.deploymentSource(null); + } + if (source != null) { + query.deploymentSource(source); + } + if (before != null) { + query.deploymentBefore(before); + } + if (after != null) { + query.deploymentAfter(after); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeDeploymentsWithoutTenantId)) { + query.includeDeploymentsWithoutTenantId(); + } + } + + @Override + protected void applySortBy(DeploymentQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_ID_VALUE)) { + query.orderByDeploymentId(); + } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { + query.orderByDeploymentName(); + } else if (sortBy.equals(SORT_BY_DEPLOYMENT_TIME_VALUE)) { + query.orderByDeploymentTime(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentResourceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentResourceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..19bc9e99443b03704fcd3d968dff215b0c1334a5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentResourceDto.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.repository.Resource; + +public class DeploymentResourceDto { + + protected String id; + protected String name; + protected String deploymentId; + + public DeploymentResourceDto() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDeploymentId() { + return deploymentId; + } + + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + public static DeploymentResourceDto fromResources(Resource resource) { + DeploymentResourceDto dto = new DeploymentResourceDto(); + dto.id = resource.getId(); + dto.name = resource.getName(); + dto.deploymentId = resource.getDeploymentId(); + + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentWithDefinitionsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentWithDefinitionsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5621d422df83f98c491d43f1c6b7f691084e3cdc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/DeploymentWithDefinitionsDto.java @@ -0,0 +1,101 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.repository.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author Christopher Zell + */ +public class DeploymentWithDefinitionsDto extends DeploymentDto { + + protected Map deployedProcessDefinitions; + protected Map deployedCaseDefinitions; + protected Map deployedDecisionDefinitions; + protected Map deployedDecisionRequirementsDefinitions; + + public Map getDeployedProcessDefinitions() { + return deployedProcessDefinitions; + } + + public Map getDeployedCaseDefinitions() { + return deployedCaseDefinitions; + } + + public Map getDeployedDecisionDefinitions() { + return deployedDecisionDefinitions; + } + + public Map getDeployedDecisionRequirementsDefinitions() { + return deployedDecisionRequirementsDefinitions; + } + + public static DeploymentWithDefinitionsDto fromDeployment(DeploymentWithDefinitions deployment) { + DeploymentWithDefinitionsDto dto = new DeploymentWithDefinitionsDto(); + dto.id = deployment.getId(); + dto.name = deployment.getName(); + dto.source = deployment.getSource(); + dto.deploymentTime = deployment.getDeploymentTime(); + dto.tenantId = deployment.getTenantId(); + + initDeployedResourceLists(deployment, dto); + + return dto; + } + + private static void initDeployedResourceLists(DeploymentWithDefinitions deployment, DeploymentWithDefinitionsDto dto) { + List deployedProcessDefinitions = deployment.getDeployedProcessDefinitions(); + if (deployedProcessDefinitions != null) { + dto.deployedProcessDefinitions = new HashMap(); + for (ProcessDefinition processDefinition : deployedProcessDefinitions) { + dto.deployedProcessDefinitions + .put(processDefinition.getId(), ProcessDefinitionDto.fromProcessDefinition(processDefinition)); + } + } + + List deployedCaseDefinitions = deployment.getDeployedCaseDefinitions(); + if (deployedCaseDefinitions != null) { + dto.deployedCaseDefinitions = new HashMap(); + for (CaseDefinition caseDefinition : deployedCaseDefinitions) { + dto.deployedCaseDefinitions + .put(caseDefinition.getId(), CaseDefinitionDto.fromCaseDefinition(caseDefinition)); + } + } + + List deployedDecisionDefinitions = deployment.getDeployedDecisionDefinitions(); + if (deployedDecisionDefinitions != null) { + dto.deployedDecisionDefinitions = new HashMap(); + for (DecisionDefinition decisionDefinition : deployedDecisionDefinitions) { + dto.deployedDecisionDefinitions + .put(decisionDefinition.getId(), DecisionDefinitionDto.fromDecisionDefinition(decisionDefinition)); + } + } + + List deployedDecisionRequirementsDefinitions = deployment.getDeployedDecisionRequirementsDefinitions(); + if (deployedDecisionRequirementsDefinitions != null) { + dto.deployedDecisionRequirementsDefinitions = new HashMap(); + for (DecisionRequirementsDefinition drd : deployedDecisionRequirementsDefinitions) { + dto.deployedDecisionRequirementsDefinitions + .put(drd.getId(), DecisionRequirementsDefinitionDto.fromDecisionRequirementsDefinition(drd)); + } + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/IncidentStatisticsResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/IncidentStatisticsResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..710eda45d46bb829fe08df119d5cfd8cf2d7732b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/IncidentStatisticsResultDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.management.IncidentStatistics; + +/** + * @author roman.smirnov + */ +public class IncidentStatisticsResultDto { + + protected String incidentType; + protected Integer incidentCount; + + public IncidentStatisticsResultDto() {} + + public String getIncidentType() { + return incidentType; + } + + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + public Integer getIncidentCount() { + return incidentCount; + } + + public void setIncidentCount(Integer incidentCount) { + this.incidentCount = incidentCount; + } + + public static IncidentStatisticsResultDto fromIncidentStatistics(IncidentStatistics statistics) { + IncidentStatisticsResultDto dto = new IncidentStatisticsResultDto(); + dto.setIncidentType(statistics.getIncidentType()); + dto.setIncidentCount(statistics.getIncidentCount()); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionDiagramDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionDiagramDto.java new file mode 100644 index 0000000000000000000000000000000000000000..53ba85ca0d68962e6431a0ebc7d44e5cbf4e8ebc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionDiagramDto.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + + +public class ProcessDefinitionDiagramDto { + + private String id; + private String bpmn20Xml; + + public String getId() { + return id; + } + + public String getBpmn20Xml() { + return bpmn20Xml; + } + + public static ProcessDefinitionDiagramDto create(String id, String bpmn20Xml) { + ProcessDefinitionDiagramDto processDefinitionDiagramDto = new ProcessDefinitionDiagramDto(); + processDefinitionDiagramDto.id = id; + processDefinitionDiagramDto.bpmn20Xml = bpmn20Xml; + + return processDefinitionDiagramDto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0fad961f25805c0f1cbc356460575d7004c4ee23 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionDto.java @@ -0,0 +1,113 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.repository.ProcessDefinition; + +public class ProcessDefinitionDto { + + protected String id; + protected String key; + protected String category; + protected String description; + protected String name; + protected int version; + protected String resource; + protected String deploymentId; + protected String diagram; + protected boolean suspended; + protected String tenantId; + protected String versionTag; + protected Integer historyTimeToLive; + protected boolean isStartableInTasklist; + + public String getId() { + return id; + } + + public String getKey() { + return key; + } + + public String getCategory() { + return category; + } + + public String getDescription() { + return description; + } + + public String getName() { + return name; + } + + public int getVersion() { + return version; + } + + public String getResource() { + return resource; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getDiagram() { + return diagram; + } + + public boolean isSuspended() { + return suspended; + } + + public String getTenantId() { + return tenantId; + } + + public String getVersionTag() { + return versionTag; + } + + public Integer getHistoryTimeToLive() { + return historyTimeToLive; + } + + public boolean isStartableInTasklist() { + return isStartableInTasklist; + } + + public static ProcessDefinitionDto fromProcessDefinition(ProcessDefinition definition) { + ProcessDefinitionDto dto = new ProcessDefinitionDto(); + dto.id = definition.getId(); + dto.key = definition.getKey(); + dto.category = definition.getCategory(); + dto.description = definition.getDescription(); + dto.name = definition.getName(); + dto.version = definition.getVersion(); + dto.resource = definition.getResourceName(); + dto.deploymentId = definition.getDeploymentId(); + dto.diagram = definition.getDiagramResourceName(); + dto.suspended = definition.isSuspended(); + dto.tenantId = definition.getTenantId(); + dto.versionTag = definition.getVersionTag(); + dto.historyTimeToLive = definition.getHistoryTimeToLive(); + dto.isStartableInTasklist = definition.isStartableInTasklist(); + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9496288a708aee3ddbd0bce98ab56d3185c29102 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionQueryDto.java @@ -0,0 +1,419 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ProcessDefinitionQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_CATEGORY_VALUE = "category"; + private static final String SORT_BY_KEY_VALUE = "key"; + private static final String SORT_BY_ID_VALUE = "id"; + private static final String SORT_BY_NAME_VALUE = "name"; + private static final String SORT_BY_VERSION_VALUE = "version"; + private static final String SORT_BY_DEPLOYMENT_ID_VALUE = "deploymentId"; + private static final String SORT_BY_DEPLOY_TIME_VALUE = "deployTime"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + private static final String SORT_BY_VERSION_TAG = "versionTag"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_CATEGORY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_VERSION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOYMENT_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_VERSION_TAG); + VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOY_TIME_VALUE); + } + + protected String processDefinitionId; + protected List processDefinitionIdIn; + protected String category; + protected String categoryLike; + protected String name; + protected String nameLike; + protected String deploymentId; + protected Date deployedAfter; + protected Date deployedAt; + protected String key; + protected String keyLike; + protected Integer version; + protected Boolean latestVersion; + protected String resourceName; + protected String resourceNameLike; + protected String startableBy; + protected Boolean active; + protected Boolean suspended; + protected String incidentId; + protected String incidentType; + protected String incidentMessage; + protected String incidentMessageLike; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean includeDefinitionsWithoutTenantId; + protected String versionTag; + protected String versionTagLike; + protected Boolean withoutVersionTag; + protected List keys; + protected Boolean startableInTasklist; + protected Boolean notStartableInTasklist; + protected Boolean startablePermissionCheck; + + public ProcessDefinitionQueryDto() { + + } + + public ProcessDefinitionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam(value = "processDefinitionIdIn", converter = StringListConverter.class) + public void setProcessDefinitionIdIn(List processDefinitionIdIn) { + this.processDefinitionIdIn = processDefinitionIdIn; + } + + @CamundaQueryParam("category") + public void setCategory(String category) { + this.category = category; + } + + @CamundaQueryParam("categoryLike") + public void setCategoryLike(String categoryLike) { + this.categoryLike = categoryLike; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + @CamundaQueryParam(value = "deployedAfter", converter = DateConverter.class) + public void setDeployedAfter(Date deployedAfter) { + this.deployedAfter = deployedAfter; + } + + @CamundaQueryParam(value = "deployedAt", converter = DateConverter.class) + public void setDeployedAt(Date deployedAt) { + this.deployedAt = deployedAt; + } + + @CamundaQueryParam("key") + public void setKey(String key) { + this.key = key; + } + + + @CamundaQueryParam(value = "keysIn", converter = StringListConverter.class) + public void setKeysIn(List keys) { + this.keys = keys; + } + + @CamundaQueryParam("keyLike") + public void setKeyLike(String keyLike) { + this.keyLike = keyLike; + } + + /** + * @deprecated use {@link #setVersion(Integer)} + */ + @Deprecated + @CamundaQueryParam(value = "ver", converter = IntegerConverter.class) + public void setVer(Integer ver) { + setVersion(ver); + } + + @CamundaQueryParam(value = "version", converter = IntegerConverter.class) + public void setVersion(Integer version) { + this.version = version; + } + + /** + * @deprecated use {@link #setLatestVersion(Boolean)} + */ + @Deprecated + @CamundaQueryParam(value = "latest", converter = BooleanConverter.class) + public void setLatest(Boolean latest) { + setLatestVersion(latest); + } + + @CamundaQueryParam(value = "latestVersion", converter = BooleanConverter.class) + public void setLatestVersion(Boolean latestVersion) { + this.latestVersion = latestVersion; + } + + @CamundaQueryParam("resourceName") + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + @CamundaQueryParam("resourceNameLike") + public void setResourceNameLike(String resourceNameLike) { + this.resourceNameLike = resourceNameLike; + } + + @CamundaQueryParam("startableBy") + public void setStartableBy(String startableBy) { + this.startableBy = startableBy; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value = "incidentId") + public void setIncidentId(String incidentId) { + this.incidentId = incidentId; + } + + @CamundaQueryParam(value = "incidentType") + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + @CamundaQueryParam(value = "incidentMessage") + public void setIncidentMessage(String incidentMessage) { + this.incidentMessage = incidentMessage; + } + + @CamundaQueryParam(value = "incidentMessageLike") + public void setIncidentMessageLike(String incidentMessageLike) { + this.incidentMessageLike = incidentMessageLike; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "includeProcessDefinitionsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeProcessDefinitionsWithoutTenantId(Boolean includeDefinitionsWithoutTenantId) { + this.includeDefinitionsWithoutTenantId = includeDefinitionsWithoutTenantId; + } + + @CamundaQueryParam(value = "versionTag") + public void setVersionTag(String versionTag) { + this.versionTag = versionTag; + } + + @CamundaQueryParam(value = "versionTagLike") + public void setVersionTagLike(String versionTagLike) { + this.versionTagLike = versionTagLike; + } + + @CamundaQueryParam(value = "withoutVersionTag", converter = BooleanConverter.class) + public void setWithoutVersionTag(Boolean withoutVersionTag) { + this.withoutVersionTag = withoutVersionTag; + } + + @CamundaQueryParam(value = "startableInTasklist", converter = BooleanConverter.class) + public void setStartableInTasklist(Boolean startableInTasklist) { + this.startableInTasklist = startableInTasklist; + } + + @CamundaQueryParam(value = "notStartableInTasklist", converter = BooleanConverter.class) + public void setNotStartableInTasklist(Boolean notStartableInTasklist) { + this.notStartableInTasklist = notStartableInTasklist; + } + + @CamundaQueryParam(value = "startablePermissionCheck", converter = BooleanConverter.class) + public void setStartablePermissionCheck(Boolean startablePermissionCheck) { + this.startablePermissionCheck = startablePermissionCheck; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected ProcessDefinitionQuery createNewQuery(ProcessEngine engine) { + return engine.getRepositoryService().createProcessDefinitionQuery(); + } + + @Override + protected void applyFilters(ProcessDefinitionQuery query) { + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionIdIn != null && !processDefinitionIdIn.isEmpty()) { + query.processDefinitionIdIn(processDefinitionIdIn.toArray(new String[processDefinitionIdIn.size()])); + } + if (category != null) { + query.processDefinitionCategory(category); + } + if (categoryLike != null) { + query.processDefinitionCategoryLike(categoryLike); + } + if (name != null) { + query.processDefinitionName(name); + } + if (nameLike != null) { + query.processDefinitionNameLike(nameLike); + } + if (deploymentId != null) { + query.deploymentId(deploymentId); + } + if(deployedAfter != null) { + query.deployedAfter(deployedAfter); + } + if(deployedAt != null) { + query.deployedAt(deployedAt); + } + if (key != null) { + query.processDefinitionKey(key); + } + if (keyLike != null) { + query.processDefinitionKeyLike(keyLike); + } + + if (keys != null && !keys.isEmpty()) { + query.processDefinitionKeysIn(keys.toArray(new String[keys.size()])); + } + if (version != null) { + query.processDefinitionVersion(version); + } + if (TRUE.equals(latestVersion)) { + query.latestVersion(); + } + if (resourceName != null) { + query.processDefinitionResourceName(resourceName); + } + if (resourceNameLike != null) { + query.processDefinitionResourceNameLike(resourceNameLike); + } + if (startableBy != null) { + query.startableByUser(startableBy); + } + if (TRUE.equals(active)) { + query.active(); + } + if (TRUE.equals(suspended)) { + query.suspended(); + } + if (incidentId != null) { + query.incidentId(incidentId); + } + if (incidentType != null) { + query.incidentType(incidentType); + } + if (incidentMessage != null) { + query.incidentMessage(incidentMessage); + } + if (incidentMessageLike != null) { + query.incidentMessageLike(incidentMessageLike); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeDefinitionsWithoutTenantId)) { + query.includeProcessDefinitionsWithoutTenantId(); + } + if( versionTag != null) { + query.versionTag(versionTag); + } + if( versionTagLike != null) { + query.versionTagLike(versionTagLike); + } + if (TRUE.equals(withoutVersionTag)) { + query.withoutVersionTag(); + } + if (TRUE.equals(startableInTasklist)) { + query.startableInTasklist(); + } + if (TRUE.equals(notStartableInTasklist)) { + query.notStartableInTasklist(); + } + if (TRUE.equals(startablePermissionCheck)) { + query.startablePermissionCheck(); + } + + } + + @Override + protected void applySortBy(ProcessDefinitionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { + query.orderByProcessDefinitionCategory(); + } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_ID_VALUE)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { + query.orderByProcessDefinitionVersion(); + } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { + query.orderByProcessDefinitionName(); + } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { + query.orderByDeploymentId(); + } else if (sortBy.equals(SORT_BY_DEPLOY_TIME_VALUE)) { + query.orderByDeploymentTime(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } else if (sortBy.equals(SORT_BY_VERSION_TAG)) { + query.orderByVersionTag(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionStatisticsResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionStatisticsResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ce92f9bb14c00bfbbae92b523bbefb079d813ba7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionStatisticsResultDto.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.management.IncidentStatistics; +import org.camunda.bpm.engine.management.ProcessDefinitionStatistics; +import org.camunda.bpm.engine.rest.dto.StatisticsResultDto; + +import java.util.ArrayList; + +public class ProcessDefinitionStatisticsResultDto extends StatisticsResultDto { + + private ProcessDefinitionDto definition; + + public ProcessDefinitionDto getDefinition() { + return definition; + } + + public void setDefinition(ProcessDefinitionDto definition) { + this.definition = definition; + } + + public static ProcessDefinitionStatisticsResultDto fromProcessDefinitionStatistics(ProcessDefinitionStatistics statistics) { + ProcessDefinitionStatisticsResultDto dto = new ProcessDefinitionStatisticsResultDto(); + + dto.definition = ProcessDefinitionDto.fromProcessDefinition(statistics); + dto.id = statistics.getId(); + dto.instances = statistics.getInstances(); + dto.failedJobs = statistics.getFailedJobs(); + + dto.incidents = new ArrayList(); + for (IncidentStatistics incident : statistics.getIncidentStatistics()) { + IncidentStatisticsResultDto incidentDto = IncidentStatisticsResultDto.fromIncidentStatistics(incident); + dto.incidents.add(incidentDto); + } + + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionSuspensionStateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionSuspensionStateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..437b8548c301d3d17a56dc06a66b80dcd66485f3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/ProcessDefinitionSuspensionStateDto.java @@ -0,0 +1,93 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import javax.ws.rs.core.Response.Status; +import java.util.Date; + +/** + * @author roman.smirnov + */ +public class ProcessDefinitionSuspensionStateDto extends SuspensionStateDto { + + private String executionDate; + private boolean includeProcessInstances; + private String processDefinitionId; + private String processDefinitionKey; + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public void setExecutionDate(String executionDate) { + this.executionDate = executionDate; + } + + public void setIncludeProcessInstances(boolean includeProcessInstances) { + this.includeProcessInstances = includeProcessInstances; + } + + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + public void updateSuspensionState(ProcessEngine engine) { + if (processDefinitionId != null && processDefinitionKey != null) { + String message = "Only one of processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + RepositoryService repositoryService = engine.getRepositoryService(); + + Date delayedExecutionDate = null; + if (executionDate != null && !executionDate.equals("")) { + delayedExecutionDate = DateTimeUtil.parseDate(executionDate); + } + + if (processDefinitionId != null) { + // activate/suspend process definition by id + if (getSuspended()) { + repositoryService.suspendProcessDefinitionById(processDefinitionId, includeProcessInstances, delayedExecutionDate); + } else { + repositoryService.activateProcessDefinitionById(processDefinitionId, includeProcessInstances, delayedExecutionDate); + } + } else + + if (processDefinitionKey != null) { + // activate/suspend process definition by key + if (getSuspended()) { + repositoryService.suspendProcessDefinitionByKey(processDefinitionKey, includeProcessInstances, delayedExecutionDate); + } else { + repositoryService.activateProcessDefinitionByKey(processDefinitionKey, includeProcessInstances, delayedExecutionDate); + } + } else { + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/RedeploymentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/RedeploymentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..32e40f0f5f93af25da0d62e141c0493a6bdff3a1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/RedeploymentDto.java @@ -0,0 +1,55 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +import java.util.List; + +/** + * @author Roman Smirnov + * + */ +public class RedeploymentDto { + + protected String source; + protected List resourceIds; + protected List resourceNames; + + public String getSource() { + return source; + } + + public void setSource(String source) { + this.source = source; + } + + public List getResourceIds() { + return resourceIds; + } + + public void setResourceIds(List resourceIds) { + this.resourceIds = resourceIds; + } + + public List getResourceNames() { + return resourceNames; + } + + public void setResourceNames(List resourceNames) { + this.resourceNames = resourceNames; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/StubProcessDefinitionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/StubProcessDefinitionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b228e2e0f059e0e4c15822ac2ae4c5ddfb908462 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/repository/StubProcessDefinitionDto.java @@ -0,0 +1,57 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.repository; + +/** + * Setters are only needed to create stub results. + * + * @author Thorben Lindhauer + * + */ +public class StubProcessDefinitionDto extends ProcessDefinitionDto { + + public void setId(String id) { + this.id = id; + } + public void setKey(String key) { + this.key = key; + } + public void setCategory(String category) { + this.category = category; + } + public void setDescription(String description) { + this.description = description; + } + public void setName(String name) { + this.name = name; + } + public void setVersion(int version) { + this.version = version; + } + public void setResource(String resource) { + this.resource = resource; + } + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + public void setDiagram(String diagram) { + this.diagram = diagram; + } + public void setSuspended(boolean suspended) { + this.suspended = suspended; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ActivityInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ActivityInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b540740925c94c4596d73f74ef7d5d06065a13f7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ActivityInstanceDto.java @@ -0,0 +1,134 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.runtime.ActivityInstance; + +/** + *

An activity instance is the instance of an activity

+ * + * @author roman.smirnov + * + */ +public class ActivityInstanceDto { + + protected String id; + protected String parentActivityInstanceId; + protected String activityId; + protected String activityType; + protected String processInstanceId; + protected String processDefinitionId; + protected ActivityInstanceDto[] childActivityInstances; + protected TransitionInstanceDto[] childTransitionInstances; + protected String[] executionIds; + protected String activityName; + protected String[] incidentIds; + protected ActivityInstanceIncidentDto[] incidents; + + /** The id of the activity instance */ + public String getId() { + return id; + } + + /** The id of the parent activity instance. If the activity is the process definition, + {@link #getId()} and {@link #getParentActivityInstanceId()} return the same value */ + public String getParentActivityInstanceId() { + return parentActivityInstanceId; + } + + /** the id of the activity */ + public String getActivityId() { + return activityId; + } + + /** type of the activity, corresponds to BPMN element name in XML (e.g. 'userTask') */ + public String getActivityType() { + return activityType; + } + + /** the process instance id */ + public String getProcessInstanceId() { + return processInstanceId; + } + + /** the process definition id */ + public String getProcessDefinitionId() { + return processDefinitionId; + } + + /** Returns the child activity instances. + * Returns an empty list if there are no child instances. */ + public ActivityInstanceDto[] getChildActivityInstances() { + return childActivityInstances; + } + + public TransitionInstanceDto[] getChildTransitionInstances() { + return childTransitionInstances; + } + + /** the list of executions that are currently waiting in this activity instance */ + public String[] getExecutionIds() { + return executionIds; + } + + /** the activity name */ + public String getActivityName() { + return activityName; + } + + /** + * deprecated; the JSON field with this name was never documented, but existed + * from 7.0 to 7.2 + */ + public String getName() { + return activityName; + } + + public String[] getIncidentIds() { + return incidentIds; + } + + public ActivityInstanceIncidentDto[] getIncidents() { + return incidents; + } + + public static ActivityInstanceDto fromActivityInstance(ActivityInstance instance) { + ActivityInstanceDto result = new ActivityInstanceDto(); + result.id = instance.getId(); + result.parentActivityInstanceId = instance.getParentActivityInstanceId(); + result.activityId = instance.getActivityId(); + result.activityType = instance.getActivityType(); + result.processInstanceId = instance.getProcessInstanceId(); + result.processDefinitionId = instance.getProcessDefinitionId(); + result.childActivityInstances = fromListOfActivityInstance(instance.getChildActivityInstances()); + result.childTransitionInstances = TransitionInstanceDto.fromListOfTransitionInstance(instance.getChildTransitionInstances()); + result.executionIds = instance.getExecutionIds(); + result.activityName = instance.getActivityName(); + result.incidentIds = instance.getIncidentIds(); + result.incidents = ActivityInstanceIncidentDto.fromIncidents(instance.getIncidents()); + return result; + } + + public static ActivityInstanceDto[] fromListOfActivityInstance(ActivityInstance[] instances) { + ActivityInstanceDto[] result = new ActivityInstanceDto[instances.length]; + for (int i = 0; i < result.length; i++) { + result[i] = fromActivityInstance(instances[i]); + } + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ActivityInstanceIncidentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ActivityInstanceIncidentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d4c99db7ccfc0d46461e0e7e65bb0501641b6020 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ActivityInstanceIncidentDto.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.runtime.Incident; + +public class ActivityInstanceIncidentDto { + + protected String id; + protected String activityId; + + public String getId() { + return id; + } + + public String getActivityId() { + return activityId; + } + + public static ActivityInstanceIncidentDto fromIncident(Incident incident) { + ActivityInstanceIncidentDto dto = new ActivityInstanceIncidentDto(); + + dto.id = incident.getId(); + dto.activityId = incident.getActivityId(); + + return dto; + } + + protected static ActivityInstanceIncidentDto[] fromIncidents(Incident[] incidents) { + ActivityInstanceIncidentDto[] incidentDtos = new ActivityInstanceIncidentDto[incidents.length]; + + for (int i = 0; i { + + protected static final String SORT_BY_EXECUTION_ID_VALUE = "caseExecutionId"; + protected static final String SORT_BY_DEFINITION_KEY_VALUE = "caseDefinitionKey"; + protected static final String SORT_BY_DEFINITION_ID_VALUE = "caseDefinitionId"; + protected static final String SORT_BY_TENANT_ID = "tenantId"; + + protected static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String caseExecutionId; + protected String caseDefinitionKey; + protected String caseDefinitionId; + protected String caseInstanceId; + protected String businessKey; + protected String activityId; + protected List tenantIds; + protected Boolean required; + protected Boolean enabled; + protected Boolean active; + protected Boolean disabled; + + protected List variables; + protected List caseInstanceVariables; + + protected Boolean variableNamesIgnoreCase; + protected Boolean variableValuesIgnoreCase; + + public CaseExecutionQueryDto() { + } + + public CaseExecutionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("caseExecutionId") + public void setCaseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + } + + @CamundaQueryParam("caseDefinitionKey") + public void setCaseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam("businessKey") + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value="required", converter = BooleanConverter.class) + public void setRequired(Boolean required) { + this.required = required; + } + + @CamundaQueryParam(value="enabled", converter = BooleanConverter.class) + public void setEnabled(Boolean enabled) { + this.enabled = enabled; + } + + @CamundaQueryParam(value="active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value="disabled", converter = BooleanConverter.class) + public void setDisabled(Boolean disabled) { + this.disabled = disabled; + } + + @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) + public void setVariables(List variables) { + this.variables = variables; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam(value = "variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + @CamundaQueryParam(value = "caseInstanceVariables", converter = VariableListConverter.class) + public void setCaseInstanceVariables(List caseInstanceVariables) { + this.caseInstanceVariables = caseInstanceVariables; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected CaseExecutionQuery createNewQuery(ProcessEngine engine) { + return engine.getCaseService().createCaseExecutionQuery(); + } + + @Override + protected void applyFilters(CaseExecutionQuery query) { + if (caseExecutionId != null) { + query.caseExecutionId(caseExecutionId); + } + + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + + if (businessKey != null) { + query.caseInstanceBusinessKey(businessKey); + } + + if (caseDefinitionKey != null) { + query.caseDefinitionKey(caseDefinitionKey); + } + + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + + if (activityId != null) { + query.activityId(activityId); + } + + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + + if (required != null && required == true) { + query.required(); + } + + if (active != null && active == true) { + query.active(); + } + + if (enabled != null && enabled == true) { + query.enabled(); + } + + if (disabled != null && disabled == true) { + query.disabled(); + } + + if(Boolean.TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + + if(Boolean.TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + + if (variables != null) { + + for (VariableQueryParameterDto variableQueryParam : variables) { + + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.variableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.variableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.variableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.variableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.variableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + + if (caseInstanceVariables != null) { + + for (VariableQueryParameterDto variableQueryParam : caseInstanceVariables) { + + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.caseInstanceVariableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.caseInstanceVariableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.caseInstanceVariableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + } + + protected void applySortBy(CaseExecutionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_EXECUTION_ID_VALUE)) { + query.orderByCaseExecutionId(); + } else if (sortBy.equals(SORT_BY_DEFINITION_KEY_VALUE)) { + query.orderByCaseDefinitionKey(); + } else if (sortBy.equals(SORT_BY_DEFINITION_ID_VALUE)) { + query.orderByCaseDefinitionId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseExecutionTriggerDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseExecutionTriggerDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e0b5624834c5b4594242422d4b302a34b3c26b3c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseExecutionTriggerDto.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.List; +import java.util.Map; + +/** + * @author Roman Smirnov + * + */ +public class CaseExecutionTriggerDto { + + private Map variables; + private List deletions; + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public List getDeletions() { + return deletions; + } + + public void setDeletions(List deletions) { + this.deletions = deletions; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..88a06bed65afcde383c283d3f651ab0937098aaf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseInstanceDto.java @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.rest.dto.LinkableDto; +import org.camunda.bpm.engine.runtime.CaseInstance; + +/** + * @author Roman Smirnov + * + */ +public class CaseInstanceDto extends LinkableDto { + + protected String id; + protected String caseDefinitionId; + protected String businessKey; + protected String tenantId; + protected boolean active; + protected boolean completed; + protected boolean terminated; + + public String getId() { + return id; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getBusinessKey() { + return businessKey; + } + + public String getTenantId() { + return tenantId; + } + + public boolean isActive() { + return active; + } + + public boolean isCompleted() { + return completed; + } + + public boolean isTerminated() { + return terminated; + } + + public static CaseInstanceDto fromCaseInstance(CaseInstance instance) { + CaseInstanceDto result = new CaseInstanceDto(); + + result.id = instance.getId(); + result.caseDefinitionId = instance.getCaseDefinitionId(); + result.businessKey = instance.getBusinessKey(); + result.tenantId = instance.getTenantId(); + result.active = instance.isActive(); + result.completed = instance.isCompleted(); + result.terminated = instance.isTerminated(); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..13ae5441b448b2dc8c09c15e0cfb8e230efd91e1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CaseInstanceQueryDto.java @@ -0,0 +1,274 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.CaseInstanceQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Roman Smirnov + * + */ +public class CaseInstanceQueryDto extends AbstractQueryDto { + + protected static final String SORT_BY_INSTANCE_ID_VALUE = "caseInstanceId"; + protected static final String SORT_BY_DEFINITION_KEY_VALUE = "caseDefinitionKey"; + protected static final String SORT_BY_DEFINITION_ID_VALUE = "caseDefinitionId"; + protected static final String SORT_BY_TENANT_ID = "tenantId"; + + protected static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String caseInstanceId; + protected String businessKey; + protected String caseDefinitionKey; + protected String caseDefinitionId; + protected String deploymentId; + protected String superProcessInstance; + protected String subProcessInstance; + protected String superCaseInstance; + protected String subCaseInstance; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean active; + protected Boolean completed; + protected Boolean terminated; + + protected List variables; + + protected Boolean variableNamesIgnoreCase; + protected Boolean variableValuesIgnoreCase; + + public CaseInstanceQueryDto() { + } + + public CaseInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam("businessKey") + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + + @CamundaQueryParam("caseDefinitionKey") + public void setCaseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + @CamundaQueryParam("superProcessInstance") + public void setSuperProcessInstance(String superProcessInstance) { + this.superProcessInstance = superProcessInstance; + } + + @CamundaQueryParam("subProcessInstance") + public void setSubProcessInstance(String subProcessInstance) { + this.subProcessInstance = subProcessInstance; + } + + @CamundaQueryParam("superCaseInstance") + public void setSuperCaseInstance(String superCaseInstance) { + this.superCaseInstance = superCaseInstance; + } + + @CamundaQueryParam("subCaseInstance") + public void setSubCaseInstance(String subCaseInstance) { + this.subCaseInstance = subCaseInstance; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "completed", converter = BooleanConverter.class) + public void setCompleted(Boolean completed) { + this.completed = completed; + } + + @CamundaQueryParam(value = "terminated", converter = BooleanConverter.class) + public void setTerminated(Boolean terminated) { + this.terminated = terminated; + } + + @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) + public void setVariables(List variables) { + this.variables = variables; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam(value = "variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected CaseInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getCaseService().createCaseInstanceQuery(); + } + + @Override + protected void applyFilters(CaseInstanceQuery query) { + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (businessKey != null) { + query.caseInstanceBusinessKey(businessKey); + } + if (caseDefinitionKey != null) { + query.caseDefinitionKey(caseDefinitionKey); + } + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (deploymentId != null) { + query.deploymentId(deploymentId ); + } + if (superProcessInstance != null) { + query.superProcessInstanceId(superProcessInstance); + } + if (subProcessInstance != null) { + query.subProcessInstanceId(subProcessInstance); + } + if (superCaseInstance != null) { + query.superCaseInstanceId(superCaseInstance); + } + if (subCaseInstance != null) { + query.subCaseInstanceId(subCaseInstance); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (active != null && active == true) { + query.active(); + } + if (completed != null && completed == true) { + query.completed(); + } + if (terminated != null && terminated == true) { + query.terminated(); + } + if(Boolean.TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + if(Boolean.TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + if (variables != null) { + + for (VariableQueryParameterDto variableQueryParam : variables) { + + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.variableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.variableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.variableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.variableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.variableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + } + + @Override + protected void applySortBy(CaseInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_INSTANCE_ID_VALUE)) { + query.orderByCaseInstanceId(); + } else if (sortBy.equals(SORT_BY_DEFINITION_KEY_VALUE)) { + query.orderByCaseDefinitionKey(); + } else if (sortBy.equals(SORT_BY_DEFINITION_ID_VALUE)) { + query.orderByCaseDefinitionId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CreateCaseInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CreateCaseInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..34f4039cd034fa86a4dc0a0a9a69a7a3f8d6cff2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/CreateCaseInstanceDto.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +import java.util.Map; + +/** + * + * @author Roman Smirnov + * + */ +public class CreateCaseInstanceDto { + + private Map variables; + private String businessKey; + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public String getBusinessKey() { + return businessKey; + } + + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/EventSubscriptionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/EventSubscriptionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bcf9492b5d4f211196631e6cd5ce012af6afbcb9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/EventSubscriptionDto.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.Date; + +import org.camunda.bpm.engine.runtime.EventSubscription; + +public class EventSubscriptionDto { + + private String id; + private String eventType; + private String eventName; + private String executionId; + private String processInstanceId; + private String activityId; + private Date createdDate; + private String tenantId; + + public String getId() { + return id; + } + public String getEventType() { + return eventType; + } + public String getEventName() { + return eventName; + } + public String getExecutionId() { + return executionId; + } + public String getProcessInstanceId() { + return processInstanceId; + } + public String getActivityId() { + return activityId; + } + public Date getCreatedDate() { + return createdDate; + } + + public String getTenantId() { + return tenantId; + } + + public static EventSubscriptionDto fromEventSubscription(EventSubscription eventSubscription) { + EventSubscriptionDto dto = new EventSubscriptionDto(); + dto.id = eventSubscription.getId(); + dto.eventType = eventSubscription.getEventType(); + dto.eventName = eventSubscription.getEventName(); + dto.executionId = eventSubscription.getExecutionId(); + dto.processInstanceId = eventSubscription.getProcessInstanceId(); + dto.activityId = eventSubscription.getActivityId(); + dto.createdDate = eventSubscription.getCreated(); + dto.tenantId = eventSubscription.getTenantId(); + + return dto; + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/EventSubscriptionQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/EventSubscriptionQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..30ed0343d2c7558b617001877d947cf0e62a81ea --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/EventSubscriptionQueryDto.java @@ -0,0 +1,196 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.runtime.EventSubscriptionQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class EventSubscriptionQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_TENANT_ID = "tenantId"; + private static final String SORT_BY_CREATED = "created"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_CREATED); + } + + private String eventSubscriptionId; + private String eventName; + private String eventType; + private String executionId; + private String processInstanceId; + private String activityId; + private List tenantIdIn; + private Boolean withoutTenantId; + private Boolean includeEventSubscriptionsWithoutTenantId; + + public EventSubscriptionQueryDto() { + + } + + public EventSubscriptionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + public String getEventSubscriptionId() { + return eventSubscriptionId; + } + + @CamundaQueryParam("eventSubscriptionId") + public void setEventSubscriptionId(String eventSubscriptionId) { + this.eventSubscriptionId = eventSubscriptionId; + } + + public String getEventName() { + return eventName; + } + + @CamundaQueryParam("eventName") + public void setEventName(String eventName) { + this.eventName = eventName; + } + + public String getEventType() { + return eventType; + } + + @CamundaQueryParam("eventType") + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public String getExecutionId() { + return executionId; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public String getActivityId() { + return activityId; + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + public List getTenantIdIn() { + return tenantIdIn; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIdIn) { + this.tenantIdIn = tenantIdIn; + } + + public Boolean getWithoutTenantId() { + return withoutTenantId; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + public Boolean getIncludeEventSubscriptionsWithoutTenantId() { + return includeEventSubscriptionsWithoutTenantId; + } + + @CamundaQueryParam(value = "includeEventSubscriptionsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeEventSubscriptionsWithoutTenantId(Boolean includeEventSubscriptionsWithoutTenantId) { + this.includeEventSubscriptionsWithoutTenantId = includeEventSubscriptionsWithoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected EventSubscriptionQuery createNewQuery(ProcessEngine engine) { + return engine.getRuntimeService().createEventSubscriptionQuery(); + } + + @Override + protected void applyFilters(EventSubscriptionQuery query) { + if (eventSubscriptionId != null) { + query.eventSubscriptionId(eventSubscriptionId); + } + if (eventName != null) { + query.eventName(eventName); + } + if (eventType != null) { + query.eventType(eventType); + } + if (executionId != null) { + query.executionId(executionId); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (activityId != null) { + query.activityId(activityId); + } + if (tenantIdIn != null && !tenantIdIn.isEmpty()) { + query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeEventSubscriptionsWithoutTenantId)) { + query.includeEventSubscriptionsWithoutTenantId(); + } + } + + @Override + protected void applySortBy(EventSubscriptionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_CREATED)) { + query.orderByCreated(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..3619b2e49c4897c6f9ddf12862c872b465ca10ca --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.runtime.Execution; + +public class ExecutionDto { + + private String id; + private String processInstanceId; + private boolean ended; + private String tenantId; + + public static ExecutionDto fromExecution(Execution execution) { + ExecutionDto dto = new ExecutionDto(); + dto.id = execution.getId(); + dto.processInstanceId = execution.getProcessInstanceId(); + dto.ended = execution.isEnded(); + dto.tenantId = execution.getTenantId(); + + return dto; + } + + public String getId() { + return id; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public boolean isEnded() { + return ended; + } + + public String getTenantId() { + return tenantId; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..05495ed90a010d40442a7241b293d52cb125e1ef --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionQueryDto.java @@ -0,0 +1,288 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.ExecutionQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ExecutionQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_INSTANCE_ID_VALUE = "instanceId"; + private static final String SORT_BY_DEFINITION_KEY_VALUE = "definitionKey"; + private static final String SORT_BY_DEFINITION_ID_VALUE = "definitionId"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + private String processDefinitionKey; + private String businessKey; + private String processDefinitionId; + private String processInstanceId; + private String activityId; + private String signalEventSubscriptionName; + private String messageEventSubscriptionName; + private Boolean active; + private Boolean suspended; + private String incidentId; + private String incidentType; + private String incidentMessage; + private String incidentMessageLike; + private List tenantIdIn; + + private List variables; + private List processVariables; + + Boolean variableValuesIgnoreCase; + Boolean variableNamesIgnoreCase; + + public ExecutionQueryDto() { + + } + + public ExecutionQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam("businessKey") + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + @CamundaQueryParam("signalEventSubscriptionName") + public void setSignalEventSubscriptionName(String signalEventSubscriptionName) { + this.signalEventSubscriptionName = signalEventSubscriptionName; + } + + @CamundaQueryParam("messageEventSubscriptionName") + public void setMessageEventSubscriptionName(String messageEventSubscriptionName) { + this.messageEventSubscriptionName = messageEventSubscriptionName; + } + + @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) + public void setVariables(List variables) { + this.variables = variables; + } + + @CamundaQueryParam(value = "processVariables", converter = VariableListConverter.class) + public void setProcessVariables(List processVariables) { + this.processVariables = processVariables; + } + + @CamundaQueryParam(value = "variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value = "incidentId") + public void setIncidentId(String incidentId) { + this.incidentId = incidentId; + } + + @CamundaQueryParam(value = "incidentType") + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + @CamundaQueryParam(value = "incidentMessage") + public void setIncidentMessage(String incidentMessage) { + this.incidentMessage = incidentMessage; + } + + @CamundaQueryParam(value = "incidentMessageLike") + public void setIncidentMessageLike(String incidentMessageLike) { + this.incidentMessageLike = incidentMessageLike; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIdIn) { + this.tenantIdIn = tenantIdIn; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected ExecutionQuery createNewQuery(ProcessEngine engine) { + return engine.getRuntimeService().createExecutionQuery(); + } + + @Override + protected void applyFilters(ExecutionQuery query) { + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (businessKey != null) { + query.processInstanceBusinessKey(businessKey); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (activityId != null) { + query.activityId(activityId); + } + if (signalEventSubscriptionName != null) { + query.signalEventSubscriptionName(signalEventSubscriptionName); + } + if (messageEventSubscriptionName != null) { + query.messageEventSubscriptionName(messageEventSubscriptionName); + } + if (active != null && active == true) { + query.active(); + } + if (suspended != null && suspended == true) { + query.suspended(); + } + if (incidentId != null) { + query.incidentId(incidentId); + } + if (incidentType != null) { + query.incidentType(incidentType); + } + if (incidentMessage != null) { + query.incidentMessage(incidentMessage); + } + if (incidentMessageLike != null) { + query.incidentMessageLike(incidentMessageLike); + } + if (tenantIdIn != null && !tenantIdIn.isEmpty()) { + query.tenantIdIn(tenantIdIn.toArray(new String[tenantIdIn.size()])); + } + if(Boolean.TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + if(Boolean.TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + if (variables != null) { + for (VariableQueryParameterDto variableQueryParam : variables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.variableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.variableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.variableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.variableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.variableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + + if (processVariables != null) { + for (VariableQueryParameterDto variableQueryParam : processVariables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.processVariableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.processVariableValueNotEquals(variableName, variableValue); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid process variable comparator specified: " + op); + } + } + } + } + + @Override + protected void applySortBy(ExecutionQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_INSTANCE_ID_VALUE)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_DEFINITION_KEY_VALUE)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_DEFINITION_ID_VALUE)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionTriggerDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionTriggerDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ecb0e3e4e3378bb0ccea1becec7905ae1d915d7b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ExecutionTriggerDto.java @@ -0,0 +1,34 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +import java.util.Map; + +public class ExecutionTriggerDto { + + private Map variables; + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/FilterDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/FilterDto.java new file mode 100644 index 0000000000000000000000000000000000000000..2b3d7d3693fdc4eea6b2cd9f9070c940bf2042d2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/FilterDto.java @@ -0,0 +1,132 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.EntityTypes; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +public class FilterDto { + + protected String id; + protected String resourceType; + protected String name; + protected String owner; + protected AbstractQueryDto query; + protected Map properties; + + protected Long itemCount; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getResourceType() { + return resourceType; + } + + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public AbstractQueryDto getQuery() { + return query; + } + + @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, + property = "resourceType", defaultImpl=TaskQueryDto.class) + @JsonSubTypes(value = { + @JsonSubTypes.Type(value = TaskQueryDto.class, name = EntityTypes.TASK)}) + public void setQuery(AbstractQueryDto query) { + this.query = query; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } + + @JsonInclude(Include.NON_NULL) + public Long getItemCount() { + return itemCount; + } + + public void setItemCount(Long itemCount) { + this.itemCount = itemCount; + } + + public static FilterDto fromFilter(Filter filter) { + FilterDto dto = new FilterDto(); + dto.id = filter.getId(); + dto.resourceType = filter.getResourceType(); + dto.name = filter.getName(); + dto.owner = filter.getOwner(); + + if (EntityTypes.TASK.equals(filter.getResourceType())) { + dto.query = TaskQueryDto.fromQuery(filter.getQuery()); + } + + dto.properties = filter.getProperties(); + return dto; + } + + public void updateFilter(Filter filter, ProcessEngine engine) { + if (getResourceType() != null && !getResourceType().equals(filter.getResourceType())) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Unable to update filter from resource type '" + filter.getResourceType() + "' to '" + getResourceType() + "'"); + } + filter.setName(getName()); + filter.setOwner(getOwner()); + filter.setQuery(query.toQuery(engine)); + filter.setProperties(getProperties()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/FilterQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/FilterQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..40fbec86bc6f7a21b59268c2422fa15c82b9467d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/FilterQueryDto.java @@ -0,0 +1,131 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.filter.FilterQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Sebastian Menski + */ +public class FilterQueryDto extends AbstractQueryDto { + + public static final String SORT_BY_ID_VALUE = "filterId"; + public static final String SORT_BY_RESOURCE_TYPE_VALUE = "resourceType"; + public static final String SORT_BY_NAME_VALUE = "name"; + public static final String SORT_BY_OWNER_VALUE = "owner"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_RESOURCE_TYPE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_OWNER_VALUE); + } + + protected String filterId; + protected String resourceType; + protected String name; + protected String nameLike; + protected String owner; + + public FilterQueryDto() { + + } + + public FilterQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("filterId") + public void setFilterId(String filterId) { + this.filterId = filterId; + } + + @CamundaQueryParam("resourceType") + public void setResourceType(String resourceType) { + this.resourceType = resourceType; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("owner") + public void setOwner(String owner) { + this.owner = owner; + } + + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + protected FilterQuery createNewQuery(ProcessEngine engine) { + return engine.getFilterService().createFilterQuery(); + } + + protected void applyFilters(FilterQuery query) { + if (filterId != null) { + query.filterId(filterId); + } + if (resourceType != null) { + query.filterResourceType(resourceType); + } + if (name != null) { + query.filterName(name); + } + if (nameLike != null) { + query.filterNameLike(nameLike); + } + if (owner != null) { + query.filterOwner(owner); + } + } + + protected void applySortBy(FilterQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_ID_VALUE)) { + query.orderByFilterId(); + } + else if (sortBy.equals(SORT_BY_RESOURCE_TYPE_VALUE)) { + query.orderByFilterResourceType(); + } + else if (sortBy.equals(SORT_BY_NAME_VALUE)) { + query.orderByFilterName(); + } + else if (sortBy.equals(SORT_BY_OWNER_VALUE)) { + query.orderByFilterOwner(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/IncidentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/IncidentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..706f16a2729b586314295b6c1b60feeae3ecafbb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/IncidentDto.java @@ -0,0 +1,128 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.Date; + +import org.camunda.bpm.engine.runtime.Incident; + +/** + * + * @author Roman Smirnov + * + */ +public class IncidentDto { + + protected String id; + protected String processDefinitionId; + protected String processInstanceId; + protected String executionId; + protected Date incidentTimestamp; + protected String incidentType; + protected String activityId; + protected String failedActivityId; + protected String causeIncidentId; + protected String rootCauseIncidentId; + protected String configuration; + protected String incidentMessage; + protected String tenantId; + protected String jobDefinitionId; + protected String annotation; + + public String getId() { + return id; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public Date getIncidentTimestamp() { + return incidentTimestamp; + } + + public String getIncidentType() { + return incidentType; + } + + public String getActivityId() { + return activityId; + } + + public String getFailedActivityId() { + return failedActivityId; + } + + public String getCauseIncidentId() { + return causeIncidentId; + } + + public String getRootCauseIncidentId() { + return rootCauseIncidentId; + } + + public String getConfiguration() { + return configuration; + } + + public String getIncidentMessage() { + return incidentMessage; + } + + public String getTenantId() { + return tenantId; + } + + public String getJobDefinitionId() { + return jobDefinitionId; + } + + public String getAnnotation() { + return annotation; + } + + public static IncidentDto fromIncident(Incident incident) { + IncidentDto dto = new IncidentDto(); + + dto.id = incident.getId(); + dto.processDefinitionId = incident.getProcessDefinitionId(); + dto.processInstanceId = incident.getProcessInstanceId(); + dto.executionId = incident.getExecutionId(); + dto.incidentTimestamp = incident.getIncidentTimestamp(); + dto.incidentType = incident.getIncidentType(); + dto.activityId = incident.getActivityId(); + dto.failedActivityId = incident.getFailedActivityId(); + dto.causeIncidentId = incident.getCauseIncidentId(); + dto.rootCauseIncidentId = incident.getRootCauseIncidentId(); + dto.configuration = incident.getConfiguration(); + dto.incidentMessage = incident.getIncidentMessage(); + dto.tenantId = incident.getTenantId(); + dto.jobDefinitionId = incident.getJobDefinitionId(); + dto.annotation = incident.getAnnotation(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/IncidentQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/IncidentQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5feaf34a12f7203f9b0638ee49e399f206f06f10 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/IncidentQueryDto.java @@ -0,0 +1,276 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.runtime.IncidentQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Roman Smirnov + * + */ +public class IncidentQueryDto extends AbstractQueryDto{ + + private static final String SORT_BY_INCIDENT_ID = "incidentId"; + private static final String SORT_BY_INCIDENT_MESSAGE = "incidentMessage"; + private static final String SORT_BY_INCIDENT_TIMESTAMP = "incidentTimestamp"; + private static final String SORT_BY_INCIDENT_TYPE = "incidentType"; + private static final String SORT_BY_EXECUTION_ID = "executionId"; + private static final String SORT_BY_ACTIVITY_ID = "activityId"; + private static final String SORT_BY_PROCESS_INSTANCE_ID = "processInstanceId"; + private static final String SORT_BY_PROCESS_DEFINITION_ID = "processDefinitionId"; + private static final String SORT_BY_CAUSE_INCIDENT_ID = "causeIncidentId"; + private static final String SORT_BY_ROOT_CAUSE_INCIDENT_ID = "rootCauseIncidentId"; + private static final String SORT_BY_CONFIGURATION = "configuration"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_MESSAGE); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_TIMESTAMP); + VALID_SORT_BY_VALUES.add(SORT_BY_INCIDENT_TYPE); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_CAUSE_INCIDENT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_ROOT_CAUSE_INCIDENT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_CONFIGURATION); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String incidentId; + protected String incidentType; + protected String incidentMessage; + protected String incidentMessageLike; + protected String processDefinitionId; + protected String[] processDefinitionKeyIn; + protected String processInstanceId; + protected String executionId; + protected Date incidentTimestampBefore; + protected Date incidentTimestampAfter; + protected String activityId; + protected String failedActivityId; + protected String causeIncidentId; + protected String rootCauseIncidentId; + protected String configuration; + protected List tenantIds; + protected List jobDefinitionIds; + + public IncidentQueryDto() {} + + public IncidentQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("incidentId") + public void setIncidentId(String incidentId) { + this.incidentId = incidentId; + } + + @CamundaQueryParam("incidentType") + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + @CamundaQueryParam("incidentMessage") + public void setIncidentMessage(String incidentMessage) { + this.incidentMessage = incidentMessage; + } + + @CamundaQueryParam("incidentMessageLike") + public void setIncidentMessageLike(String incidentMessageLike) { + this.incidentMessageLike = incidentMessageLike; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringArrayConverter.class) + public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) { + this.processDefinitionKeyIn = processDefinitionKeyIn; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam(value="incidentTimestampAfter", converter= DateConverter.class) + public void setIncidentTimestampAfter(Date incidentTimestampAfter) { + this.incidentTimestampAfter = incidentTimestampAfter; + } + + @CamundaQueryParam(value="incidentTimestampBefore", converter= DateConverter.class) + public void setIncidentTimestampBefore(Date incidentTimestampBefore) { + this.incidentTimestampBefore = incidentTimestampBefore; + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + @CamundaQueryParam("failedActivityId") + public void setFailedActivityId(String activityId) { + this.failedActivityId = activityId; + } + + @CamundaQueryParam("causeIncidentId") + public void setCauseIncidentId(String causeIncidentId) { + this.causeIncidentId = causeIncidentId; + } + + @CamundaQueryParam("rootCauseIncidentId") + public void setRootCauseIncidentId(String rootCauseIncidentId) { + this.rootCauseIncidentId = rootCauseIncidentId; + } + + @CamundaQueryParam("configuration") + public void setConfiguration(String configuration) { + this.configuration = configuration; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "jobDefinitionIdIn", converter = StringListConverter.class) + public void setJobDefinitionIdIn(List jobDefinitionIds) { + this.jobDefinitionIds = jobDefinitionIds; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + + @Override + protected IncidentQuery createNewQuery(ProcessEngine engine) { + return engine.getRuntimeService().createIncidentQuery(); + } + + @Override + protected void applyFilters(IncidentQuery query) { + if (incidentId != null) { + query.incidentId(incidentId); + } + if (incidentType != null) { + query.incidentType(incidentType); + } + if (incidentMessage != null) { + query.incidentMessage(incidentMessage); + } + if (incidentMessageLike != null) { + query.incidentMessageLike(incidentMessageLike); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) { + query.processDefinitionKeyIn(processDefinitionKeyIn); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (executionId != null) { + query.executionId(executionId); + } + if (incidentTimestampBefore != null) { + query.incidentTimestampBefore(incidentTimestampBefore); + } + if (incidentTimestampAfter != null) { + query.incidentTimestampAfter(incidentTimestampAfter); + } + if (activityId != null) { + query.activityId(activityId); + } + if (failedActivityId != null) { + query.failedActivityId(failedActivityId); + } + if (causeIncidentId != null) { + query.causeIncidentId(causeIncidentId); + } + if (rootCauseIncidentId != null) { + query.rootCauseIncidentId(rootCauseIncidentId); + } + if (configuration != null) { + query.configuration(configuration); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (jobDefinitionIds != null && !jobDefinitionIds.isEmpty()) { + query.jobDefinitionIdIn(jobDefinitionIds.toArray(new String[jobDefinitionIds.size()])); + } + } + + @Override + protected void applySortBy(IncidentQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_INCIDENT_ID)) { + query.orderByIncidentId(); + } else if (sortBy.equals(SORT_BY_INCIDENT_MESSAGE)) { + query.orderByIncidentMessage(); + } else if (sortBy.equals(SORT_BY_INCIDENT_TIMESTAMP)) { + query.orderByIncidentTimestamp(); + } else if (sortBy.equals(SORT_BY_INCIDENT_TYPE)) { + query.orderByIncidentType(); + } else if (sortBy.equals(SORT_BY_EXECUTION_ID)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_ID)) { + query.orderByActivityId(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_CAUSE_INCIDENT_ID)) { + query.orderByCauseIncidentId(); + } else if (sortBy.equals(SORT_BY_ROOT_CAUSE_INCIDENT_ID)) { + query.orderByRootCauseIncidentId(); + } else if (sortBy.equals(SORT_BY_CONFIGURATION)) { + query.orderByConfiguration(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDefinitionPriorityDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDefinitionPriorityDto.java new file mode 100644 index 0000000000000000000000000000000000000000..15286a8012fe21e130534621642a3268c9fb399a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDefinitionPriorityDto.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +public class JobDefinitionPriorityDto { + + protected Long priority; + protected boolean includeJobs = false; + + public Long getPriority() { + return priority; + } + + public void setPriority(Long priority) { + this.priority = priority; + } + + public boolean isIncludeJobs() { + return includeJobs; + } + + public void setIncludeJobs(boolean includeJobs) { + this.includeJobs = includeJobs; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f31eb59bf9a0ee31fd5ba3ff0fdb0af486b21723 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDto.java @@ -0,0 +1,122 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.Date; + +import org.camunda.bpm.engine.runtime.Job; + +public class JobDto { + + protected String id; + protected String jobDefinitionId; + protected String processInstanceId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String executionId; + protected String exceptionMessage; + protected String failedActivityId; + protected int retries; + protected Date dueDate; + protected boolean suspended; + protected long priority; + protected String tenantId; + protected Date createTime; + protected String batchId; + + public static JobDto fromJob(Job job) { + JobDto dto = new JobDto(); + dto.id = job.getId(); + dto.jobDefinitionId = job.getJobDefinitionId(); + dto.processInstanceId = job.getProcessInstanceId(); + dto.processDefinitionId = job.getProcessDefinitionId(); + dto.processDefinitionKey = job.getProcessDefinitionKey(); + dto.executionId = job.getExecutionId(); + dto.exceptionMessage = job.getExceptionMessage(); + dto.failedActivityId = job.getFailedActivityId(); + dto.retries = job.getRetries(); + dto.dueDate = job.getDuedate(); + dto.suspended = job.isSuspended(); + dto.priority = job.getPriority(); + dto.tenantId = job.getTenantId(); + dto.createTime = job.getCreateTime(); + dto.batchId = job.getBatchId(); + + return dto; + } + + public String getId() { + return id; + } + + public String getJobDefinitionId() { + return jobDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getExceptionMessage() { + return exceptionMessage; + } + + public String getFailedActivityId() { + return failedActivityId; + } + + public int getRetries() { + return retries; + } + + public Date getDueDate() { + return dueDate; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public boolean isSuspended() { + return suspended; + } + + public long getPriority() { + return priority; + } + + public String getTenantId() { + return tenantId; + } + + public Date getCreateTime() { + return createTime; + } + + public String getBatchId() { + return batchId; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDuedateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDuedateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..3cbf4c7a9ff260f7a2eefb8e115e78082ba7e754 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobDuedateDto.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.Date; + +public class JobDuedateDto { + + private Date duedate; + private boolean cascade; + + public Date getDuedate() { + return duedate; + } + + public void setDuedate(Date duedate) { + this.duedate = duedate; + } + + public boolean isCascade() { + return cascade; + } + + public void setCascade(boolean cascade) { + this.cascade = cascade; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..b4a6616dac8d3b1accc93baa1f49d8dd57a2e323 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobQueryDto.java @@ -0,0 +1,455 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.util.CollectionUtil; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.ConditionQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.ConditionListConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.LongConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringSetConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.runtime.JobQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JobQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_JOB_ID_VALUE = "jobId"; + private static final String SORT_BY_EXECUTION_ID_VALUE = "executionId"; + private static final String SORT_BY_PROCESS_INSTANCE_ID_VALUE = "processInstanceId"; + private static final String SORT_BY_PROCESS_DEFINITION_ID_VALUE = "processDefinitionId"; + private static final String SORT_BY_PROCESS_DEFINITION_KEY_VALUE = "processDefinitionKey"; + private static final String SORT_BY_JOB_RETRIES_VALUE = "jobRetries"; + private static final String SORT_BY_JOB_DUEDATE_VALUE = "jobDueDate"; + private static final String SORT_BY_JOB_PRIORITY_VALUE = "jobPriority"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_DEFINITION_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_RETRIES_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_DUEDATE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_JOB_PRIORITY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String activityId; + protected String jobId; + protected Set jobIds; + protected String executionId; + protected String processInstanceId; + protected Set processInstanceIds; + protected String processDefinitionId; + protected String processDefinitionKey; + protected Boolean withRetriesLeft; + protected Boolean executable; + protected Boolean timers; + protected Boolean messages; + protected Boolean withException; + protected String exceptionMessage; + protected String failedActivityId; + protected Boolean noRetriesLeft; + protected Boolean active; + protected Boolean suspended; + protected Long priorityHigherThanOrEquals; + protected Long priorityLowerThanOrEquals; + protected String jobDefinitionId; + protected List tenantIds; + protected Boolean withoutTenantId; + protected Boolean includeJobsWithoutTenantId; + protected Boolean acquired; + + protected List dueDates; + protected List createTimes; + + public JobQueryDto() {} + + public JobQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("activityId") + public void setActivityId(String activityId) { + this.activityId = activityId; + } + + @CamundaQueryParam("failedActivityId") + public void setFailedActivityId(String activityId) { + this.failedActivityId = activityId; + } + + @CamundaQueryParam("jobId") + public void setJobId(String jobId) { + this.jobId = jobId; + } + + @CamundaQueryParam(value = "jobIds", converter = StringSetConverter.class) + public void setJobIds(Set jobIds) { + this.jobIds = jobIds; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam(value = "processInstanceIds", converter = StringSetConverter.class) + public void setProcessInstanceIds(Set processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam(value="withRetriesLeft", converter = BooleanConverter.class) + public void setWithRetriesLeft(Boolean withRetriesLeft) { + this.withRetriesLeft = withRetriesLeft; + } + + @CamundaQueryParam(value="executable", converter = BooleanConverter.class) + public void setExecutable(Boolean executable) { + this.executable = executable; + } + + @CamundaQueryParam(value="timers", converter = BooleanConverter.class) + public void setTimers(Boolean timers) { + this.timers = timers; + } + + @CamundaQueryParam(value="withException", converter = BooleanConverter.class) + public void setWithException(Boolean withException) { + this.withException = withException; + } + + @CamundaQueryParam(value="messages", converter = BooleanConverter.class) + public void setMessages(Boolean messages) { + this.messages = messages; + } + + @CamundaQueryParam("exceptionMessage") + public void setExceptionMessage(String exceptionMessage) { + this.exceptionMessage = exceptionMessage; + } + + @CamundaQueryParam(value = "dueDates", converter = ConditionListConverter.class) + public void setDueDates(List dueDates) { + this.dueDates = dueDates; + } + + @CamundaQueryParam(value = "createTimes", converter = ConditionListConverter.class) + public void setCreateTimes(List createTimes) { + this.createTimes = createTimes; + } + + @CamundaQueryParam(value="noRetriesLeft", converter = BooleanConverter.class) + public void setNoRetriesLeft(Boolean noRetriesLeft) { + this.noRetriesLeft = noRetriesLeft; + } + + @CamundaQueryParam(value="active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value="suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value="priorityHigherThanOrEquals", converter = LongConverter.class) + public void setPriorityHigherThanOrEquals(Long priorityHigherThanOrEquals) { + this.priorityHigherThanOrEquals = priorityHigherThanOrEquals; + } + + @CamundaQueryParam(value="priorityLowerThanOrEquals", converter = LongConverter.class) + public void setPriorityLowerThanOrEquals(Long priorityLowerThanOrEquals) { + this.priorityLowerThanOrEquals = priorityLowerThanOrEquals; + } + + @CamundaQueryParam("jobDefinitionId") + public void setJobDefinitionId(String jobDefinitionId) { + this.jobDefinitionId = jobDefinitionId; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam(value = "includeJobsWithoutTenantId", converter = BooleanConverter.class) + public void setIncludeJobsWithoutTenantId(Boolean includeJobsWithoutTenantId) { + this.includeJobsWithoutTenantId = includeJobsWithoutTenantId; + } + + @CamundaQueryParam(value="acquired", converter = BooleanConverter.class) + public void setAcquired(Boolean acquired) { + this.acquired = acquired; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected JobQuery createNewQuery(ProcessEngine engine) { + return engine.getManagementService().createJobQuery(); + } + + private abstract class ApplyDates { + void run(List dates) { + DateConverter dateConverter = new DateConverter(); + dateConverter.setObjectMapper(objectMapper); + + for (ConditionQueryParameterDto conditionQueryParam : dates) { + String op = conditionQueryParam.getOperator(); + Date date; + + try { + date = dateConverter.convertQueryParameterToType((String) conditionQueryParam.getValue()); + } catch (RestException e) { + throw new InvalidRequestException(e.getStatus(), e, "Invalid " + fieldName() + " format: " + e.getMessage()); + } + + if (op.equals(ConditionQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + setGreaterThan(date); + } else if (op.equals(ConditionQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + setLowerThan(date); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid " + fieldName() + " comparator specified: " + op); + } + } + } + + /** + * @return a descriptive name of the target field, used in error-messages + */ + abstract String fieldName(); + + abstract void setGreaterThan(Date date); + + abstract void setLowerThan(Date date); + } + + @Override + protected void applyFilters(final JobQuery query) { + if (activityId != null){ + query.activityId(activityId); + } + + if (jobId != null) { + query.jobId(jobId); + } + + if (!CollectionUtil.isEmpty(jobIds)) { + query.jobIds(jobIds); + } + + if (executionId != null) { + query.executionId(executionId); + } + + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + + if (!CollectionUtil.isEmpty(processInstanceIds)) { + query.processInstanceIds(processInstanceIds); + } + + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + + if (TRUE.equals(withRetriesLeft)) { + query.withRetriesLeft(); + } + + if (TRUE.equals(executable)) { + query.executable(); + } + + if (TRUE.equals(timers)) { + if (messages != null && messages) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Parameter timers cannot be used together with parameter messages."); + } + query.timers(); + } + + if (TRUE.equals(messages)) { + if (timers != null && timers) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Parameter messages cannot be used together with parameter timers."); + } + query.messages(); + } + + if (TRUE.equals(withException)) { + query.withException(); + } + + if (exceptionMessage != null) { + query.exceptionMessage(exceptionMessage); + } + + if (failedActivityId != null) { + query.failedActivityId(failedActivityId); + } + + if (TRUE.equals(noRetriesLeft)) { + query.noRetriesLeft(); + } + + if (TRUE.equals(active)) { + query.active(); + } + + if (TRUE.equals(suspended)) { + query.suspended(); + } + + if (priorityHigherThanOrEquals != null) { + query.priorityHigherThanOrEquals(priorityHigherThanOrEquals); + } + + if (priorityLowerThanOrEquals != null) { + query.priorityLowerThanOrEquals(priorityLowerThanOrEquals); + } + + if (jobDefinitionId != null) { + query.jobDefinitionId(jobDefinitionId); + } + + if (dueDates != null) { + new ApplyDates() { + @Override + void setGreaterThan(Date date) { + query.duedateHigherThan(date); + } + + @Override + void setLowerThan(Date date) { + query.duedateLowerThan(date); + } + + @Override + String fieldName() { + return "due date"; + } + }.run(dueDates); + } + + if (createTimes != null) { + new ApplyDates() { + @Override + void setGreaterThan(Date date) { + query.createdAfter(date); + } + + @Override + void setLowerThan(Date date) { + query.createdBefore(date); + } + + @Override + String fieldName() { + return "create time"; + } + }.run(createTimes); + } + + if (!CollectionUtil.isEmpty(tenantIds)) { + query.tenantIdIn(tenantIds.toArray(new String[0])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (TRUE.equals(includeJobsWithoutTenantId)) { + query.includeJobsWithoutTenantId(); + } + if (TRUE.equals(acquired)) { + query.acquired(); + } + } + + @Override + protected void applySortBy(JobQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_JOB_ID_VALUE)) { + query.orderByJobId(); + } else if (sortBy.equals(SORT_BY_EXECUTION_ID_VALUE)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID_VALUE)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID_VALUE)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY_VALUE)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_JOB_RETRIES_VALUE)) { + query.orderByJobRetries(); + } else if (sortBy.equals(SORT_BY_JOB_DUEDATE_VALUE)) { + query.orderByJobDuedate(); + } else if (sortBy.equals(SORT_BY_JOB_PRIORITY_VALUE)) { + query.orderByJobPriority(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobSuspensionStateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobSuspensionStateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e195c6bdf3b55317cbe5da61e84b6ef6a9b954b8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/JobSuspensionStateDto.java @@ -0,0 +1,129 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.management.UpdateJobSuspensionStateBuilder; +import org.camunda.bpm.engine.management.UpdateJobSuspensionStateSelectBuilder; +import org.camunda.bpm.engine.management.UpdateJobSuspensionStateTenantBuilder; +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; + +/** + * @author roman.smirnov + */ +public class JobSuspensionStateDto extends SuspensionStateDto { + + private String jobId; + private String jobDefinitionId; + private String processInstanceId; + private String processDefinitionId; + private String processDefinitionKey; + + private String processDefinitionTenantId; + private boolean processDefinitionWithoutTenantId; + + public String getJobId() { + return jobId; + } + + public void setJobId(String jobId) { + this.jobId = jobId; + } + + public void setJobDefinitionId(String jobDefinitionId) { + this.jobDefinitionId = jobDefinitionId; + } + + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + public void setProcessDefinitionTenantId(String processDefinitionTenantId) { + this.processDefinitionTenantId = processDefinitionTenantId; + } + + public void setProcessDefinitionWithoutTenantId(boolean processDefinitionWithoutTenantId) { + this.processDefinitionWithoutTenantId = processDefinitionWithoutTenantId; + } + + @Override + public void updateSuspensionState(ProcessEngine engine) { + int params = (jobId != null ? 1 : 0) + + (jobDefinitionId != null ? 1 : 0) + + (processInstanceId != null ? 1 : 0) + + (processDefinitionId != null ? 1 : 0) + + (processDefinitionKey != null ? 1 : 0); + + if (params > 1) { + String message = "Only one of jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + + } else if(params == 0) { + String message = "Either jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + UpdateJobSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateBuilder(engine); + + if(getSuspended()) { + updateSuspensionStateBuilder.suspend(); + } else { + updateSuspensionStateBuilder.activate(); + } + } + + protected UpdateJobSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) { + UpdateJobSuspensionStateSelectBuilder selectBuilder = engine.getManagementService().updateJobSuspensionState(); + + if (jobId != null) { + return selectBuilder.byJobId(jobId); + + } else if (jobDefinitionId != null) { + return selectBuilder.byJobDefinitionId(jobDefinitionId); + + } else if (processInstanceId != null) { + return selectBuilder.byProcessInstanceId(processInstanceId); + + } else if (processDefinitionId != null) { + return selectBuilder.byProcessDefinitionId(processDefinitionId); + + } else { + UpdateJobSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey); + + if (processDefinitionTenantId != null) { + tenantBuilder.processDefinitionTenantId(processDefinitionTenantId); + + } else if (processDefinitionWithoutTenantId) { + tenantBuilder.processDefinitionWithoutTenantId(); + } + + return tenantBuilder; + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/PriorityDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/PriorityDto.java new file mode 100644 index 0000000000000000000000000000000000000000..64695b0219e1ae3147c56b30f9a21f694bd5e378 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/PriorityDto.java @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +public class PriorityDto { + + protected Long priority; + + public Long getPriority() { + return priority; + } + + public void setPriority(Long priority) { + this.priority = priority; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..575ac30bdae7e34ab7d46335c994f8a657863ab0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceDto.java @@ -0,0 +1,83 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.rest.dto.LinkableDto; +import org.camunda.bpm.engine.runtime.ProcessInstance; + +public class ProcessInstanceDto extends LinkableDto { + + private String id; + private String definitionId; + private String businessKey; + private String caseInstanceId; + private boolean ended; + private boolean suspended; + private String tenantId; + private String definitionKey; + + public ProcessInstanceDto() { + } + + public ProcessInstanceDto(ProcessInstance instance) { + this.id = instance.getId(); + this.definitionId = instance.getProcessDefinitionId(); + this.definitionKey = instance.getProcessDefinitionKey(); + this.businessKey = instance.getBusinessKey(); + this.caseInstanceId = instance.getCaseInstanceId(); + this.ended = instance.isEnded(); + this.suspended = instance.isSuspended(); + this.tenantId = instance.getTenantId(); + } + + public String getId() { + return id; + } + + public String getDefinitionId() { + return definitionId; + } + + public String getDefinitionKey() { + return definitionKey; + } + + public String getBusinessKey() { + return businessKey; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public boolean isEnded() { + return ended; + } + + public boolean isSuspended() { + return suspended; + } + + public String getTenantId() { + return tenantId; + } + + public static ProcessInstanceDto fromProcessInstance(ProcessInstance instance) { + return new ProcessInstanceDto(instance); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9e575582a5bd6481dd36dec32de886d8c1fd6a09 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceQueryDto.java @@ -0,0 +1,533 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringSetConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ProcessInstanceQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_INSTANCE_ID_VALUE = "instanceId"; + private static final String SORT_BY_DEFINITION_KEY_VALUE = "definitionKey"; + private static final String SORT_BY_DEFINITION_ID_VALUE = "definitionId"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + private static final String SORT_BY_BUSINESS_KEY = "businessKey"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_KEY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DEFINITION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + VALID_SORT_BY_VALUES.add(SORT_BY_BUSINESS_KEY); + } + + private String deploymentId; + private String processDefinitionKey; + private List processDefinitionKeys; + private List processDefinitionKeyNotIn; + private String businessKey; + private String businessKeyLike; + private String caseInstanceId; + private String processDefinitionId; + private String superProcessInstance; + private String subProcessInstance; + private String superCaseInstance; + private String subCaseInstance; + private Boolean active; + private Boolean suspended; + private Set processInstanceIds; + private Boolean withIncident; + private String incidentId; + private String rootProcessInstanceId; + private String incidentType; + private String incidentMessage; + private String incidentMessageLike; + private List tenantIds; + private Boolean withoutTenantId; + private List activityIds; + private Boolean rootProcessInstances; + private Boolean leafProcessInstances; + private Boolean isProcessDefinitionWithoutTenantId; + + protected Boolean variableNamesIgnoreCase; + protected Boolean variableValuesIgnoreCase; + + private List variables; + + private List orQueries; + + public ProcessInstanceQueryDto() { + + } + + public ProcessInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("orQueries") + public void setOrQueries(List orQueries) { + this.orQueries = orQueries; + } + + public Set getProcessInstanceIds() { + return processInstanceIds; + } + + @CamundaQueryParam(value = "processInstanceIds", converter = StringSetConverter.class) + public void setProcessInstanceIds(Set processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public String getDeploymentId() { + return deploymentId; + } + + @CamundaQueryParam("deploymentId") + public void setDeploymentId(String deploymentId) { + this.deploymentId = deploymentId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + public List getProcessDefinitionKeys() { + return processDefinitionKeys; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringListConverter.class) + public void setProcessDefinitionKeyIn(List processDefinitionKeys) { + this.processDefinitionKeys = processDefinitionKeys; + } + + public List getProcessDefinitionKeyNotIn() { + return processDefinitionKeyNotIn; + } + + @CamundaQueryParam(value = "processDefinitionKeyNotIn", converter = StringListConverter.class) + public void setProcessDefinitionKeyNotIn(List processDefinitionKeys) { + this.processDefinitionKeyNotIn = processDefinitionKeys; + } + + public String getBusinessKey() { + return businessKey; + } + + @CamundaQueryParam("businessKey") + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + + public String getBusinessKeyLike() { + return businessKeyLike; + } + + @CamundaQueryParam("businessKeyLike") + public void setBusinessKeyLike(String businessKeyLike) { + this.businessKeyLike = businessKeyLike; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public String getSuperProcessInstance() { + return superProcessInstance; + } + + @CamundaQueryParam("superProcessInstance") + public void setSuperProcessInstance(String superProcessInstance) { + this.superProcessInstance = superProcessInstance; + } + + public String getSubProcessInstance() { + return subProcessInstance; + } + + @CamundaQueryParam("subProcessInstance") + public void setSubProcessInstance(String subProcessInstance) { + this.subProcessInstance = subProcessInstance; + } + + public String getSuperCaseInstance() { + return superCaseInstance; + } + + @CamundaQueryParam("superCaseInstance") + public void setSuperCaseInstance(String superCaseInstance) { + this.superCaseInstance = superCaseInstance; + } + + public String getSubCaseInstance() { + return subCaseInstance; + } + + @CamundaQueryParam("subCaseInstance") + public void setSubCaseInstance(String subCaseInstance) { + this.subCaseInstance = subCaseInstance; + } + + public Boolean isActive() { + return active; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + public Boolean isSuspended() { + return suspended; + } + + @CamundaQueryParam(value = "suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + public List getVariables() { + return variables; + } + + @CamundaQueryParam(value = "variables", converter = VariableListConverter.class) + public void setVariables(List variables) { + this.variables = variables; + } + + public Boolean isVariableNamesIgnoreCase() { + return variableNamesIgnoreCase; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesCaseInsensitive) { + this.variableNamesIgnoreCase = variableNamesCaseInsensitive; + } + + public Boolean isVariableValuesIgnoreCase() { + return variableValuesIgnoreCase; + } + + @CamundaQueryParam(value ="variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesCaseInsensitive) { + this.variableValuesIgnoreCase = variableValuesCaseInsensitive; + } + + public Boolean isWithIncident() { + return withIncident; + } + + @CamundaQueryParam(value = "withIncident", converter = BooleanConverter.class) + public void setWithIncident(Boolean withIncident) { + this.withIncident = withIncident; + } + + public String getIncidentId() { + return incidentId; + } + + @CamundaQueryParam(value = "incidentId") + public void setIncidentId(String incidentId) { + this.incidentId = incidentId; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + @CamundaQueryParam("rootProcessInstanceId") + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + + public String getIncidentType() { + return incidentType; + } + + @CamundaQueryParam(value = "incidentType") + public void setIncidentType(String incidentType) { + this.incidentType = incidentType; + } + + public String getIncidentMessage() { + return incidentMessage; + } + + @CamundaQueryParam(value = "incidentMessage") + public void setIncidentMessage(String incidentMessage) { + this.incidentMessage = incidentMessage; + } + + public String getIncidentMessageLike() { + return incidentMessageLike; + } + + @CamundaQueryParam(value = "incidentMessageLike") + public void setIncidentMessageLike(String incidentMessageLike) { + this.incidentMessageLike = incidentMessageLike; + } + + public List getTenantIdIn() { + return tenantIds; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + public Boolean isWithoutTenantId() { + return withoutTenantId; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + public List getActivityIds() { + return activityIds; + } + + @CamundaQueryParam(value = "activityIdIn", converter = StringListConverter.class) + public void setActivityIdIn(List activityIds) { + this.activityIds = activityIds; + } + + public Boolean isRootProcessInstances() { + return rootProcessInstances; + } + + @CamundaQueryParam(value = "rootProcessInstances", converter = BooleanConverter.class) + public void setRootProcessInstances(Boolean rootProcessInstances) { + this.rootProcessInstances = rootProcessInstances; + } + + + public Boolean isLeafProcessInstances() { + return leafProcessInstances; + } + + @CamundaQueryParam(value = "leafProcessInstances", converter = BooleanConverter.class) + public void setLeafProcessInstances(Boolean leafProcessInstances) { + this.leafProcessInstances = leafProcessInstances; + } + + public Boolean isProcessDefinitionWithoutTenantId() { + return isProcessDefinitionWithoutTenantId; + } + + @CamundaQueryParam(value = "processDefinitionWithoutTenantId", converter = BooleanConverter.class) + public void setProcessDefinitionWithoutTenantId(Boolean isProcessDefinitionWithoutTenantId) { + this.isProcessDefinitionWithoutTenantId = isProcessDefinitionWithoutTenantId; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected ProcessInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getRuntimeService().createProcessInstanceQuery(); + } + + public List getOrQueries() { + return orQueries; + } + + @Override + protected void applyFilters(ProcessInstanceQuery query) { + if (orQueries != null) { + for (ProcessInstanceQueryDto orQueryDto: orQueries) { + ProcessInstanceQueryImpl orQuery = new ProcessInstanceQueryImpl(); + orQuery.setOrQueryActive(); + orQueryDto.applyFilters(orQuery); + ((ProcessInstanceQueryImpl) query).addOrQuery(orQuery); + } + } + if (processInstanceIds != null) { + query.processInstanceIds(processInstanceIds); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processDefinitionKeys != null && !processDefinitionKeys.isEmpty()) { + query.processDefinitionKeyIn(processDefinitionKeys.toArray(new String[processDefinitionKeys.size()])); + } + if (processDefinitionKeyNotIn != null && !processDefinitionKeyNotIn.isEmpty()) { + query.processDefinitionKeyNotIn(processDefinitionKeyNotIn.toArray(new String[processDefinitionKeyNotIn.size()])); + } + if (deploymentId != null) { + query.deploymentId(deploymentId); + } + if (businessKey != null) { + query.processInstanceBusinessKey(businessKey); + } + if (businessKeyLike != null) { + query.processInstanceBusinessKeyLike(businessKeyLike); + } + if(TRUE.equals(withIncident)) { + query.withIncident(); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (superProcessInstance != null) { + query.superProcessInstanceId(superProcessInstance); + } + if (subProcessInstance != null) { + query.subProcessInstanceId(subProcessInstance); + } + if (superCaseInstance != null) { + query.superCaseInstanceId(superCaseInstance); + } + if (subCaseInstance != null) { + query.subCaseInstanceId(subCaseInstance); + } + if (TRUE.equals(active)) { + query.active(); + } + if (TRUE.equals(suspended)) { + query.suspended(); + } + if (incidentId != null) { + query.incidentId(incidentId); + } + if (rootProcessInstanceId != null) { + query.rootProcessInstanceId(rootProcessInstanceId); + } + if (incidentType != null) { + query.incidentType(incidentType); + } + if (incidentMessage != null) { + query.incidentMessage(incidentMessage); + } + if (incidentMessageLike != null) { + query.incidentMessageLike(incidentMessageLike); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (activityIds != null && !activityIds.isEmpty()) { + query.activityIdIn(activityIds.toArray(new String[activityIds.size()])); + } + if (TRUE.equals(rootProcessInstances)) { + query.rootProcessInstances(); + } + if(TRUE.equals(leafProcessInstances)) { + query.leafProcessInstances(); + } + if (TRUE.equals(isProcessDefinitionWithoutTenantId)) { + query.processDefinitionWithoutTenantId(); + } + if(TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + if(TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + if (variables != null) { + for (VariableQueryParameterDto variableQueryParam : variables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.variableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.variableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.variableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.variableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.variableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + } + + @Override + protected void applySortBy(ProcessInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_INSTANCE_ID_VALUE)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_DEFINITION_KEY_VALUE)) { + query.orderByProcessDefinitionKey(); + } else if (sortBy.equals(SORT_BY_DEFINITION_ID_VALUE)) { + query.orderByProcessDefinitionId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } else if (sortBy.equals(SORT_BY_BUSINESS_KEY)) { + query.orderByBusinessKey(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceSuspensionStateAsyncDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceSuspensionStateAsyncDto.java new file mode 100644 index 0000000000000000000000000000000000000000..fc01d6405a1bc81fed0b6190e954cab6381bfd13 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceSuspensionStateAsyncDto.java @@ -0,0 +1,113 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateSelectBuilder; +import org.camunda.bpm.engine.runtime.UpdateProcessInstancesSuspensionStateBuilder; + +public class ProcessInstanceSuspensionStateAsyncDto extends SuspensionStateDto { + + protected List processInstanceIds; + protected ProcessInstanceQueryDto processInstanceQuery; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { + this.processInstanceQuery = processInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public Batch updateSuspensionStateAsync(ProcessEngine engine) { + + int params = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery); + + if (params == 0) { + String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + UpdateProcessInstancesSuspensionStateBuilder updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine); + if (getSuspended()) { + return updateSuspensionStateBuilder.suspendAsync(); + } else { + return updateSuspensionStateBuilder.activateAsync(); + } + } + + protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) { + UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState(); + UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null; + if (processInstanceIds != null) { + groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds); + } + + if (processInstanceQuery != null) { + if (groupBuilder == null) { + groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); + } else { + groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); + } + } + + if (historicProcessInstanceQuery != null) { + if (groupBuilder == null) { + groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); + } else { + groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); + } + } + + return groupBuilder; + } + + protected int parameterCount(Object... o) { + int count = 0; + for (Object o1 : o) { + count += (o1 != null ? 1 : 0); + } + return count; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceSuspensionStateDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceSuspensionStateDto.java new file mode 100644 index 0000000000000000000000000000000000000000..e4ade553c5b048f77af7d13ffd5fb8be75b74982 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceSuspensionStateDto.java @@ -0,0 +1,179 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.List; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateBuilder; +import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateSelectBuilder; +import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateTenantBuilder; +import org.camunda.bpm.engine.runtime.UpdateProcessInstancesSuspensionStateBuilder; + +/** + * @author roman.smirnov + */ +public class ProcessInstanceSuspensionStateDto extends SuspensionStateDto { + + protected String processDefinitionId; + protected String processDefinitionKey; + + protected List processInstanceIds; + protected ProcessInstanceQueryDto processInstanceQuery; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + + protected String processDefinitionTenantId; + protected boolean processDefinitionWithoutTenantId; + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { + this.processInstanceQuery = processInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setProcessDefinitionTenantId(String processDefinitionTenantId) { + this.processDefinitionTenantId = processDefinitionTenantId; + } + + public boolean getProcessDefinitionWithoutTenantId() { + return processDefinitionWithoutTenantId; + } + + public void setProcessDefinitionWithoutTenantId(boolean processDefinitionWithoutTenantId) { + this.processDefinitionWithoutTenantId = processDefinitionWithoutTenantId; + } + + @Override + public void updateSuspensionState(ProcessEngine engine) { + int params = parameterCount(processDefinitionId, processDefinitionKey); + int syncParams = parameterCount(processInstanceIds, processInstanceQuery, historicProcessInstanceQuery); + + if (params >= 1 && syncParams >= 1) { + String message = "Choose either a single processInstance with processDefinitionId or processDefinitionKey or a group of processInstances with processInstanceIds, procesInstanceQuery or historicProcessInstanceQuery."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } else if (params > 1) { + String message = "Only one of processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } else if (params == 0 && syncParams == 0) { + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + UpdateProcessInstanceSuspensionStateBuilder updateSuspensionStateBuilder = null; + if (params == 1) { + updateSuspensionStateBuilder = createUpdateSuspensionStateBuilder(engine); + } else if (syncParams >= 1) { + updateSuspensionStateBuilder = createUpdateSuspensionStateGroupBuilder(engine); + } + + if (getSuspended()) { + updateSuspensionStateBuilder.suspend(); + } else { + updateSuspensionStateBuilder.activate(); + } + } + + protected UpdateProcessInstanceSuspensionStateBuilder createUpdateSuspensionStateBuilder(ProcessEngine engine) { + UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState(); + + if (processDefinitionId != null) { + return selectBuilder.byProcessDefinitionId(processDefinitionId); + } else { // processDefinitionKey != null + UpdateProcessInstanceSuspensionStateTenantBuilder tenantBuilder = selectBuilder.byProcessDefinitionKey(processDefinitionKey); + if (processDefinitionTenantId != null) { + tenantBuilder.processDefinitionTenantId(processDefinitionTenantId); + } else if (processDefinitionWithoutTenantId) { + tenantBuilder.processDefinitionWithoutTenantId(); + } + return tenantBuilder; + } + } + + protected UpdateProcessInstancesSuspensionStateBuilder createUpdateSuspensionStateGroupBuilder(ProcessEngine engine) { + UpdateProcessInstanceSuspensionStateSelectBuilder selectBuilder = engine.getRuntimeService().updateProcessInstanceSuspensionState(); + UpdateProcessInstancesSuspensionStateBuilder groupBuilder = null; + if (processInstanceIds != null) { + groupBuilder = selectBuilder.byProcessInstanceIds(processInstanceIds); + } + + if (processInstanceQuery != null) { + if (groupBuilder == null) { + groupBuilder = selectBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); + } else { + groupBuilder.byProcessInstanceQuery(processInstanceQuery.toQuery(engine)); + } + } + + if (historicProcessInstanceQuery != null) { + if (groupBuilder == null) { + groupBuilder = selectBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); + } else { + groupBuilder.byHistoricProcessInstanceQuery(historicProcessInstanceQuery.toQuery(engine)); + } + } + + return groupBuilder; + } + + protected int parameterCount(Object... o) { + int count = 0; + for (Object o1 : o) { + count += (o1 != null ? 1 : 0); + } + return count; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceWithVariablesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceWithVariablesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..14a68228f78fc34afd746f2389b31afb64c63468 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/ProcessInstanceWithVariablesDto.java @@ -0,0 +1,56 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.Map; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceWithVariables; +import org.camunda.bpm.engine.variable.VariableMap; + +/** + * Represents a process instance dto extension dto that contains latest variables. + * + * @author Christopher Zell + */ +public class ProcessInstanceWithVariablesDto extends ProcessInstanceDto { + + private Map variables; + + public ProcessInstanceWithVariablesDto() { + } + + public ProcessInstanceWithVariablesDto(ProcessInstance instance) { + super(instance); + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public static ProcessInstanceDto fromProcessInstance(ProcessInstanceWithVariables instance) { + ProcessInstanceWithVariablesDto result = new ProcessInstanceWithVariablesDto(instance); + VariableMap variables = instance.getVariables(); + + result.variables = VariableValueDto.fromMap(variables, true); + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/RestartProcessInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/RestartProcessInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..8d6d140cbe101704f2a4e1cb7595ae5aac697107 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/RestartProcessInstanceDto.java @@ -0,0 +1,105 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.modification.ProcessInstanceModificationInstructionDto; +import org.camunda.bpm.engine.runtime.RestartProcessInstanceBuilder; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * + * @author Anna Pazola + * + */ +public class RestartProcessInstanceDto { + + protected List processInstanceIds; + protected List instructions; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + protected boolean initialVariables; + protected boolean skipCustomListeners; + protected boolean skipIoMappings; + protected boolean withoutBusinessKey; + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public List getInstructions() { + return instructions; + } + + public void setInstructions(List instructions) { + this.instructions = instructions; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } + + public boolean isInitialVariables() { + return initialVariables; + } + + public void setInitialVariables(boolean initialVariables) { + this.initialVariables = initialVariables; + } + + public boolean isSkipCustomListeners() { + return skipCustomListeners; + } + + public void setSkipCustomListeners(boolean skipCustomListeners) { + this.skipCustomListeners = skipCustomListeners; + } + + public boolean isSkipIoMappings() { + return skipIoMappings; + } + + public void setSkipIoMappings(boolean skipIoMappings) { + this.skipIoMappings = skipIoMappings; + } + + public boolean isWithoutBusinessKey() { + return withoutBusinessKey; + } + + public void setWithoutBusinessKey(boolean withoutBusinessKey) { + this.withoutBusinessKey = withoutBusinessKey; + } + + public void applyTo(RestartProcessInstanceBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) { + for (ProcessInstanceModificationInstructionDto instruction : instructions) { + + instruction.applyTo(builder, processEngine, objectMapper); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/RetriesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/RetriesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..89ab0f9540cc593afc1b1bf3d8d6202c844b8480 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/RetriesDto.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.util.Date; + +@JsonIgnoreProperties(value = { "dueDateSet" }) +public class RetriesDto { + + protected Integer retries; + protected Date dueDate; + protected boolean dueDateSet = false; // internal property to distinguish between missing due date and null due date parameters + + public Integer getRetries() { + return retries; + } + + public void setRetries(Integer retries) { + this.retries = retries; + } + + public Date getDueDate() { + return dueDate; + } + + public void setDueDate(Date dueDate) { + this.dueDateSet = true; + this.dueDate = dueDate; + } + + public boolean isDueDateSet() { + return dueDateSet; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SerializedObjectDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SerializedObjectDto.java new file mode 100644 index 0000000000000000000000000000000000000000..0039a72e27720a7e41c5cbafad0952c955bd0d27 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SerializedObjectDto.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import com.fasterxml.jackson.databind.type.TypeFactory; + +/** + * + * @author Daniel Meyer + */ +public class SerializedObjectDto { + + protected String type; + protected Object object; + + public SerializedObjectDto(Object value) { + type = TypeFactory.defaultInstance().constructType(value.getClass()).toCanonical(); + object = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Object getObject() { + return object; + } + + public void setObject(Object object) { + this.object = object; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SetJobRetriesByProcessDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SetJobRetriesByProcessDto.java new file mode 100644 index 0000000000000000000000000000000000000000..3be0adfd65f7086f33334f3bbaccb7c2f2532c01 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SetJobRetriesByProcessDto.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.List; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; + +/** + * @author Askar Akhmerov + */ +public class SetJobRetriesByProcessDto extends SetJobRetriesDto { + protected List processInstances; + protected ProcessInstanceQueryDto processInstanceQuery; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + + public List getProcessInstances() { + return processInstances; + } + + public void setProcessInstances(List processInstances) { + this.processInstances = processInstances; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { + this.processInstanceQuery = processInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SetJobRetriesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SetJobRetriesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ef469787eef5470229798bb32c38f335cb46b7db --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/SetJobRetriesDto.java @@ -0,0 +1,44 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.List; + +/** + * @author Askar Akhmerov + */ +public class SetJobRetriesDto extends RetriesDto { + protected List jobIds; + protected JobQueryDto jobQuery; + + public List getJobIds() { + return jobIds; + } + + public void setJobIds(List jobIds) { + this.jobIds = jobIds; + } + + public JobQueryDto getJobQuery() { + return jobQuery; + } + + public void setJobQuery(JobQueryDto jobQuery) { + this.jobQuery = jobQuery; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/StartProcessInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/StartProcessInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..283353026a3d939712091a6e9d1775e077245a6a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/StartProcessInstanceDto.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.runtime.modification.ProcessInstanceModificationInstructionDto; + +public class StartProcessInstanceDto { + + protected Map variables; + protected String businessKey; + protected String caseInstanceId; + protected List startInstructions; + protected boolean skipCustomListeners; + protected boolean skipIoMappings; + protected boolean withVariablesInReturn = false; + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public String getBusinessKey() { + return businessKey; + } + + public void setBusinessKey(String businessKey) { + this.businessKey = businessKey; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + public List getStartInstructions() { + return startInstructions; + } + + public void setStartInstructions(List startInstructions) { + this.startInstructions = startInstructions; + } + + public boolean isSkipCustomListeners() { + return skipCustomListeners; + } + + public void setSkipCustomListeners(boolean skipCustomListeners) { + this.skipCustomListeners = skipCustomListeners; + } + + public boolean isSkipIoMappings() { + return skipIoMappings; + } + + public void setSkipIoMappings(boolean skipIoMappings) { + this.skipIoMappings = skipIoMappings; + } + + public boolean isWithVariablesInReturn() { + return withVariablesInReturn; + } + + public void setWithVariablesInReturn(boolean withVariablesInReturn) { + this.withVariablesInReturn = withVariablesInReturn; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/TransitionInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/TransitionInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..20ab15de3cab564f7dac30102c2595d3b5adb1d6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/TransitionInstanceDto.java @@ -0,0 +1,107 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.runtime.TransitionInstance; + +/** + * @author Daniel Meyer + * + */ +public class TransitionInstanceDto { + + protected String id; + protected String parentActivityInstanceId; + protected String processInstanceId; + protected String processDefinitionId; + protected String activityId; + protected String activityName; + protected String activityType; + protected String executionId; + protected String[] incidentIds; + protected ActivityInstanceIncidentDto[] incidents; + + public String getId() { + return id; + } + + public String getParentActivityInstanceId() { + return parentActivityInstanceId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + @Deprecated + public String getTargetActivityId() { + return activityId; + } + + public String getActivityId() { + return activityId; + } + + public String getActivityName() { + return activityName; + } + + public String getActivityType() { + return activityType; + } + + public String getExecutionId() { + return executionId; + } + + public String[] getIncidentIds() { + return incidentIds; + } + + public ActivityInstanceIncidentDto[] getIncidents() { + return incidents; + } + + public static TransitionInstanceDto fromTransitionInstance(TransitionInstance instance) { + TransitionInstanceDto result = new TransitionInstanceDto(); + result.id = instance.getId(); + result.parentActivityInstanceId = instance.getParentActivityInstanceId(); + result.activityId = instance.getActivityId(); + result.activityName = instance.getActivityName(); + result.activityType = instance.getActivityType(); + result.processInstanceId = instance.getProcessInstanceId(); + result.processDefinitionId = instance.getProcessDefinitionId(); + result.executionId = instance.getExecutionId(); + result.incidentIds = instance.getIncidentIds(); + result.incidents = ActivityInstanceIncidentDto.fromIncidents(instance.getIncidents()); + return result; + } + + + public static TransitionInstanceDto[] fromListOfTransitionInstance(TransitionInstance[] instances) { + TransitionInstanceDto[] result = new TransitionInstanceDto[instances.length]; + for (int i = 0; i < result.length; i++) { + result[i] = fromTransitionInstance(instances[i]); + } + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/TriggerVariableValueDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/TriggerVariableValueDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ee6de48870d153cb9987d2d5d7f73b40a5d409e9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/TriggerVariableValueDto.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +/** + * + * @author Roman Smirnov + * + */ +public class TriggerVariableValueDto extends VariableValueDto { + + protected boolean local; + + public boolean isLocal() { + return local; + } + + public void setLocal(boolean local) { + this.local = local; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableInstanceDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableInstanceDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f81ffd6067e6e7a62cc6f4291d9e4f976d4f2730 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableInstanceDto.java @@ -0,0 +1,155 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.runtime.VariableInstance; + +/** + * @author roman.smirnov + */ +public class VariableInstanceDto extends VariableValueDto { + + protected String id; + protected String name; + protected String processDefinitionId; + protected String processInstanceId; + protected String executionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String taskId; + protected String batchId; + protected String activityInstanceId; + protected String errorMessage; + protected String tenantId; + + public VariableInstanceDto() { } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + public String getBatchId() { + return batchId; + } + + public void setBatchId(String batchId) { + this.batchId = batchId; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public void setActivityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getTenantId() { + return tenantId; + } + + public static VariableInstanceDto fromVariableInstance(VariableInstance variableInstance) { + VariableInstanceDto dto = new VariableInstanceDto(); + + dto.id = variableInstance.getId(); + dto.name = variableInstance.getName(); + dto.processDefinitionId = variableInstance.getProcessDefinitionId(); + dto.processInstanceId = variableInstance.getProcessInstanceId(); + dto.executionId = variableInstance.getExecutionId(); + + dto.caseExecutionId = variableInstance.getCaseExecutionId(); + dto.caseInstanceId = variableInstance.getCaseInstanceId(); + + dto.taskId = variableInstance.getTaskId(); + dto.batchId = variableInstance.getBatchId(); + dto.activityInstanceId = variableInstance.getActivityInstanceId(); + + dto.tenantId = variableInstance.getTenantId(); + + if(variableInstance.getErrorMessage() == null) { + VariableValueDto.fromTypedValue(dto, variableInstance.getTypedValue()); + } + else { + dto.errorMessage = variableInstance.getErrorMessage(); + dto.type = VariableValueDto.toRestApiTypeName(variableInstance.getTypeName()); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableInstanceQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableInstanceQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..cff87910dcaf669d61be58db7036ee9ecf434465 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableInstanceQueryDto.java @@ -0,0 +1,252 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.VariableInstanceQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author roman.smirnov + */ +public class VariableInstanceQueryDto extends AbstractQueryDto { + + private static final String SORT_BY_VARIABLE_NAME_VALUE = "variableName"; + private static final String SORT_BY_VARIABLE_TYPE_VALUE = "variableType"; + private static final String SORT_BY_ACTIVITY_INSTANCE_ID_VALUE = "activityInstanceId"; + private static final String SORT_BY_TENANT_ID = "tenantId"; + + private static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList(); + VALID_SORT_BY_VALUES.add(SORT_BY_VARIABLE_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_VARIABLE_TYPE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ACTIVITY_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID); + } + + protected String variableName; + protected String variableNameLike; + protected List variableValues; + protected Boolean variableNamesIgnoreCase; + protected Boolean variableValuesIgnoreCase; + protected String[] executionIdIn; + protected String[] processInstanceIdIn; + protected String[] caseExecutionIdIn; + protected String[] caseInstanceIdIn; + protected String[] taskIdIn; + protected String[] batchIdIn; + protected String[] variableScopeIdIn; + protected String[] activityInstanceIdIn; + private List tenantIds; + + public VariableInstanceQueryDto() {} + + public VariableInstanceQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("variableName") + public void setVariableName(String variableName) { + this.variableName = variableName; + } + + @CamundaQueryParam("variableNameLike") + public void setVariableNameLike(String variableNameLike) { + this.variableNameLike = variableNameLike; + } + + @CamundaQueryParam(value = "variableValues", converter = VariableListConverter.class) + public void setVariableValues(List variableValues) { + this.variableValues = variableValues; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesIgnoreCase) { + this.variableNamesIgnoreCase = variableNamesIgnoreCase; + } + + @CamundaQueryParam(value = "variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesIgnoreCase) { + this.variableValuesIgnoreCase = variableValuesIgnoreCase; + } + + @CamundaQueryParam(value="executionIdIn", converter = StringArrayConverter.class) + public void setExecutionIdIn(String[] executionIdIn) { + this.executionIdIn = executionIdIn; + } + + @CamundaQueryParam(value="processInstanceIdIn", converter = StringArrayConverter.class) + public void setProcessInstanceIdIn(String[] processInstanceIdIn) { + this.processInstanceIdIn = processInstanceIdIn; + } + + @CamundaQueryParam(value="caseExecutionIdIn", converter = StringArrayConverter.class) + public void setCaseExecutionIdIn(String[] caseExecutionIdIn) { + this.caseExecutionIdIn = caseExecutionIdIn; + } + + @CamundaQueryParam(value="caseInstanceIdIn", converter = StringArrayConverter.class) + public void setCaseInstanceIdIn(String[] caseInstanceIdIn) { + this.caseInstanceIdIn = caseInstanceIdIn; + } + + @CamundaQueryParam(value="taskIdIn", converter = StringArrayConverter.class) + public void setTaskIdIn(String[] taskIdIn) { + this.taskIdIn = taskIdIn; + } + + @CamundaQueryParam(value="batchIdIn", converter = StringArrayConverter.class) + public void setBatchIdIn(String[] batchIdIn) { + this.batchIdIn = batchIdIn; + } + + @CamundaQueryParam(value="variableScopeIdIn", converter = StringArrayConverter.class) + public void setVariableScopeIdIn(String[] variableScopeIdIn) { + this.variableScopeIdIn = variableScopeIdIn; + } + + @CamundaQueryParam(value="activityInstanceIdIn", converter = StringArrayConverter.class) + public void setActivityInstanceIdIn(String[] activityInstanceIdIn) { + this.activityInstanceIdIn = activityInstanceIdIn; + } + + @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) + public void setTenantIdIn(List tenantIds) { + this.tenantIds = tenantIds; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected VariableInstanceQuery createNewQuery(ProcessEngine engine) { + return engine.getRuntimeService().createVariableInstanceQuery(); + } + + @Override + protected void applyFilters(VariableInstanceQuery query) { + if (variableName != null) { + query.variableName(variableName); + } + + if (variableNameLike != null) { + query.variableNameLike(variableNameLike); + } + + if(Boolean.TRUE.equals(variableNamesIgnoreCase)) { + query.matchVariableNamesIgnoreCase(); + } + + if(Boolean.TRUE.equals(variableValuesIgnoreCase)) { + query.matchVariableValuesIgnoreCase(); + } + + if (variableValues != null) { + for (VariableQueryParameterDto variableQueryParam : variableValues) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.variableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.variableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueGreaterThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.variableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.variableValueLessThanOrEqual(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.variableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.variableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid variable comparator specified: " + op); + } + } + } + + if (executionIdIn != null && executionIdIn.length > 0) { + query.executionIdIn(executionIdIn); + } + + if (processInstanceIdIn != null && processInstanceIdIn.length > 0) { + query.processInstanceIdIn(processInstanceIdIn); + } + + if (caseExecutionIdIn != null && caseExecutionIdIn.length > 0) { + query.caseExecutionIdIn(caseExecutionIdIn); + } + + if (caseInstanceIdIn != null && caseInstanceIdIn.length > 0) { + query.caseInstanceIdIn(caseInstanceIdIn); + } + + if (taskIdIn != null && taskIdIn.length > 0) { + query.taskIdIn(taskIdIn); + } + + if (batchIdIn != null && batchIdIn.length > 0) { + query.batchIdIn(batchIdIn); + } + + if (variableScopeIdIn != null && variableScopeIdIn.length > 0) { + query.variableScopeIdIn(variableScopeIdIn); + } + + if (activityInstanceIdIn != null && activityInstanceIdIn.length > 0) { + query.activityInstanceIdIn(activityInstanceIdIn); + } + if (tenantIds != null && !tenantIds.isEmpty()) { + query.tenantIdIn(tenantIds.toArray(new String[0])); + } + } + + @Override + protected void applySortBy(VariableInstanceQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_VARIABLE_NAME_VALUE)) { + query.orderByVariableName(); + } else if (sortBy.equals(SORT_BY_VARIABLE_TYPE_VALUE)) { + query.orderByVariableType(); + } else if (sortBy.equals(SORT_BY_ACTIVITY_INSTANCE_ID_VALUE)) { + query.orderByActivityInstanceId(); + } else if (sortBy.equals(SORT_BY_TENANT_ID)) { + query.orderByTenantId(); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableNameDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableNameDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bc4dae5a06066632c9372f4ba057d91f9a331711 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/VariableNameDto.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime; + +/** + * + * @author Roman Smirnov + * + */ +public class VariableNameDto { + + protected String name; + protected boolean local; + + public VariableNameDto() { + } + + public VariableNameDto(String name) { + this.name = name; + this.local = false; + } + + public VariableNameDto(String name, boolean local) { + this.name = name; + this.local = local; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public boolean isLocal() { + return local; + } + + public void setLocal(boolean local) { + this.local = local; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/CorrelationMessageAsyncDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/CorrelationMessageAsyncDto.java new file mode 100644 index 0000000000000000000000000000000000000000..58447cf74eaa14661a775e2fdb7b1342a1150d0d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/CorrelationMessageAsyncDto.java @@ -0,0 +1,74 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.batch; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; + +import java.util.List; +import java.util.Map; + +public class CorrelationMessageAsyncDto { + + protected String messageName; + protected List processInstanceIds; + protected ProcessInstanceQueryDto processInstanceQuery; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + protected Map variables; + + public String getMessageName() { + return messageName; + } + + public void setMessageName(String messageName) { + this.messageName = messageName; + } + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto runtimeQuery) { + this.processInstanceQuery = runtimeQuery; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historyQuery) { + this.historicProcessInstanceQuery = historyQuery; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/DeleteProcessInstancesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/DeleteProcessInstancesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..a69b08ea6a659b33f9f46214a9bb52e7b3b9823e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/DeleteProcessInstancesDto.java @@ -0,0 +1,92 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.batch; + +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; + +import java.util.List; + +/** + * @author Askar Akhmerov + */ +public class DeleteProcessInstancesDto { + protected List processInstanceIds; + protected ProcessInstanceQueryDto processInstanceQuery; + protected String deleteReason; + protected boolean skipCustomListeners; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + protected boolean skipSubprocesses; + protected boolean skipIoMappings; + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQuery) { + this.processInstanceQuery = processInstanceQuery; + } + + public String getDeleteReason() { + return deleteReason; + } + + public void setDeleteReason(String deleteReason) { + this.deleteReason = deleteReason; + } + + public boolean isSkipCustomListeners() { + return skipCustomListeners; + } + + public void setSkipCustomListeners(boolean skipCustomListeners) { + this.skipCustomListeners = skipCustomListeners; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) { + this.historicProcessInstanceQuery = historicProcessInstanceQuery; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public boolean isSkipSubprocesses() { + return skipSubprocesses; + } + + public void setSkipSubprocesses(Boolean skipSubprocesses) { + this.skipSubprocesses = skipSubprocesses; + } + + public boolean isSkipIoMappings() { + return skipIoMappings; + } + + public void setSkipIoMappings(boolean skipIoMappings) { + this.skipIoMappings = skipIoMappings; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/SetVariablesAsyncDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/SetVariablesAsyncDto.java new file mode 100644 index 0000000000000000000000000000000000000000..592f5953bb7cdeffd36ec2ee65a7fd7d847616a2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/batch/SetVariablesAsyncDto.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.batch; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; + +import java.util.List; +import java.util.Map; + +public class SetVariablesAsyncDto { + + protected List processInstanceIds; + protected ProcessInstanceQueryDto processInstanceQuery; + protected HistoricProcessInstanceQueryDto historicProcessInstanceQuery; + protected Map variables; + + public List getProcessInstanceIds() { + return processInstanceIds; + } + + public void setProcessInstanceIds(List processInstanceIds) { + this.processInstanceIds = processInstanceIds; + } + + public ProcessInstanceQueryDto getProcessInstanceQuery() { + return processInstanceQuery; + } + + public void setProcessInstanceQuery(ProcessInstanceQueryDto runtimeQuery) { + this.processInstanceQuery = runtimeQuery; + } + + public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { + return historicProcessInstanceQuery; + } + + public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historyQuery) { + this.historicProcessInstanceQuery = historyQuery; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/CancellationInstructionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/CancellationInstructionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f8a39a6933ccf9f3f2ff867d3e8ceaf86295fba7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/CancellationInstructionDto.java @@ -0,0 +1,97 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.modification; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.InstantiationBuilder; +import org.camunda.bpm.engine.runtime.ModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Thorben Lindhauer + * + */ +@JsonTypeName(ProcessInstanceModificationInstructionDto.CANCEL_INSTRUCTION_TYPE) +public class CancellationInstructionDto extends ProcessInstanceModificationInstructionDto { + + @Override + public void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + + validateParameters(); + + if (activityId != null) { + builder.cancelAllForActivity(activityId); + } + else if (activityInstanceId != null) { + builder.cancelActivityInstance(activityInstanceId); + } + else if (transitionInstanceId != null) { + builder.cancelTransitionInstance(transitionInstanceId); + } + + } + + protected void validateParameters() { + // exactly one parameter should be set + boolean oneParameterSet = false; + boolean moreThanOneParametersSet = false; + + if (activityId != null) { + oneParameterSet = true; + } + + if (activityInstanceId != null) { + moreThanOneParametersSet |= oneParameterSet; + oneParameterSet = true; + } + + if (transitionInstanceId != null) { + moreThanOneParametersSet |= oneParameterSet; + oneParameterSet = true; + } + + if (moreThanOneParametersSet || !oneParameterSet) { + throw new InvalidRequestException(Status.BAD_REQUEST, buildErrorMessage( + "exactly one, 'activityId', 'activityInstanceId', or 'transitionInstanceId', is required")); + } + } + + @Override + public void applyTo(InstantiationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + // cannot be applied to instantiation + + if (builder instanceof ModificationBuilder) { + if (activityId == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, buildErrorMessage("'activityId' must be set")); + } + if (cancelCurrentActiveActivityInstances) { + ((ModificationBuilder) builder).cancelAllForActivity(activityId, true); + } else { + ((ModificationBuilder) builder).cancelAllForActivity(activityId); + } + } + } + + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/ProcessInstanceModificationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/ProcessInstanceModificationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d14e96db36c44753d166991519c10f0b6164b7f9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/ProcessInstanceModificationDto.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.modification; + +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationBuilder; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Thorben Lindhauer + * + */ +public class ProcessInstanceModificationDto { + + protected boolean skipCustomListeners = false; + protected boolean skipIoMappings = false; + protected List instructions; + protected String annotation; + + public boolean isSkipCustomListeners() { + return skipCustomListeners; + } + + public void setSkipCustomListeners(boolean skipCustomListeners) { + this.skipCustomListeners = skipCustomListeners; + } + + public boolean isSkipIoMappings() { + return skipIoMappings; + } + + public void setSkipIoMappings(boolean skipIoMappings) { + this.skipIoMappings = skipIoMappings; + } + + public List getInstructions() { + return instructions; + } + + public void setInstructions(List instructions) { + this.instructions = instructions; + } + + public void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper objectMapper) { + for (ProcessInstanceModificationInstructionDto instruction : instructions) { + + instruction.applyTo(builder, engine, objectMapper); + } + } + + public String getAnnotation() { + return annotation; + } + + public void setAnnotation(String annotation) { + this.annotation = annotation; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/ProcessInstanceModificationInstructionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/ProcessInstanceModificationInstructionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..060d709c72b227a47d2923320c8b70e219c5ceae --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/ProcessInstanceModificationInstructionDto.java @@ -0,0 +1,134 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.modification; + +import java.util.Map; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.runtime.TriggerVariableValueDto; +import org.camunda.bpm.engine.runtime.ActivityInstantiationBuilder; +import org.camunda.bpm.engine.runtime.InstantiationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationBuilder; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Thorben Lindhauer + * + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true) +@JsonSubTypes(value = { + @JsonSubTypes.Type(value = CancellationInstructionDto.class), + @JsonSubTypes.Type(value = StartBeforeInstructionDto.class), + @JsonSubTypes.Type(value = StartAfterInstructionDto.class), + @JsonSubTypes.Type(value = StartTransitionInstructionDto.class)}) +public abstract class ProcessInstanceModificationInstructionDto { + + public static final String CANCEL_INSTRUCTION_TYPE = "cancel"; + public static final String START_BEFORE_INSTRUCTION_TYPE = "startBeforeActivity"; + public static final String START_TRANSITION_INSTRUCTION_TYPE = "startTransition"; + public static final String START_AFTER_INSTRUCTION_TYPE = "startAfterActivity"; + + protected String type; + + protected Map variables; + + protected String activityId; + protected String transitionId; + protected String activityInstanceId; + protected String transitionInstanceId; + protected String ancestorActivityInstanceId; + protected boolean cancelCurrentActiveActivityInstances; + + public Map getVariables() { + return variables; + } + public void setVariables(Map variables) { + this.variables = variables; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getActivityId() { + return activityId; + } + public void setActivityId(String activityId) { + this.activityId = activityId; + } + public String getTransitionId() { + return transitionId; + } + public void setTransitionId(String transitionId) { + this.transitionId = transitionId; + } + public String getActivityInstanceId() { + return activityInstanceId; + } + public void setActivityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + } + public String getTransitionInstanceId() { + return transitionInstanceId; + } + public void setTransitionInstanceId(String transitionInstanceId) { + this.transitionInstanceId = transitionInstanceId; + } + public String getAncestorActivityInstanceId() { + return ancestorActivityInstanceId; + } + public void setAncestorActivityInstanceId(String ancestorActivityInstanceId) { + this.ancestorActivityInstanceId = ancestorActivityInstanceId; + } + public boolean isCancelCurrentActiveActivityInstances() { + return cancelCurrentActiveActivityInstances; + } + public void setCancelCurrentActiveActivityInstances(boolean cancelCurrentActiveActivityInstances) { + this.cancelCurrentActiveActivityInstances = cancelCurrentActiveActivityInstances; + } + + public abstract void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper); + + public abstract void applyTo(InstantiationBuilder builder, ProcessEngine engine, ObjectMapper mapper); + + protected String buildErrorMessage(String message) { + return "For instruction type '" + type + "': " + message; + } + + protected void applyVariables(ActivityInstantiationBuilder builder, + ProcessEngine engine, ObjectMapper mapper) { + + if (variables != null) { + for (Map.Entry variableValue : variables.entrySet()) { + TriggerVariableValueDto value = variableValue.getValue(); + + if (value.isLocal()) { + builder.setVariableLocal(variableValue.getKey(), value.toTypedValue(engine, mapper)); + } + else { + builder.setVariable(variableValue.getKey(), value.toTypedValue(engine, mapper)); + + } + } + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartAfterInstructionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartAfterInstructionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c551de4afa47cc5ed306524c82c4de0285c847ba --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartAfterInstructionDto.java @@ -0,0 +1,73 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.modification; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.InstantiationBuilder; +import org.camunda.bpm.engine.runtime.ModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationInstantiationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Thorben Lindhauer + * + */ +@JsonTypeName(ProcessInstanceModificationInstructionDto.START_AFTER_INSTRUCTION_TYPE) +public class StartAfterInstructionDto extends ProcessInstanceModificationInstructionDto { + + @Override + public void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + checkValidity(); + + ProcessInstanceModificationInstantiationBuilder activityBuilder = null; + + if (ancestorActivityInstanceId != null) { + activityBuilder = builder.startAfterActivity(activityId, ancestorActivityInstanceId); + } + else { + activityBuilder = builder.startAfterActivity(activityId); + } + + applyVariables(activityBuilder, engine, mapper); + } + + @Override + public void applyTo(InstantiationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + checkValidity(); + + builder.startAfterActivity(activityId); + if (builder instanceof ProcessInstantiationBuilder) { + applyVariables((ProcessInstantiationBuilder) builder, engine, mapper); + } + } + + protected void checkValidity() { + if (activityId == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, + buildErrorMessage("'activityId' must be set")); + } + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartBeforeInstructionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartBeforeInstructionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..a795bf6fe6408b827911fdccd8abc39925891417 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartBeforeInstructionDto.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.modification; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.InstantiationBuilder; +import org.camunda.bpm.engine.runtime.ModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationInstantiationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Thorben Lindhauer + * + */ +@JsonTypeName(ProcessInstanceModificationInstructionDto.START_BEFORE_INSTRUCTION_TYPE) +public class StartBeforeInstructionDto extends ProcessInstanceModificationInstructionDto { + + @Override + public void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + checkValidity(); + + ProcessInstanceModificationInstantiationBuilder activityBuilder = null; + + if (ancestorActivityInstanceId != null) { + activityBuilder = builder.startBeforeActivity(activityId, ancestorActivityInstanceId); + } + else { + activityBuilder = builder.startBeforeActivity(activityId); + } + + applyVariables(activityBuilder, engine, mapper); + + } + + @Override + public void applyTo(InstantiationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + checkValidity(); + + builder.startBeforeActivity(activityId); + + if (builder instanceof ProcessInstantiationBuilder) { + applyVariables((ProcessInstantiationBuilder) builder, engine, mapper); + } + } + + protected void checkValidity() { + if (activityId == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, + buildErrorMessage("'activityId' must be set")); + } + } + + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartTransitionInstructionDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartTransitionInstructionDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c4285c251364cf39a04f358eff810d2f540194b0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/runtime/modification/StartTransitionInstructionDto.java @@ -0,0 +1,71 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.runtime.modification; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.InstantiationBuilder; +import org.camunda.bpm.engine.runtime.ModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationInstantiationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder; + +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Thorben Lindhauer + * + */ +@JsonTypeName(ProcessInstanceModificationInstructionDto.START_TRANSITION_INSTRUCTION_TYPE) +public class StartTransitionInstructionDto extends ProcessInstanceModificationInstructionDto { + + @Override + public void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + checkValidity(); + + ProcessInstanceModificationInstantiationBuilder activityBuilder = null; + + if (ancestorActivityInstanceId != null) { + activityBuilder = builder.startTransition(transitionId, ancestorActivityInstanceId); + } + else { + activityBuilder = builder.startTransition(transitionId); + } + + applyVariables(activityBuilder, engine, mapper); + } + + @Override + public void applyTo(InstantiationBuilder builder, ProcessEngine engine, ObjectMapper mapper) { + checkValidity(); + + builder.startTransition(transitionId); + if (builder instanceof ProcessInstantiationBuilder) { + applyVariables((ProcessInstantiationBuilder) builder, engine, mapper); + } + } + + protected void checkValidity() { + if (transitionId == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, + buildErrorMessage("'transitionId' must be set")); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/AttachmentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/AttachmentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4990b119a711995e893dc42f56bd4dad64a64d46 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/AttachmentDto.java @@ -0,0 +1,124 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import java.util.Date; + +import org.camunda.bpm.engine.rest.dto.LinkableDto; +import org.camunda.bpm.engine.task.Attachment; + +public class AttachmentDto extends LinkableDto { + + private String id; + private String name; + private String description; + private String taskId; + private String type; + private String url; + private Date createTime; + private Date removalTime; + private String rootProcessInstanceId; + + public AttachmentDto() { + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getRemovalTime() { + return removalTime; + } + + public void setRemovalTime(Date removalTime) { + this.removalTime = removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + + public static AttachmentDto fromAttachment(Attachment attachment) { + AttachmentDto dto = new AttachmentDto(); + dto.id = attachment.getId(); + dto.name = attachment.getName(); + dto.type = attachment.getType(); + dto.description = attachment.getDescription(); + dto.taskId = attachment.getTaskId(); + dto.url = attachment.getUrl(); + dto.createTime = attachment.getCreateTime(); + dto.removalTime = attachment.getRemovalTime(); + dto.rootProcessInstanceId = attachment.getRootProcessInstanceId(); + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/CommentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/CommentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..3bccc29613217aa698f09d121f3781d082b4b33e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/CommentDto.java @@ -0,0 +1,112 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import org.camunda.bpm.engine.rest.dto.LinkableDto; +import org.camunda.bpm.engine.task.Comment; + +import java.util.Date; + +public class CommentDto extends LinkableDto { + + protected String id; + protected String userId; + protected Date time; + protected String taskId; + protected String message; + protected Date removalTime; + protected String rootProcessInstanceId; + protected String processInstanceId; + + public CommentDto() { + } + + public String getId() { + return id; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public Date getTime() { + return time; + } + + public void setTime(Date time) { + this.time = time; + } + + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public Date getRemovalTime() { + return removalTime; + } + + public void setRemovalTime(Date removalDate) { + this.removalTime = removalDate; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public void setRootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + } + + public String getProcessInstanceId() { + return this.processInstanceId; + } + + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public static CommentDto fromComment(Comment comment) { + CommentDto dto = new CommentDto(); + dto.id = comment.getId(); + dto.userId = comment.getUserId(); + dto.time = comment.getTime(); + dto.taskId = comment.getTaskId(); + dto.message = comment.getFullMessage(); + dto.removalTime = comment.getRemovalTime(); + dto.rootProcessInstanceId = comment.getRootProcessInstanceId(); + dto.processInstanceId = comment.getProcessInstanceId(); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/CompleteTaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/CompleteTaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..144ccbc2885b235955205a1b56bf6e9a3ffd30be --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/CompleteTaskDto.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +import java.util.Map; + +public class CompleteTaskDto { + + private Map variables; + private boolean withVariablesInReturn; + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public boolean isWithVariablesInReturn() { + return withVariablesInReturn; + } + + public void setWithVariablesInReturn(boolean withVariablesInReturn) { + this.withVariablesInReturn = withVariablesInReturn; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/FormDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/FormDto.java new file mode 100644 index 0000000000000000000000000000000000000000..8256c19f61a70a45ee3b75595d477b6c166a7117 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/FormDto.java @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import org.camunda.bpm.engine.form.CamundaFormRef; +import org.camunda.bpm.engine.form.FormData; + +/** + * + * @author nico.rehwaldt + */ +public class FormDto { + + private String key; + private CamundaFormRef camundaFormRef; + private String contextPath; + + public void setKey(String form) { + this.key = form; + } + + public String getKey() { + return key; + } + + public CamundaFormRef getCamundaFormRef() { + return camundaFormRef; + } + + public void setCamundaFormRef(CamundaFormRef camundaFormRef) { + this.camundaFormRef = camundaFormRef; + } + + public void setContextPath(String contextPath) { + this.contextPath = contextPath; + } + + public String getContextPath() { + return contextPath; + } + + public static FormDto fromFormData(FormData formData) { + FormDto dto = new FormDto(); + + if (formData != null) { + dto.key = formData.getFormKey(); + dto.camundaFormRef = formData.getCamundaFormRef(); + } + + return dto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/GroupDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/GroupDto.java new file mode 100644 index 0000000000000000000000000000000000000000..334de8464d94951fa04bfa59dadf640e41a9d59f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/GroupDto.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +/** + * @author: drobisch + */ +public class GroupDto { + private String id; + private String name; + + public GroupDto(String id, String name) { + this.id = id; + this.name = name; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/GroupInfoDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/GroupInfoDto.java new file mode 100644 index 0000000000000000000000000000000000000000..acb3ceae40a637be8c38a16c0ea0fbf04c65b9ae --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/GroupInfoDto.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import java.util.List; +import java.util.Set; + +/** + * @author: drobisch + */ +public class GroupInfoDto { + + private final List groups; + private Set groupUsers; + + public GroupInfoDto() { + this.groups = null; + this.groupUsers = null; + } + + public GroupInfoDto(List groups, Set groupUsers) { + this.groupUsers = groupUsers; + this.groups = groups; + } + + public Set getGroupUsers() { + return groupUsers; + } + + public List getGroups() { + return groups; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/IdentityLinkDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/IdentityLinkDto.java new file mode 100644 index 0000000000000000000000000000000000000000..c669f8112b7ca18f92f92028fbb6bad442610844 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/IdentityLinkDto.java @@ -0,0 +1,73 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.task.IdentityLink; + +import javax.ws.rs.core.Response.Status; + +public class IdentityLinkDto { + + protected String userId; + protected String groupId; + protected String type; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getGroupId() { + return groupId; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public static IdentityLinkDto fromIdentityLink(IdentityLink identityLink) { + IdentityLinkDto dto = new IdentityLinkDto(); + dto.userId = identityLink.getUserId(); + dto.groupId = identityLink.getGroupId(); + dto.type = identityLink.getType(); + + return dto; + } + + public void validate() { + if (userId != null && groupId != null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Identity Link requires userId or groupId, but not both."); + } + + if (userId == null && groupId == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Identity Link requires userId or groupId."); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskBpmnErrorDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskBpmnErrorDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f4bcd7eae7ce7925b80d9509cfdbb2c10ac8156e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskBpmnErrorDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +public class TaskBpmnErrorDto { + + protected String errorCode; + protected String errorMessage; + protected Map variables; + + + public String getErrorCode() { + return errorCode; + } + + public void setErrorCode(String errorCode) { + this.errorCode = errorCode; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskCountByCandidateGroupResultDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskCountByCandidateGroupResultDto.java new file mode 100644 index 0000000000000000000000000000000000000000..f71ca6161734d7877e74b820d53d526d90b1a800 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskCountByCandidateGroupResultDto.java @@ -0,0 +1,70 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.task.TaskCountByCandidateGroupResult; +import org.camunda.bpm.engine.task.TaskReport; + +import javax.ws.rs.core.Response; +import java.util.List; + +/** + * @author Stefan Hentschel. + */ +public class TaskCountByCandidateGroupResultDto { + + protected String groupName; + protected int taskCount; + + public int getTaskCount() { + return taskCount; + } + + public void setTaskCount(int taskCount) { + this.taskCount = taskCount; + } + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public static TaskCountByCandidateGroupResultDto fromTaskCountByCandidateGroupResultDto(TaskCountByCandidateGroupResult taskCountByCandidateGroupResult) { + TaskCountByCandidateGroupResultDto dto = new TaskCountByCandidateGroupResultDto(); + + dto.groupName = taskCountByCandidateGroupResult.getGroupName(); + dto.taskCount = taskCountByCandidateGroupResult.getTaskCount(); + + return dto; + } + + public List executeTaskCountByCandidateGroupReport(ProcessEngine engine) { + TaskReport reportQuery = engine.getTaskService().createTaskReport(); + + try { + return reportQuery.taskCountByCandidateGroup(); + } catch( NotValidException e ) { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, e, e.getMessage()); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ee4943915b1c90504aca39d464937fb71b943d0a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskDto.java @@ -0,0 +1,307 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import java.util.Date; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.form.CamundaFormRef; +import org.camunda.bpm.engine.rest.dto.converter.DelegationStateConverter; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.task.DelegationState; +import org.camunda.bpm.engine.task.Task; + +public class TaskDto { + + private String id; + private String name; + private String assignee; + private Date created; + private Date due; + private Date followUp; + private Date lastUpdated; + private String delegationState; + private String description; + private String executionId; + private String owner; + private String parentTaskId; + private int priority; + private String processDefinitionId; + private String processInstanceId; + private String taskDefinitionKey; + private String caseExecutionId; + private String caseInstanceId; + private String caseDefinitionId; + private boolean suspended; + private String formKey; + private CamundaFormRef camundaFormRef; + private String tenantId; + /** + * Returns task State of task + */ + private String taskState; + + public TaskDto() { + } + + public TaskDto(Task task) { + this.id = task.getId(); + this.name = task.getName(); + this.assignee = task.getAssignee(); + this.created = task.getCreateTime(); + this.lastUpdated = task.getLastUpdated(); + this.due = task.getDueDate(); + this.followUp = task.getFollowUpDate(); + + if (task.getDelegationState() != null) { + this.delegationState = task.getDelegationState().toString(); + } + + this.description = task.getDescription(); + this.executionId = task.getExecutionId(); + this.owner = task.getOwner(); + this.parentTaskId = task.getParentTaskId(); + this.priority = task.getPriority(); + this.processDefinitionId = task.getProcessDefinitionId(); + this.processInstanceId = task.getProcessInstanceId(); + this.taskDefinitionKey = task.getTaskDefinitionKey(); + this.caseDefinitionId = task.getCaseDefinitionId(); + this.caseExecutionId = task.getCaseExecutionId(); + this.caseInstanceId = task.getCaseInstanceId(); + this.suspended = task.isSuspended(); + this.tenantId = task.getTenantId(); + this.taskState = task.getTaskState(); + try { + this.formKey = task.getFormKey(); + this.camundaFormRef = task.getCamundaFormRef(); + } + catch (BadUserRequestException e) { + // ignore (initializeFormKeys was not called) + } + } + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAssignee() { + return assignee; + } + + public void setAssignee(String assignee) { + this.assignee = assignee; + } + + public Date getCreated() { + return created; + } + + public Date getDue() { + return due; + } + + public void setDue(Date due) { + this.due = due; + } + + public String getDelegationState() { + return delegationState; + } + + public void setDelegationState(String delegationState) { + this.delegationState = delegationState; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getExecutionId() { + return executionId; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getParentTaskId() { + return parentTaskId; + } + + public void setParentTaskId(String parentTaskId) { + this.parentTaskId = parentTaskId; + } + + public int getPriority() { + return priority; + } + + public void setPriority(int priority) { + this.priority = priority; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getTaskDefinitionKey() { + return taskDefinitionKey; + } + + public Date getFollowUp() { + return followUp; + } + + public void setFollowUp(Date followUp) { + this.followUp = followUp; + } + + public Date getLastUpdated() { + return lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + public boolean isSuspended() { + return suspended; + } + + public String getFormKey() { + return formKey; + } + + public CamundaFormRef getCamundaFormRef() { + return camundaFormRef; + } + + public String getTenantId() { + return tenantId; + } + + public void setTenantId(String tenantId) { + this.tenantId = tenantId; + } + + public String getTaskState() { + return taskState; + } + public void setTaskState(String taskState) { + this.taskState = taskState; + } + + public static TaskDto fromEntity(Task task) { + TaskDto dto = new TaskDto(); + dto.id = task.getId(); + dto.name = task.getName(); + dto.assignee = task.getAssignee(); + dto.created = task.getCreateTime(); + dto.lastUpdated = task.getLastUpdated(); + dto.due = task.getDueDate(); + dto.followUp = task.getFollowUpDate(); + + if (task.getDelegationState() != null) { + dto.delegationState = task.getDelegationState().toString(); + } + + dto.description = task.getDescription(); + dto.executionId = task.getExecutionId(); + dto.owner = task.getOwner(); + dto.parentTaskId = task.getParentTaskId(); + dto.priority = task.getPriority(); + dto.processDefinitionId = task.getProcessDefinitionId(); + dto.processInstanceId = task.getProcessInstanceId(); + dto.taskDefinitionKey = task.getTaskDefinitionKey(); + dto.caseDefinitionId = task.getCaseDefinitionId(); + dto.caseExecutionId = task.getCaseExecutionId(); + dto.caseInstanceId = task.getCaseInstanceId(); + dto.suspended = task.isSuspended(); + dto.tenantId = task.getTenantId(); + dto.taskState = task.getTaskState(); + + try { + dto.formKey = task.getFormKey(); + dto.camundaFormRef = task.getCamundaFormRef(); + } + catch (BadUserRequestException e) { + // ignore (initializeFormKeys was not called) + } + return dto; + } + + public void updateTask(Task task) { + task.setName(getName()); + task.setDescription(getDescription()); + task.setPriority(getPriority()); + task.setAssignee(getAssignee()); + task.setOwner(getOwner()); + + DelegationState state = null; + if (getDelegationState() != null) { + DelegationStateConverter converter = new DelegationStateConverter(); + state = converter.convertQueryParameterToType(getDelegationState()); + } + task.setDelegationState(state); + + task.setDueDate(getDue()); + task.setFollowUpDate(getFollowUp()); + task.setParentTaskId(getParentTaskId()); + task.setCaseInstanceId(getCaseInstanceId()); + task.setTenantId(getTenantId()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskEscalationDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskEscalationDto.java new file mode 100644 index 0000000000000000000000000000000000000000..047d64e85db88c74d243e5c8ba4542f488e91b3e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskEscalationDto.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import java.util.Map; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; + +public class TaskEscalationDto { + + protected String escalationCode; + protected Map variables; + + + public String getEscalationCode() { + return escalationCode; + } + + public void setEscalationCode(String escalationCode) { + this.escalationCode = escalationCode; + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..83893e67ea3b6244e70c8081f8abc64d23354b2f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskQueryDto.java @@ -0,0 +1,1929 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import static java.lang.Boolean.TRUE; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.QueryEntityRelationCondition; +import org.camunda.bpm.engine.impl.QueryOrderingProperty; +import org.camunda.bpm.engine.impl.TaskQueryImpl; +import org.camunda.bpm.engine.impl.TaskQueryProperty; +import org.camunda.bpm.engine.impl.TaskQueryVariableValue; +import org.camunda.bpm.engine.impl.VariableInstanceQueryProperty; +import org.camunda.bpm.engine.impl.VariableOrderProperty; +import org.camunda.bpm.engine.impl.persistence.entity.SuspensionState; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.query.QueryProperty; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.SortingDto; +import org.camunda.bpm.engine.rest.dto.VariableQueryParameterDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.DelegationStateConverter; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.converter.VariableListConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.task.DelegationState; +import org.camunda.bpm.engine.task.TaskQuery; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.type.ValueTypeResolver; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.ObjectMapper; + +@JsonInclude(Include.NON_NULL) +public class TaskQueryDto extends AbstractQueryDto { + + public static final String SORT_BY_PROCESS_INSTANCE_ID_VALUE = "instanceId"; + public static final String SORT_BY_CASE_INSTANCE_ID_VALUE = "caseInstanceId"; + public static final String SORT_BY_DUE_DATE_VALUE = "dueDate"; + public static final String SORT_BY_FOLLOW_UP_VALUE = "followUpDate"; + public static final String SORT_BY_EXECUTION_ID_VALUE = "executionId"; + public static final String SORT_BY_CASE_EXECUTION_ID_VALUE = "caseExecutionId"; + public static final String SORT_BY_ASSIGNEE_VALUE = "assignee"; + public static final String SORT_BY_CREATE_TIME_VALUE = "created"; + public static final String SORT_BY_LAST_UPDATED_VALUE = "lastUpdated"; + public static final String SORT_BY_DESCRIPTION_VALUE = "description"; + public static final String SORT_BY_ID_VALUE = "id"; + public static final String SORT_BY_NAME_VALUE = "name"; + public static final String SORT_BY_NAME_CASE_INSENSITIVE_VALUE = "nameCaseInsensitive"; + public static final String SORT_BY_PRIORITY_VALUE = "priority"; + public static final String SORT_BY_TENANT_ID_VALUE = "tenantId"; + + public static final String SORT_BY_PROCESS_VARIABLE = "processVariable"; + public static final String SORT_BY_EXECUTION_VARIABLE = "executionVariable"; + public static final String SORT_BY_TASK_VARIABLE = "taskVariable"; + public static final String SORT_BY_CASE_INSTANCE_VARIABLE = "caseInstanceVariable"; + public static final String SORT_BY_CASE_EXECUTION_VARIABLE = "caseExecutionVariable"; + + public static final List VALID_SORT_BY_VALUES; + static { + VALID_SORT_BY_VALUES = new ArrayList<>(); + VALID_SORT_BY_VALUES.add(SORT_BY_PROCESS_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_INSTANCE_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DUE_DATE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_FOLLOW_UP_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_EXECUTION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CASE_EXECUTION_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ASSIGNEE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_CREATE_TIME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_LAST_UPDATED_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_DESCRIPTION_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_NAME_CASE_INSENSITIVE_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_PRIORITY_VALUE); + VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID_VALUE); + } + + public static final String SORT_PARAMETERS_VARIABLE_NAME = "variable"; + public static final String SORT_PARAMETERS_VALUE_TYPE = "type"; + + private String processInstanceBusinessKey; + private String processInstanceBusinessKeyExpression; + private String[] processInstanceBusinessKeyIn; + private String processInstanceBusinessKeyLike; + private String processInstanceBusinessKeyLikeExpression; + private String processDefinitionKey; + private String[] processDefinitionKeyIn; + private String processDefinitionId; + private String executionId; + private String[] activityInstanceIdIn; + private String processDefinitionName; + private String processDefinitionNameLike; + private String processInstanceId; + private String[] processInstanceIdIn; + private String assignee; + private String assigneeExpression; + private String assigneeLike; + private String assigneeLikeExpression; + private String[] assigneeIn; + private String[] assigneeNotIn; + private String candidateGroup; + private String candidateGroupExpression; + private String candidateGroupLike; + private String candidateUser; + private String candidateUserExpression; + private Boolean includeAssignedTasks; + private String taskDefinitionKey; + private String[] taskDefinitionKeyIn; + private String[] taskDefinitionKeyNotIn; + private String taskDefinitionKeyLike; + private String taskId; + private String[] taskIdIn; + private String description; + private String descriptionLike; + private String involvedUser; + private String involvedUserExpression; + private Integer maxPriority; + private Integer minPriority; + private String name; + private String nameNotEqual; + private String nameLike; + private String nameNotLike; + private String owner; + private String ownerExpression; + private Integer priority; + private String parentTaskId; + protected Boolean assigned; + private Boolean unassigned; + private Boolean active; + private Boolean suspended; + + private String caseDefinitionKey; + private String caseDefinitionId; + private String caseDefinitionName; + private String caseDefinitionNameLike; + private String caseInstanceId; + private String caseInstanceBusinessKey; + private String caseInstanceBusinessKeyLike; + private String caseExecutionId; + + private Date dueAfter; + private String dueAfterExpression; + private Date dueBefore; + private String dueBeforeExpression; + private Date dueDate; + private String dueDateExpression; + private Boolean withoutDueDate; + private Date followUpAfter; + private String followUpAfterExpression; + private Date followUpBefore; + private String followUpBeforeExpression; + private Date followUpBeforeOrNotExistent; + private String followUpBeforeOrNotExistentExpression; + private Date followUpDate; + private String followUpDateExpression; + private Date createdAfter; + private String createdAfterExpression; + private Date createdBefore; + private String createdBeforeExpression; + private Date createdOn; + private String createdOnExpression; + private Date updatedAfter; + private String updatedAfterExpression; + + private String delegationState; + + private String[] tenantIdIn; + private Boolean withoutTenantId; + + private List candidateGroups; + private String candidateGroupsExpression; + protected Boolean withCandidateGroups; + protected Boolean withoutCandidateGroups; + protected Boolean withCandidateUsers; + protected Boolean withoutCandidateUsers; + + protected Boolean variableNamesIgnoreCase; + protected Boolean variableValuesIgnoreCase; + + private List taskVariables; + private List processVariables; + private List caseInstanceVariables; + + private List orQueries; + + private Boolean withCommentAttachmentInfo; + + private Boolean withTaskVariablesInReturn; + + private Boolean withTaskLocalVariablesInReturn; + + public TaskQueryDto() { + + } + + public TaskQueryDto(ObjectMapper objectMapper, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + } + + @CamundaQueryParam("orQueries") + public void setOrQueries(List orQueries) { + this.orQueries = orQueries; + } + + @CamundaQueryParam("processInstanceBusinessKey") + public void setProcessInstanceBusinessKey(String businessKey) { + this.processInstanceBusinessKey = businessKey; + } + + @CamundaQueryParam("processInstanceBusinessKeyExpression") + public void setProcessInstanceBusinessKeyExpression(String businessKeyExpression) { + this.processInstanceBusinessKeyExpression = businessKeyExpression; + } + + @CamundaQueryParam(value = "processInstanceBusinessKeyIn", converter = StringArrayConverter.class) + public void setProcessInstanceBusinessKeyIn(String[] processInstanceBusinessKeyIn) { + this.processInstanceBusinessKeyIn = processInstanceBusinessKeyIn; + } + + @CamundaQueryParam("processInstanceBusinessKeyLike") + public void setProcessInstanceBusinessKeyLike(String businessKeyLike) { + this.processInstanceBusinessKeyLike = businessKeyLike; + } + + @CamundaQueryParam("processInstanceBusinessKeyLikeExpression") + public void setProcessInstanceBusinessKeyLikeExpression(String businessKeyLikeExpression) { + this.processInstanceBusinessKeyLikeExpression = businessKeyLikeExpression; + } + + @CamundaQueryParam("processDefinitionKey") + public void setProcessDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + } + + @CamundaQueryParam(value = "processDefinitionKeyIn", converter = StringArrayConverter.class) + public void setProcessDefinitionKeyIn(String[] processDefinitionKeyIn) { + this.processDefinitionKeyIn = processDefinitionKeyIn; + } + + @CamundaQueryParam("processDefinitionId") + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam("executionId") + public void setExecutionId(String executionId) { + this.executionId = executionId; + } + + @CamundaQueryParam(value="activityInstanceIdIn", converter = StringArrayConverter.class) + public void setActivityInstanceIdIn(String[] activityInstanceIdIn) { + this.activityInstanceIdIn = activityInstanceIdIn; + } + + @CamundaQueryParam(value="tenantIdIn", converter = StringArrayConverter.class) + public void setTenantIdIn(String[] tenantIdIn) { + this.tenantIdIn = tenantIdIn; + } + + @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) + public void setWithoutTenantId(Boolean withoutTenantId) { + this.withoutTenantId = withoutTenantId; + } + + @CamundaQueryParam("processDefinitionName") + public void setProcessDefinitionName(String processDefinitionName) { + this.processDefinitionName = processDefinitionName; + } + + @CamundaQueryParam("processDefinitionNameLike") + public void setProcessDefinitionNameLike(String processDefinitionNameLike) { + this.processDefinitionNameLike = processDefinitionNameLike; + } + + @CamundaQueryParam("processInstanceId") + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @CamundaQueryParam(value = "processInstanceIdIn", converter = StringArrayConverter.class) + public void setProcessInstanceIdIn(String[] processInstanceIdIn) { + this.processInstanceIdIn = processInstanceIdIn; + } + + @CamundaQueryParam("assignee") + public void setAssignee(String assignee) { + this.assignee = assignee; + } + + @CamundaQueryParam("assigneeExpression") + public void setAssigneeExpression(String assigneeExpression) { + this.assigneeExpression = assigneeExpression; + } + + @CamundaQueryParam("assigneeLike") + public void setAssigneeLike(String assigneeLike) { + this.assigneeLike = assigneeLike; + } + + @CamundaQueryParam(value = "assigneeIn", converter = StringArrayConverter.class) + public void setAssigneeIn(String[] assigneeIn) { + this.assigneeIn = assigneeIn; + } + + @CamundaQueryParam(value = "assigneeNotIn", converter = StringArrayConverter.class) + public void setAssigneeNotIn(String[] assigneeNotIn) { + this.assigneeNotIn = assigneeNotIn; + } + + @CamundaQueryParam("assigneeLikeExpression") + public void setAssigneeLikeExpression(String assigneeLikeExpression) { + this.assigneeLikeExpression = assigneeLikeExpression; + } + + @CamundaQueryParam("candidateGroup") + public void setCandidateGroup(String candidateGroup) { + this.candidateGroup = candidateGroup; + } + + @CamundaQueryParam("candidateGroupExpression") + public void setCandidateGroupExpression(String candidateGroupExpression) { + this.candidateGroupExpression = candidateGroupExpression; + } + + @CamundaQueryParam("candidateGroupLike") + public void setCandidateGroupLike(String candidateGroupLike) { + this.candidateGroupLike = candidateGroupLike; + } + + @CamundaQueryParam(value = "withCandidateGroups", converter = BooleanConverter.class) + public void setWithCandidateGroups(Boolean withCandidateGroups) { + this.withCandidateGroups = withCandidateGroups; + } + + @CamundaQueryParam(value = "withoutCandidateGroups", converter = BooleanConverter.class) + public void setWithoutCandidateGroups(Boolean withoutCandidateGroups) { + this.withoutCandidateGroups = withoutCandidateGroups; + } + + @CamundaQueryParam(value = "withCandidateUsers", converter = BooleanConverter.class) + public void setWithCandidateUsers(Boolean withCandidateUsers) { + this.withCandidateUsers = withCandidateUsers; + } + + @CamundaQueryParam(value = "withoutCandidateUsers", converter = BooleanConverter.class) + public void setWithoutCandidateUsers(Boolean withoutCandidateUsers) { + this.withoutCandidateUsers = withoutCandidateUsers; + } + + @CamundaQueryParam("candidateUser") + public void setCandidateUser(String candidateUser) { + this.candidateUser = candidateUser; + } + + @CamundaQueryParam("candidateUserExpression") + public void setCandidateUserExpression(String candidateUserExpression) { + this.candidateUserExpression = candidateUserExpression; + } + + @CamundaQueryParam(value = "includeAssignedTasks", converter = BooleanConverter.class) + public void setIncludeAssignedTasks(Boolean includeAssignedTasks){ + this.includeAssignedTasks = includeAssignedTasks; + } + + @CamundaQueryParam("taskId") + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + @CamundaQueryParam(value = "taskIdIn", converter= StringArrayConverter.class) + public void setTaskIdIn(String[] taskIdIn) { + this.taskIdIn = taskIdIn; + } + + @CamundaQueryParam("taskDefinitionKey") + public void setTaskDefinitionKey(String taskDefinitionKey) { + this.taskDefinitionKey = taskDefinitionKey; + } + + @CamundaQueryParam(value = "taskDefinitionKeyIn", converter= StringArrayConverter.class) + public void setTaskDefinitionKeyIn(String[] taskDefinitionKeyIn) { + this.taskDefinitionKeyIn = taskDefinitionKeyIn; + } + + @CamundaQueryParam(value = "taskDefinitionKeyNotIn", converter= StringArrayConverter.class) + public void setTaskDefinitionKeyNotIn(String[] taskDefinitionKeyNotIn) { + this.taskDefinitionKeyNotIn = taskDefinitionKeyNotIn; + } + + @CamundaQueryParam("taskDefinitionKeyLike") + public void setTaskDefinitionKeyLike(String taskDefinitionKeyLike) { + this.taskDefinitionKeyLike = taskDefinitionKeyLike; + } + + @CamundaQueryParam("description") + public void setDescription(String description) { + this.description = description; + } + + @CamundaQueryParam("descriptionLike") + public void setDescriptionLike(String descriptionLike) { + this.descriptionLike = descriptionLike; + } + + @CamundaQueryParam("involvedUser") + public void setInvolvedUser(String involvedUser) { + this.involvedUser = involvedUser; + } + + @CamundaQueryParam("involvedUserExpression") + public void setInvolvedUserExpression(String involvedUserExpression) { + this.involvedUserExpression = involvedUserExpression; + } + + @CamundaQueryParam(value = "maxPriority", converter = IntegerConverter.class) + public void setMaxPriority(Integer maxPriority) { + this.maxPriority = maxPriority; + } + + @CamundaQueryParam(value = "minPriority", converter = IntegerConverter.class) + public void setMinPriority(Integer minPriority) { + this.minPriority = minPriority; + } + + @CamundaQueryParam("name") + public void setName(String name) { + this.name = name; + } + + @CamundaQueryParam("nameNotEqual") + public void setNameNotEqual(String nameNotEqual) { + this.nameNotEqual = nameNotEqual; + } + + @CamundaQueryParam("nameLike") + public void setNameLike(String nameLike) { + this.nameLike = nameLike; + } + + @CamundaQueryParam("nameNotLike") + public void setNameNotLike(String nameNotLike) { + this.nameNotLike = nameNotLike; + } + + @CamundaQueryParam("owner") + public void setOwner(String owner) { + this.owner = owner; + } + + @CamundaQueryParam("ownerExpression") + public void setOwnerExpression(String ownerExpression) { + this.ownerExpression = ownerExpression; + } + + @CamundaQueryParam(value = "priority", converter = IntegerConverter.class) + public void setPriority(Integer priority) { + this.priority = priority; + } + + @CamundaQueryParam("parentTaskId") + public void setParentTaskId(String parentTaskId) { + this.parentTaskId = parentTaskId; + } + + @CamundaQueryParam(value = "assigned", converter = BooleanConverter.class) + public void setAssigned(Boolean assigned) { + this.assigned = assigned; + } + + @CamundaQueryParam(value = "unassigned", converter = BooleanConverter.class) + public void setUnassigned(Boolean unassigned) { + this.unassigned = unassigned; + } + + @CamundaQueryParam(value = "active", converter = BooleanConverter.class) + public void setActive(Boolean active) { + this.active = active; + } + + @CamundaQueryParam(value = "suspended", converter = BooleanConverter.class) + public void setSuspended(Boolean suspended) { + this.suspended = suspended; + } + + @CamundaQueryParam(value = "dueAfter", converter = DateConverter.class) + public void setDueAfter(Date dueAfter) { + this.dueAfter = dueAfter; + } + + @CamundaQueryParam(value = "dueAfterExpression") + public void setDueAfterExpression(String dueAfterExpression) { + this.dueAfterExpression = dueAfterExpression; + } + + @CamundaQueryParam(value = "dueBefore", converter = DateConverter.class) + public void setDueBefore(Date dueBefore) { + this.dueBefore = dueBefore; + } + + @CamundaQueryParam(value = "dueBeforeExpression") + public void setDueBeforeExpression(String dueBeforeExpression) { + this.dueBeforeExpression = dueBeforeExpression; + } + + @CamundaQueryParam(value = "dueDate", converter = DateConverter.class) + public void setDueDate(Date dueDate) { + this.dueDate = dueDate; + } + + @Deprecated + @CamundaQueryParam(value = "due", converter = DateConverter.class) + public void setDue(Date dueDate) { + this.dueDate = dueDate; + } + + @CamundaQueryParam(value = "dueDateExpression") + public void setDueDateExpression(String dueDateExpression) { + this.dueDateExpression = dueDateExpression; + } + + @CamundaQueryParam(value = "withoutDueDate", converter = BooleanConverter.class) + public void setWithoutDueDate(Boolean withoutDueDate) { + this.withoutDueDate = withoutDueDate; + } + + @CamundaQueryParam(value = "followUpAfter", converter = DateConverter.class) + public void setFollowUpAfter(Date followUpAfter) { + this.followUpAfter = followUpAfter; + } + + @CamundaQueryParam(value = "followUpAfterExpression") + public void setFollowUpAfterExpression(String followUpAfterExpression) { + this.followUpAfterExpression = followUpAfterExpression; + } + + @CamundaQueryParam(value = "followUpBefore", converter = DateConverter.class) + public void setFollowUpBefore(Date followUpBefore) { + this.followUpBefore = followUpBefore; + } + + @CamundaQueryParam(value = "followUpBeforeOrNotExistentExpression") + public void setFollowUpBeforeOrNotExistentExpression(String followUpBeforeExpression) { + this.followUpBeforeOrNotExistentExpression = followUpBeforeExpression; + } + + @CamundaQueryParam(value = "followUpBeforeOrNotExistent", converter = DateConverter.class) + public void setFollowUpBeforeOrNotExistent(Date followUpBefore) { + this.followUpBeforeOrNotExistent = followUpBefore; + } + + @CamundaQueryParam(value = "followUpBeforeExpression") + public void setFollowUpBeforeExpression(String followUpBeforeExpression) { + this.followUpBeforeExpression = followUpBeforeExpression; + } + + @CamundaQueryParam(value = "followUpDate", converter = DateConverter.class) + public void setFollowUpDate(Date followUpDate) { + this.followUpDate = followUpDate; + } + + @Deprecated + @CamundaQueryParam(value = "followUp", converter = DateConverter.class) + public void setFollowUp(Date followUpDate) { + this.followUpDate = followUpDate; + } + + @CamundaQueryParam(value = "followUpDateExpression") + public void setFollowUpDateExpression(String followUpDateExpression) { + this.followUpDateExpression = followUpDateExpression; + } + + @CamundaQueryParam(value = "createdAfter", converter = DateConverter.class) + public void setCreatedAfter(Date createdAfter) { + this.createdAfter = createdAfter; + } + + @CamundaQueryParam(value = "createdAfterExpression") + public void setCreatedAfterExpression(String createdAfterExpression) { + this.createdAfterExpression = createdAfterExpression; + } + + @CamundaQueryParam(value = "createdBefore", converter = DateConverter.class) + public void setCreatedBefore(Date createdBefore) { + this.createdBefore = createdBefore; + } + + @CamundaQueryParam(value = "createdBeforeExpression") + public void setCreatedBeforeExpression(String createdBeforeExpression) { + this.createdBeforeExpression = createdBeforeExpression; + } + + @CamundaQueryParam(value = "createdOn", converter = DateConverter.class) + public void setCreatedOn(Date createdOn) { + this.createdOn = createdOn; + } + + @Deprecated + @CamundaQueryParam(value = "created", converter = DateConverter.class) + public void setCreated(Date createdOn) { + this.createdOn = createdOn; + } + + @CamundaQueryParam(value = "createdOnExpression") + public void setCreatedOnExpression(String createdOnExpression) { + this.createdOnExpression = createdOnExpression; + } + + @CamundaQueryParam(value = "updatedAfter", converter = DateConverter.class) + public void setUpdatedAfter(Date updatedAfter) { + this.updatedAfter = updatedAfter; + } + + @CamundaQueryParam(value = "updatedAfterExpression") + public void setUpdatedAfterExpression(String updatedAfterExpression) { + this.updatedAfterExpression = updatedAfterExpression; + } + + @CamundaQueryParam(value = "delegationState") + public void setDelegationState(String taskDelegationState) { + this.delegationState = taskDelegationState; + } + + @CamundaQueryParam(value = "candidateGroups", converter = StringListConverter.class) + public void setCandidateGroups(List candidateGroups) { + this.candidateGroups = candidateGroups; + } + + @CamundaQueryParam(value = "candidateGroupsExpression") + public void setCandidateGroupsExpression(String candidateGroupsExpression) { + this.candidateGroupsExpression = candidateGroupsExpression; + } + + @CamundaQueryParam(value = "taskVariables", converter = VariableListConverter.class) + public void setTaskVariables(List taskVariables) { + this.taskVariables = taskVariables; + } + + @CamundaQueryParam(value = "processVariables", converter = VariableListConverter.class) + public void setProcessVariables(List processVariables) { + this.processVariables = processVariables; + } + + @CamundaQueryParam("caseDefinitionId") + public void setCaseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + } + + @CamundaQueryParam("caseDefinitionKey") + public void setCaseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + } + + @CamundaQueryParam("caseDefinitionName") + public void setCaseDefinitionName(String caseDefinitionName) { + this.caseDefinitionName = caseDefinitionName; + } + + @CamundaQueryParam("caseDefinitionNameLike") + public void setCaseDefinitionNameLike(String caseDefinitionNameLike) { + this.caseDefinitionNameLike = caseDefinitionNameLike; + } + + @CamundaQueryParam("caseExecutionId") + public void setCaseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + } + + @CamundaQueryParam("caseInstanceBusinessKey") + public void setCaseInstanceBusinessKey(String caseInstanceBusinessKey) { + this.caseInstanceBusinessKey = caseInstanceBusinessKey; + } + + @CamundaQueryParam("caseInstanceBusinessKeyLike") + public void setCaseInstanceBusinessKeyLike(String caseInstanceBusinessKeyLike) { + this.caseInstanceBusinessKeyLike = caseInstanceBusinessKeyLike; + } + + @CamundaQueryParam("caseInstanceId") + public void setCaseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + } + + @CamundaQueryParam(value = "caseInstanceVariables", converter = VariableListConverter.class) + public void setCaseInstanceVariables(List caseInstanceVariables) { + this.caseInstanceVariables = caseInstanceVariables; + } + + @CamundaQueryParam(value = "variableNamesIgnoreCase", converter = BooleanConverter.class) + public void setVariableNamesIgnoreCase(Boolean variableNamesCaseInsensitive) { + this.variableNamesIgnoreCase = variableNamesCaseInsensitive; + } + + @CamundaQueryParam(value ="variableValuesIgnoreCase", converter = BooleanConverter.class) + public void setVariableValuesIgnoreCase(Boolean variableValuesCaseInsensitive) { + this.variableValuesIgnoreCase = variableValuesCaseInsensitive; + } + + @CamundaQueryParam(value = "withCommentAttachmentInfo", converter = BooleanConverter.class) + public void setWithCommentAttachmentInfo(Boolean withCommentAttachmentInfo) { + this.withCommentAttachmentInfo = withCommentAttachmentInfo; + } + + @CamundaQueryParam(value = "withTaskVariablesInReturn", converter = BooleanConverter.class) + public void setWithTaskVariablesInReturn(Boolean withTaskVariablesInReturn) { + this.withTaskVariablesInReturn = withTaskVariablesInReturn; + } + + @CamundaQueryParam(value = "withTaskLocalVariablesInReturn", converter = BooleanConverter.class) + public void setWithTaskLocalVariablesInReturn(Boolean withTaskLocalVariablesInReturn) { + this.withTaskLocalVariablesInReturn = withTaskLocalVariablesInReturn; + } + + @Override + protected boolean isValidSortByValue(String value) { + return VALID_SORT_BY_VALUES.contains(value); + } + + @Override + protected TaskQuery createNewQuery(ProcessEngine engine) { + return engine.getTaskService().createTaskQuery(); + } + + public String getProcessInstanceBusinessKey() { + return processInstanceBusinessKey; + } + + public String getProcessInstanceBusinessKeyExpression() { + return processInstanceBusinessKeyExpression; + } + + public String[] getProcessInstanceBusinessKeyIn() { + return processInstanceBusinessKeyIn; + } + + public String getProcessInstanceBusinessKeyLike() { + return processInstanceBusinessKeyLike; + } + + public String getProcessInstanceBusinessKeyLikeExpression() { + return processInstanceBusinessKeyLikeExpression; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String[] getProcessDefinitionKeyIn() { + return processDefinitionKeyIn; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getExecutionId() { + return executionId; + } + + public String[] getActivityInstanceIdIn() { + return activityInstanceIdIn; + } + + public String[] getTenantIdIn() { + return tenantIdIn; + } + + public Boolean getWithoutTenantId() { + return withoutTenantId; + } + + public String getProcessDefinitionName() { + return processDefinitionName; + } + + public String getProcessDefinitionNameLike() { + return processDefinitionNameLike; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String[] getProcessInstanceIdIn() { + return processInstanceIdIn; + } + + public String getAssignee() { + return assignee; + } + + public String getAssigneeExpression() { + return assigneeExpression; + } + + public String getAssigneeLike() { + return assigneeLike; + } + + public String[] getAssigneeIn() { + return assigneeIn; + } + + public String[] getAssigneeNotIn() { + return assigneeNotIn; + } + + public String getAssigneeLikeExpression() { + return assigneeLikeExpression; + } + + public String getCandidateGroup() { + return candidateGroup; + } + + public String getCandidateGroupExpression() { + return candidateGroupExpression; + } + + public String getCandidateGroupLike() { + return candidateGroupLike; + } + + public String getCandidateUser() { + return candidateUser; + } + + public String getCandidateUserExpression() { + return candidateUserExpression; + } + + public Boolean getIncludeAssignedTasks(){ + return includeAssignedTasks; + } + + public String[] getTaskIdIn() { + return taskIdIn; + } + + public String getTaskId() { + return taskId; + } + + public String[] getTaskDefinitionKeyIn() { + return taskDefinitionKeyIn; + } + + public String[] getTaskDefinitionKeyNotIn() { + return taskDefinitionKeyNotIn; + } + + public String getTaskDefinitionKey() { + return taskDefinitionKey; + } + + public String getTaskDefinitionKeyLike() { + return taskDefinitionKeyLike; + } + + public String getDescription() { + return description; + } + + public String getDescriptionLike() { + return descriptionLike; + } + + public String getInvolvedUser() { + return involvedUser; + } + + public String getInvolvedUserExpression() { + return involvedUserExpression; + } + + public Integer getMaxPriority() { + return maxPriority; + } + + public Integer getMinPriority() { + return minPriority; + } + + public String getName() { + return name; + } + + public String getNameNotEqual() { + return nameNotEqual; + } + + public String getNameLike() { + return nameLike; + } + + public String getNameNotLike() { + return nameNotLike; + } + + public String getOwner() { + return owner; + } + + public String getOwnerExpression() { + return ownerExpression; + } + + public Integer getPriority() { + return priority; + } + + public String getParentTaskId() { + return parentTaskId; + } + + public Boolean getAssigned() { + return assigned; + } + + public Boolean getUnassigned() { + return unassigned; + } + + public Boolean getActive() { + return active; + } + + public Boolean getSuspended() { + return suspended; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseDefinitionName() { + return caseDefinitionName; + } + + public String getCaseDefinitionNameLike() { + return caseDefinitionNameLike; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseInstanceBusinessKey() { + return caseInstanceBusinessKey; + } + + public String getCaseInstanceBusinessKeyLike() { + return caseInstanceBusinessKeyLike; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public Date getDueAfter() { + return dueAfter; + } + + public String getDueAfterExpression() { + return dueAfterExpression; + } + + public Date getDueBefore() { + return dueBefore; + } + + public String getDueBeforeExpression() { + return dueBeforeExpression; + } + + public Date getDueDate() { + return dueDate; + } + + public String getDueDateExpression() { + return dueDateExpression; + } + + public Boolean getWithoutDueDate() { + return withoutDueDate; + } + + public Date getFollowUpAfter() { + return followUpAfter; + } + + public String getFollowUpAfterExpression() { + return followUpAfterExpression; + } + + public Date getFollowUpBefore() { + return followUpBefore; + } + + public String getFollowUpBeforeExpression() { + return followUpBeforeExpression; + } + + public Date getFollowUpBeforeOrNotExistent() { + return followUpBeforeOrNotExistent; + } + + public String getFollowUpBeforeOrNotExistentExpression() { + return followUpBeforeOrNotExistentExpression; + } + + public Date getFollowUpDate() { + return followUpDate; + } + + public String getFollowUpDateExpression() { + return followUpDateExpression; + } + + public Date getCreatedAfter() { + return createdAfter; + } + + public String getCreatedAfterExpression() { + return createdAfterExpression; + } + + public Date getCreatedBefore() { + return createdBefore; + } + + public String getCreatedBeforeExpression() { + return createdBeforeExpression; + } + + public Date getCreatedOn() { + return createdOn; + } + + public String getCreatedOnExpression() { + return createdOnExpression; + } + + public Date getUpdatedAfter() { + return updatedAfter; + } + + public String getUpdatedAfterExpression() { + return updatedAfterExpression; + } + + public String getDelegationState() { + return delegationState; + } + + public List getCandidateGroups() { + return candidateGroups; + } + + public String getCandidateGroupsExpression() { + return candidateGroupsExpression; + } + + public List getTaskVariables() { + return taskVariables; + } + + public List getProcessVariables() { + return processVariables; + } + + public List getCaseInstanceVariables() { + return caseInstanceVariables; + } + + public List getOrQueries() { + return orQueries; + } + + public Boolean isVariableNamesIgnoreCase() { + return variableNamesIgnoreCase; + } + + public Boolean isVariableValuesIgnoreCase() { + return variableValuesIgnoreCase; + } + + public Boolean getWithCommentAttachmentInfo() { return withCommentAttachmentInfo;} + + public Boolean getWithTaskVariablesInReturn() { + return withTaskVariablesInReturn; + } + + public Boolean getWithTaskLocalVariablesInReturn() { + return withTaskLocalVariablesInReturn; + } + + @Override + protected void applyFilters(TaskQuery query) { + if (orQueries != null) { + for (TaskQueryDto orQueryDto: orQueries) { + TaskQueryImpl orQuery = new TaskQueryImpl(); + orQuery.setOrQueryActive(); + orQueryDto.applyFilters(orQuery); + ((TaskQueryImpl) query).addOrQuery(orQuery); + } + } + if (processInstanceBusinessKey != null) { + query.processInstanceBusinessKey(processInstanceBusinessKey); + } + if (processInstanceBusinessKeyExpression != null) { + query.processInstanceBusinessKeyExpression(processInstanceBusinessKeyExpression); + } + if (processInstanceBusinessKeyIn != null && processInstanceBusinessKeyIn.length > 0) { + query.processInstanceBusinessKeyIn(processInstanceBusinessKeyIn); + } + if (processInstanceBusinessKeyLike != null) { + query.processInstanceBusinessKeyLike(processInstanceBusinessKeyLike); + } + if (processInstanceBusinessKeyLikeExpression != null) { + query.processInstanceBusinessKeyLikeExpression(processInstanceBusinessKeyLikeExpression); + } + if (processDefinitionKey != null) { + query.processDefinitionKey(processDefinitionKey); + } + if (processDefinitionKeyIn != null && processDefinitionKeyIn.length > 0) { + query.processDefinitionKeyIn(processDefinitionKeyIn); + } + if (processDefinitionId != null) { + query.processDefinitionId(processDefinitionId); + } + if (executionId != null) { + query.executionId(executionId); + } + if (activityInstanceIdIn != null && activityInstanceIdIn.length > 0) { + query.activityInstanceIdIn(activityInstanceIdIn); + } + if (tenantIdIn != null && tenantIdIn.length > 0) { + query.tenantIdIn(tenantIdIn); + } + if (TRUE.equals(withoutTenantId)) { + query.withoutTenantId(); + } + if (processDefinitionName != null) { + query.processDefinitionName(processDefinitionName); + } + if (processDefinitionNameLike != null) { + query.processDefinitionNameLike(processDefinitionNameLike); + } + if (processInstanceId != null) { + query.processInstanceId(processInstanceId); + } + if (processInstanceIdIn != null && processInstanceIdIn.length > 0) { + query.processInstanceIdIn(processInstanceIdIn); + } + if (assignee != null) { + query.taskAssignee(assignee); + } + if (assigneeExpression != null) { + query.taskAssigneeExpression(assigneeExpression); + } + if (assigneeLike != null) { + query.taskAssigneeLike(assigneeLike); + } + if (assigneeLikeExpression != null) { + query.taskAssigneeLikeExpression(assigneeLikeExpression); + } + if (assigneeIn != null && assigneeIn.length > 0) { + query.taskAssigneeIn(assigneeIn); + } + if (assigneeNotIn != null && assigneeNotIn.length > 0) { + query.taskAssigneeNotIn(assigneeNotIn); + } + if (candidateGroup != null) { + query.taskCandidateGroup(candidateGroup); + } + if (candidateGroupExpression != null) { + query.taskCandidateGroupExpression(candidateGroupExpression); + } + if (candidateGroupLike != null) { + query.taskCandidateGroupLike(candidateGroupLike); + } + if (withCandidateGroups != null && withCandidateGroups) { + query.withCandidateGroups(); + } + if (withoutCandidateGroups != null && withoutCandidateGroups) { + query.withoutCandidateGroups(); + } + if (withCandidateUsers != null && withCandidateUsers) { + query.withCandidateUsers(); + } + if (withoutCandidateUsers != null && withoutCandidateUsers) { + query.withoutCandidateUsers(); + } + if (candidateUser != null) { + query.taskCandidateUser(candidateUser); + } + if (candidateUserExpression != null) { + query.taskCandidateUserExpression(candidateUserExpression); + } + if (taskIdIn != null && taskIdIn.length > 0) { + query.taskIdIn(taskIdIn); + } + if (taskId != null) { + query.taskId(taskId); + } + if (taskDefinitionKeyIn != null && taskDefinitionKeyIn.length > 0) { + query.taskDefinitionKeyIn(taskDefinitionKeyIn); + } + if (taskDefinitionKeyNotIn != null && taskDefinitionKeyNotIn.length > 0) { + query.taskDefinitionKeyNotIn(taskDefinitionKeyNotIn); + } + if (taskDefinitionKey != null) { + query.taskDefinitionKey(taskDefinitionKey); + } + if (taskDefinitionKeyLike != null) { + query.taskDefinitionKeyLike(taskDefinitionKeyLike); + } + if (description != null) { + query.taskDescription(description); + } + if (descriptionLike != null) { + query.taskDescriptionLike(descriptionLike); + } + if (involvedUser != null) { + query.taskInvolvedUser(involvedUser); + } + if (involvedUserExpression != null) { + query.taskInvolvedUserExpression(involvedUserExpression); + } + if (maxPriority != null) { + query.taskMaxPriority(maxPriority); + } + if (minPriority != null) { + query.taskMinPriority(minPriority); + } + if (name != null) { + query.taskName(name); + } + if (nameNotEqual != null) { + query.taskNameNotEqual(nameNotEqual); + } + if (nameLike != null) { + query.taskNameLike(nameLike); + } + if (nameNotLike != null) { + query.taskNameNotLike(nameNotLike); + } + if (owner != null) { + query.taskOwner(owner); + } + if (ownerExpression != null) { + query.taskOwnerExpression(ownerExpression); + } + if (priority != null) { + query.taskPriority(priority); + } + if (parentTaskId != null) { + query.taskParentTaskId(parentTaskId); + } + if (assigned != null && assigned) { + query.taskAssigned(); + } + if (unassigned != null && unassigned) { + query.taskUnassigned(); + } + if (dueAfter != null) { + query.dueAfter(dueAfter); + } + if (dueAfterExpression != null) { + query.dueAfterExpression(dueAfterExpression); + } + if (dueBefore != null) { + query.dueBefore(dueBefore); + } + if (dueBeforeExpression != null) { + query.dueBeforeExpression(dueBeforeExpression); + } + if (dueDate != null) { + query.dueDate(dueDate); + } + if (dueDateExpression != null) { + query.dueDateExpression(dueDateExpression); + } + if (TRUE.equals(withoutDueDate)) { + query.withoutDueDate(); + } + if (followUpAfter != null) { + query.followUpAfter(followUpAfter); + } + if (followUpAfterExpression != null) { + query.followUpAfterExpression(followUpAfterExpression); + } + if (followUpBefore != null) { + query.followUpBefore(followUpBefore); + } + if (followUpBeforeExpression != null) { + query.followUpBeforeExpression(followUpBeforeExpression); + } + if (followUpBeforeOrNotExistent != null) { + query.followUpBeforeOrNotExistent(followUpBeforeOrNotExistent); + } + if (followUpBeforeOrNotExistentExpression != null) { + query.followUpBeforeOrNotExistentExpression(followUpBeforeOrNotExistentExpression); + } + if (followUpDate != null) { + query.followUpDate(followUpDate); + } + if (followUpDateExpression != null) { + query.followUpDateExpression(followUpDateExpression); + } + if (createdAfter != null) { + query.taskCreatedAfter(createdAfter); + } + if (createdAfterExpression != null) { + query.taskCreatedAfterExpression(createdAfterExpression); + } + if (createdBefore != null) { + query.taskCreatedBefore(createdBefore); + } + if (createdBeforeExpression != null) { + query.taskCreatedBeforeExpression(createdBeforeExpression); + } + if (createdOn != null) { + query.taskCreatedOn(createdOn); + } + if (createdOnExpression != null) { + query.taskCreatedOnExpression(createdOnExpression); + } + if (updatedAfter != null) { + query.taskUpdatedAfter(updatedAfter); + } + if (updatedAfterExpression != null) { + query.taskUpdatedAfterExpression(updatedAfterExpression); + } + if (delegationState != null) { + DelegationStateConverter converter = new DelegationStateConverter(); + DelegationState state = converter.convertQueryParameterToType(delegationState); + query.taskDelegationState(state); + } + if (candidateGroups != null) { + query.taskCandidateGroupIn(candidateGroups); + } + if (candidateGroupsExpression != null) { + query.taskCandidateGroupInExpression(candidateGroupsExpression); + } + if (includeAssignedTasks != null && includeAssignedTasks){ + query.includeAssignedTasks(); + } + if (active != null && active) { + query.active(); + } + if (suspended != null && suspended) { + query.suspended(); + } + if (caseDefinitionId != null) { + query.caseDefinitionId(caseDefinitionId); + } + if (caseDefinitionKey != null) { + query.caseDefinitionKey(caseDefinitionKey); + } + if (caseDefinitionName != null) { + query.caseDefinitionName(caseDefinitionName); + } + if (caseDefinitionNameLike != null) { + query.caseDefinitionNameLike(caseDefinitionNameLike); + } + if (caseExecutionId != null) { + query.caseExecutionId(caseExecutionId); + } + if (caseInstanceBusinessKey != null) { + query.caseInstanceBusinessKey(caseInstanceBusinessKey); + } + if (caseInstanceBusinessKeyLike != null) { + query.caseInstanceBusinessKeyLike(caseInstanceBusinessKeyLike); + } + if (caseInstanceId != null) { + query.caseInstanceId(caseInstanceId); + } + if(variableValuesIgnoreCase != null && variableValuesIgnoreCase) { + query.matchVariableValuesIgnoreCase(); + } + if(variableNamesIgnoreCase != null && variableNamesIgnoreCase) { + query.matchVariableNamesIgnoreCase(); + } + + if (taskVariables != null) { + for (VariableQueryParameterDto variableQueryParam : taskVariables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.taskVariableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.taskVariableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.taskVariableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.taskVariableValueGreaterThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.taskVariableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.taskVariableValueLessThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.taskVariableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid task variable comparator specified: " + op); + } + + } + } + + if (processVariables != null) { + for (VariableQueryParameterDto variableQueryParam : processVariables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.processVariableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.processVariableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.processVariableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.processVariableValueGreaterThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.processVariableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.processVariableValueLessThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.processVariableValueLike(variableName, String.valueOf(variableValue)); + } else if (op.equals(VariableQueryParameterDto.NOT_LIKE_OPERATOR_NAME)) { + query.processVariableValueNotLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid process variable comparator specified: " + op); + } + + } + } + + if (caseInstanceVariables != null) { + for (VariableQueryParameterDto variableQueryParam : caseInstanceVariables) { + String variableName = variableQueryParam.getName(); + String op = variableQueryParam.getOperator(); + Object variableValue = variableQueryParam.resolveValue(objectMapper); + + if (op.equals(VariableQueryParameterDto.EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.NOT_EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueNotEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OPERATOR_NAME)) { + query.caseInstanceVariableValueGreaterThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.GREATER_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueGreaterThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OPERATOR_NAME)) { + query.caseInstanceVariableValueLessThan(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LESS_THAN_OR_EQUALS_OPERATOR_NAME)) { + query.caseInstanceVariableValueLessThanOrEquals(variableName, variableValue); + } else if (op.equals(VariableQueryParameterDto.LIKE_OPERATOR_NAME)) { + query.caseInstanceVariableValueLike(variableName, String.valueOf(variableValue)); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Invalid case variable comparator specified: " + op); + } + } + } + if (withCommentAttachmentInfo != null && withCommentAttachmentInfo) { + query.withCommentAttachmentInfo(); + } + } + + @Override + protected void applySortBy(TaskQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID_VALUE)) { + query.orderByProcessInstanceId(); + } else if (sortBy.equals(SORT_BY_CASE_INSTANCE_ID_VALUE)) { + query.orderByCaseInstanceId(); + } else if (sortBy.equals(SORT_BY_DUE_DATE_VALUE)) { + query.orderByDueDate(); + } else if (sortBy.equals(SORT_BY_FOLLOW_UP_VALUE)) { + query.orderByFollowUpDate(); + } else if (sortBy.equals(SORT_BY_EXECUTION_ID_VALUE)) { + query.orderByExecutionId(); + } else if (sortBy.equals(SORT_BY_CASE_EXECUTION_ID_VALUE)) { + query.orderByCaseExecutionId(); + } else if (sortBy.equals(SORT_BY_ASSIGNEE_VALUE)) { + query.orderByTaskAssignee(); + } else if (sortBy.equals(SORT_BY_CREATE_TIME_VALUE)) { + query.orderByTaskCreateTime(); + } else if (sortBy.equals(SORT_BY_LAST_UPDATED_VALUE)) { + query.orderByLastUpdated(); + } else if (sortBy.equals(SORT_BY_DESCRIPTION_VALUE)) { + query.orderByTaskDescription(); + } else if (sortBy.equals(SORT_BY_ID_VALUE)) { + query.orderByTaskId(); + } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { + query.orderByTaskName(); + } else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { + query.orderByTenantId(); + } else if (sortBy.equals(SORT_BY_NAME_CASE_INSENSITIVE_VALUE)) { + query.orderByTaskNameCaseInsensitive(); + } else if (sortBy.equals(SORT_BY_PRIORITY_VALUE)) { + query.orderByTaskPriority(); + + } else if (sortBy.equals(SORT_BY_PROCESS_VARIABLE)) { + String variableName = getVariableName(parameters); + String valueTypeName = getValueTypeName(parameters); + query.orderByProcessVariable(variableName, getValueTypeByName(valueTypeName, engine)); + + } else if (sortBy.equals(SORT_BY_EXECUTION_VARIABLE)) { + String variableName = getVariableName(parameters); + String valueTypeName = getValueTypeName(parameters); + query.orderByExecutionVariable(variableName, getValueTypeByName(valueTypeName, engine)); + + } else if (sortBy.equals(SORT_BY_TASK_VARIABLE)) { + String variableName = getVariableName(parameters); + String valueTypeName = getValueTypeName(parameters); + query.orderByTaskVariable(variableName, getValueTypeByName(valueTypeName, engine)); + + } else if (sortBy.equals(SORT_BY_CASE_INSTANCE_VARIABLE)) { + String variableName = getVariableName(parameters); + String valueTypeName = getValueTypeName(parameters); + query.orderByCaseInstanceVariable(variableName, getValueTypeByName(valueTypeName, engine)); + + } else if (sortBy.equals(SORT_BY_CASE_EXECUTION_VARIABLE)) { + String variableName = getVariableName(parameters); + String valueTypeName = getValueTypeName(parameters); + query.orderByCaseExecutionVariable(variableName, getValueTypeByName(valueTypeName, engine)); + } + } + + protected String getValueTypeName(Map parameters) { + String valueTypeName = (String) getValue(parameters, SORT_PARAMETERS_VALUE_TYPE); + if (valueTypeName != null) { + valueTypeName = VariableValueDto.fromRestApiTypeName(valueTypeName); + } + return valueTypeName; + } + + protected String getVariableName(Map parameters) { + return (String) getValue(parameters, SORT_PARAMETERS_VARIABLE_NAME); + } + + protected Object getValue(Map map, String key) { + if (map != null) { + return map.get(key); + } + return null; + } + + protected ValueType getValueTypeByName(String name, ProcessEngine engine) { + ValueTypeResolver valueTypeResolver = engine.getProcessEngineConfiguration().getValueTypeResolver(); + return valueTypeResolver.typeForName(name); + } + + public static TaskQueryDto fromQuery(Query query) { + return fromQuery(query, false); + } + + public static TaskQueryDto fromQuery(Query query, boolean isOrQueryActive) { + TaskQueryImpl taskQuery = (TaskQueryImpl) query; + + TaskQueryDto dto = new TaskQueryDto(); + + if (!isOrQueryActive) { + dto.orQueries = new ArrayList<>(); + for (TaskQueryImpl orQuery: taskQuery.getQueries()) { + if (orQuery.isOrQueryActive()) { + dto.orQueries.add(fromQuery(orQuery, true)); + } + } + } + + dto.activityInstanceIdIn = taskQuery.getActivityInstanceIdIn(); + dto.caseDefinitionId = taskQuery.getCaseDefinitionId(); + dto.caseDefinitionKey = taskQuery.getCaseDefinitionKey(); + dto.caseDefinitionName = taskQuery.getCaseDefinitionName(); + dto.caseDefinitionNameLike = taskQuery.getCaseDefinitionNameLike(); + dto.caseExecutionId = taskQuery.getCaseExecutionId(); + dto.caseInstanceBusinessKey = taskQuery.getCaseInstanceBusinessKey(); + dto.caseInstanceBusinessKeyLike = taskQuery.getCaseInstanceBusinessKeyLike(); + dto.caseInstanceId = taskQuery.getCaseInstanceId(); + + dto.candidateUser = taskQuery.getCandidateUser(); + dto.candidateGroup = taskQuery.getCandidateGroup(); + dto.candidateGroupLike = taskQuery.getCandidateGroupLike(); + dto.candidateGroups = taskQuery.getCandidateGroupsInternal(); + dto.includeAssignedTasks = taskQuery.isIncludeAssignedTasksInternal(); + dto.withCandidateGroups = taskQuery.isWithCandidateGroups(); + dto.withoutCandidateGroups = taskQuery.isWithoutCandidateGroups(); + dto.withCandidateUsers = taskQuery.isWithCandidateUsers(); + dto.withoutCandidateUsers = taskQuery.isWithoutCandidateUsers(); + + dto.processInstanceBusinessKey = taskQuery.getProcessInstanceBusinessKey(); + dto.processInstanceBusinessKeyLike = taskQuery.getProcessInstanceBusinessKeyLike(); + dto.processDefinitionKey = taskQuery.getProcessDefinitionKey(); + dto.processDefinitionKeyIn = taskQuery.getProcessDefinitionKeys(); + dto.processDefinitionId = taskQuery.getProcessDefinitionId(); + dto.executionId = taskQuery.getExecutionId(); + + dto.processDefinitionName = taskQuery.getProcessDefinitionName(); + dto.processDefinitionNameLike = taskQuery.getProcessDefinitionNameLike(); + dto.processInstanceId = taskQuery.getProcessInstanceId(); + if(taskQuery.getProcessInstanceIdIn() != null) { + dto.processInstanceIdIn = taskQuery.getProcessInstanceIdIn(); + } + + dto.assignee = taskQuery.getAssignee(); + + if (taskQuery.getAssigneeIn() != null) { + dto.assigneeIn = taskQuery.getAssigneeIn() + .toArray(new String[taskQuery.getAssigneeIn().size()]); + } + + dto.assigneeLike = taskQuery.getAssigneeLike(); + dto.taskDefinitionKey = taskQuery.getKey(); + dto.taskDefinitionKeyIn = taskQuery.getKeys(); + dto.taskDefinitionKeyNotIn = taskQuery.getKeyNotIn(); + dto.taskDefinitionKeyLike = taskQuery.getKeyLike(); + dto.description = taskQuery.getDescription(); + dto.descriptionLike = taskQuery.getDescriptionLike(); + dto.involvedUser = taskQuery.getInvolvedUser(); + dto.maxPriority = taskQuery.getMaxPriority(); + dto.minPriority = taskQuery.getMinPriority(); + dto.name = taskQuery.getName(); + dto.nameNotEqual = taskQuery.getNameNotEqual(); + dto.nameLike = taskQuery.getNameLike(); + dto.nameNotLike = taskQuery.getNameNotLike(); + dto.owner = taskQuery.getOwner(); + dto.priority = taskQuery.getPriority(); + dto.assigned = taskQuery.isAssignedInternal(); + dto.unassigned = taskQuery.isUnassignedInternal(); + dto.parentTaskId = taskQuery.getParentTaskId(); + + dto.dueAfter = taskQuery.getDueAfter(); + dto.dueBefore = taskQuery.getDueBefore(); + dto.dueDate = taskQuery.getDueDate(); + if (taskQuery.isWithoutDueDate()) { + dto.withoutDueDate = taskQuery.isWithoutDueDate(); + } + + dto.followUpAfter = taskQuery.getFollowUpAfter(); + + dto.variableNamesIgnoreCase = taskQuery.isVariableNamesIgnoreCase(); + dto.variableValuesIgnoreCase = taskQuery.isVariableValuesIgnoreCase(); + + if (taskQuery.isFollowUpNullAccepted()) { + dto.followUpBeforeOrNotExistent = taskQuery.getFollowUpBefore(); + } else { + dto.followUpBefore = taskQuery.getFollowUpBefore(); + } + dto.followUpDate = taskQuery.getFollowUpDate(); + dto.createdAfter = taskQuery.getCreateTimeAfter(); + dto.createdBefore = taskQuery.getCreateTimeBefore(); + dto.createdOn = taskQuery.getCreateTime(); + + dto.updatedAfter = taskQuery.getUpdatedAfter(); + + if (taskQuery.getDelegationState() != null) { + dto.delegationState = taskQuery.getDelegationState().toString(); + } + + if (taskQuery.isWithoutTenantId()) { + if (taskQuery.getTenantIds() != null) { + dto.tenantIdIn = taskQuery.getTenantIds(); + } else { + dto.withoutTenantId = true; + } + } + + dto.processVariables = new ArrayList<>(); + dto.taskVariables = new ArrayList<>(); + dto.caseInstanceVariables = new ArrayList<>(); + for (TaskQueryVariableValue variableValue : taskQuery.getVariables()) { + VariableQueryParameterDto variableValueDto = new VariableQueryParameterDto(variableValue); + + if (variableValue.isProcessInstanceVariable()) { + dto.processVariables.add(variableValueDto); + } else if (variableValue.isLocal()) { + dto.taskVariables.add(variableValueDto); + } else { + dto.caseInstanceVariables.add(variableValueDto); + } + } + + if (taskQuery.getSuspensionState() == SuspensionState.ACTIVE) { + dto.active = true; + } + if (taskQuery.getSuspensionState() == SuspensionState.SUSPENDED) { + dto.suspended = true; + } + + // sorting + List orderingProperties = taskQuery.getOrderingProperties(); + if (!orderingProperties.isEmpty()) { + dto.setSorting(convertQueryOrderingPropertiesToSortingDtos(orderingProperties)); + } + + // expressions + Map expressions = taskQuery.getExpressions(); + if (expressions.containsKey("taskAssignee")) { + dto.setAssigneeExpression(expressions.get("taskAssignee")); + } + if (expressions.containsKey("taskAssigneeLike")) { + dto.setAssigneeLikeExpression(expressions.get("taskAssigneeLike")); + } + if (expressions.containsKey("taskOwner")) { + dto.setOwnerExpression(expressions.get("taskOwner")); + } + if (expressions.containsKey("taskCandidateUser")) { + dto.setCandidateUserExpression(expressions.get("taskCandidateUser")); + } + if (expressions.containsKey("taskInvolvedUser")) { + dto.setInvolvedUserExpression(expressions.get("taskInvolvedUser")); + } + if (expressions.containsKey("taskCandidateGroup")) { + dto.setCandidateGroupExpression(expressions.get("taskCandidateGroup")); + } + if (expressions.containsKey("taskCandidateGroupIn")) { + dto.setCandidateGroupsExpression(expressions.get("taskCandidateGroupIn")); + } + if (expressions.containsKey("taskCreatedOn")) { + dto.setCreatedOnExpression(expressions.get("taskCreatedOn")); + } + if (expressions.containsKey("taskCreatedBefore")) { + dto.setCreatedBeforeExpression(expressions.get("taskCreatedBefore")); + } + if (expressions.containsKey("taskCreatedAfter")) { + dto.setCreatedAfterExpression(expressions.get("taskCreatedAfter")); + } + if (expressions.containsKey("taskUpdatedAfter")) { + dto.setUpdatedAfterExpression(expressions.get("taskUpdatedAfter")); + } + if (expressions.containsKey("dueDate")) { + dto.setDueDateExpression(expressions.get("dueDate")); + } + if (expressions.containsKey("dueBefore")) { + dto.setDueBeforeExpression(expressions.get("dueBefore")); + } + if (expressions.containsKey("dueAfter")) { + dto.setDueAfterExpression(expressions.get("dueAfter")); + } + if (expressions.containsKey("followUpDate")) { + dto.setFollowUpDateExpression(expressions.get("followUpDate")); + } + if (expressions.containsKey("followUpBefore")) { + dto.setFollowUpBeforeExpression(expressions.get("followUpBefore")); + } + if (expressions.containsKey("followUpBeforeOrNotExistent")) { + dto.setFollowUpBeforeOrNotExistentExpression(expressions.get("followUpBeforeOrNotExistent")); + } + if (expressions.containsKey("followUpAfter")) { + dto.setFollowUpAfterExpression(expressions.get("followUpAfter")); + } + if (expressions.containsKey("processInstanceBusinessKey")) { + dto.setProcessInstanceBusinessKeyExpression(expressions.get("processInstanceBusinessKey")); + } + if (expressions.containsKey("processInstanceBusinessKeyLike")) { + dto.setProcessInstanceBusinessKeyLikeExpression(expressions.get("processInstanceBusinessKeyLike")); + } + + return dto; + } + + public static List convertQueryOrderingPropertiesToSortingDtos(List orderingProperties) { + List sortingDtos = new ArrayList<>(); + for (QueryOrderingProperty orderingProperty : orderingProperties) { + SortingDto sortingDto; + if (orderingProperty instanceof VariableOrderProperty) { + sortingDto = convertVariableOrderPropertyToSortingDto((VariableOrderProperty) orderingProperty); + } + else { + sortingDto = convertQueryOrderingPropertyToSortingDto(orderingProperty); + } + sortingDtos.add(sortingDto); + } + return sortingDtos; + } + + public static SortingDto convertVariableOrderPropertyToSortingDto(VariableOrderProperty variableOrderProperty) { + SortingDto sortingDto = new SortingDto(); + sortingDto.setSortBy(sortByValueForVariableOrderProperty(variableOrderProperty)); + sortingDto.setSortOrder(sortOrderValueForDirection(variableOrderProperty.getDirection())); + sortingDto.setParameters(sortParametersForVariableOrderProperty(variableOrderProperty)); + return sortingDto; + } + + public static SortingDto convertQueryOrderingPropertyToSortingDto(QueryOrderingProperty orderingProperty) { + SortingDto sortingDto = new SortingDto(); + sortingDto.setSortBy(sortByValueForQueryProperty(orderingProperty.getQueryProperty())); + sortingDto.setSortOrder(sortOrderValueForDirection(orderingProperty.getDirection())); + return sortingDto; + } + + public static String sortByValueForQueryProperty(QueryProperty queryProperty) { + if (TaskQueryProperty.ASSIGNEE.equals(queryProperty)) { + return SORT_BY_ASSIGNEE_VALUE; + } + else if (TaskQueryProperty.CASE_EXECUTION_ID.equals(queryProperty)) { + return SORT_BY_CASE_EXECUTION_ID_VALUE; + } + else if (TaskQueryProperty.CASE_INSTANCE_ID.equals(queryProperty)) { + return SORT_BY_CASE_INSTANCE_ID_VALUE; + } + else if (TaskQueryProperty.CREATE_TIME.equals(queryProperty)) { + return SORT_BY_CREATE_TIME_VALUE; + } + else if (TaskQueryProperty.LAST_UPDATED.equals(queryProperty)) { + return SORT_BY_LAST_UPDATED_VALUE; + } + else if (TaskQueryProperty.DESCRIPTION.equals(queryProperty)) { + return SORT_BY_DESCRIPTION_VALUE; + } + else if (TaskQueryProperty.DUE_DATE.equals(queryProperty)) { + return SORT_BY_DUE_DATE_VALUE; + } + else if (TaskQueryProperty.EXECUTION_ID.equals(queryProperty)) { + return SORT_BY_EXECUTION_ID_VALUE; + } + else if (TaskQueryProperty.FOLLOW_UP_DATE.equals(queryProperty)) { + return SORT_BY_FOLLOW_UP_VALUE; + } + else if (TaskQueryProperty.NAME.equals(queryProperty)) { + return SORT_BY_NAME_VALUE; + } + else if (TaskQueryProperty.NAME_CASE_INSENSITIVE.equals(queryProperty)) { + return SORT_BY_NAME_CASE_INSENSITIVE_VALUE; + } + else if (TaskQueryProperty.PRIORITY.equals(queryProperty)) { + return SORT_BY_PRIORITY_VALUE; + } + else if (TaskQueryProperty.PROCESS_INSTANCE_ID.equals(queryProperty)) { + return SORT_BY_PROCESS_INSTANCE_ID_VALUE; + } + else if (TaskQueryProperty.TASK_ID.equals(queryProperty)) { + return SORT_BY_ID_VALUE; + } + else if (TaskQueryProperty.TENANT_ID.equals(queryProperty)) { + return SORT_BY_TENANT_ID_VALUE; + } + else { + throw new RestException("Unknown query property for task query " + queryProperty); + } + } + + public static String sortByValueForVariableOrderProperty(VariableOrderProperty variableOrderProperty) { + for (QueryEntityRelationCondition relationCondition : variableOrderProperty.getRelationConditions()) { + if (relationCondition.isPropertyComparison()) { + return sortByValueForQueryEntityRelationCondition(relationCondition); + } + } + + // if no property comparison was found throw an exception + throw new RestException("Unknown variable order property for task query " + variableOrderProperty); + } + + public static String sortByValueForQueryEntityRelationCondition(QueryEntityRelationCondition relationCondition) { + QueryProperty property = relationCondition.getProperty(); + QueryProperty comparisonProperty = relationCondition.getComparisonProperty(); + if (VariableInstanceQueryProperty.EXECUTION_ID.equals(property) && TaskQueryProperty.PROCESS_INSTANCE_ID.equals(comparisonProperty)) { + return SORT_BY_PROCESS_VARIABLE; + } + else if (VariableInstanceQueryProperty.EXECUTION_ID.equals(property) && TaskQueryProperty.EXECUTION_ID.equals(comparisonProperty)) { + return SORT_BY_EXECUTION_VARIABLE; + } + else if (VariableInstanceQueryProperty.TASK_ID.equals(property) && TaskQueryProperty.TASK_ID.equals(comparisonProperty)) { + return SORT_BY_TASK_VARIABLE; + } + else if (VariableInstanceQueryProperty.CASE_EXECUTION_ID.equals(property) && TaskQueryProperty.CASE_INSTANCE_ID.equals(comparisonProperty)) { + return SORT_BY_CASE_INSTANCE_VARIABLE; + } + else if (VariableInstanceQueryProperty.CASE_EXECUTION_ID.equals(property) && TaskQueryProperty.CASE_EXECUTION_ID.equals(comparisonProperty)) { + return SORT_BY_CASE_EXECUTION_VARIABLE; + } + else { + throw new RestException("Unknown relation condition for task query with query property " + property + " and comparison property " + comparisonProperty); + } + } + + public static Map sortParametersForVariableOrderProperty(VariableOrderProperty variableOrderProperty) { + Map parameters = new HashMap<>(); + for (QueryEntityRelationCondition relationCondition : variableOrderProperty.getRelationConditions()) { + QueryProperty property = relationCondition.getProperty(); + if (VariableInstanceQueryProperty.VARIABLE_NAME.equals(property)) { + parameters.put(SORT_PARAMETERS_VARIABLE_NAME, relationCondition.getScalarValue()); + } + else if (VariableInstanceQueryProperty.VARIABLE_TYPE.equals(property)) { + String type = VariableValueDto.toRestApiTypeName((String) relationCondition.getScalarValue()); + parameters.put(SORT_PARAMETERS_VALUE_TYPE, type); + } + } + return parameters; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskWithAttachmentAndCommentDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskWithAttachmentAndCommentDto.java new file mode 100644 index 0000000000000000000000000000000000000000..76dbdc5aa7d4792fdac23078ca74e9e7108f8c2b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskWithAttachmentAndCommentDto.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import java.util.Map; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.task.Task; + +public class TaskWithAttachmentAndCommentDto extends TaskWithVariablesDto { + + private boolean hasAttachment; + private boolean hasComment; + + public TaskWithAttachmentAndCommentDto() { + } + + public TaskWithAttachmentAndCommentDto(Task task, Map variables) { + super(task, variables); + } + + public TaskWithAttachmentAndCommentDto(Task task) { + super(task); + } + public boolean getAttachment() { + return hasAttachment; + } + public void setAttachment(boolean hasAttachment) { + this.hasAttachment = hasAttachment; + } + + public boolean getComment() { + return hasComment; + } + + public void setComment(boolean hasComment) { + this.hasComment = hasComment; + } + + public static TaskDto fromEntity(Task task, Map variables) { + TaskWithAttachmentAndCommentDto result = new TaskWithAttachmentAndCommentDto(task, variables); + result.hasAttachment = task.hasAttachment(); + result.hasComment = task.hasComment(); + return result; + } + + public static TaskDto fromEntity(Task task) { + return fromEntity(task, null); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskWithVariablesDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskWithVariablesDto.java new file mode 100644 index 0000000000000000000000000000000000000000..d2f7d790290c67dbdd8ccc3a53aac0c69739266e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/TaskWithVariablesDto.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.Map; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.task.Task; + +public class TaskWithVariablesDto extends TaskDto { + @JsonInclude(JsonInclude.Include.NON_DEFAULT) + private Map variables; + + public TaskWithVariablesDto() { + } + + public TaskWithVariablesDto(Task task, Map variables) { + super(task); + this.variables = variables; + } + + public TaskWithVariablesDto(Task task) { + super(task); + } + + public Map getVariables() { + return variables; + } + + public void setVariables(Map variables) { + this.variables = variables; + } + + public static TaskDto fromEntity(Task task, Map variables) { + TaskWithVariablesDto result = new TaskWithVariablesDto(task); + result.setVariables(variables); + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/UserDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/UserDto.java new file mode 100644 index 0000000000000000000000000000000000000000..5588f5e49364249f698ba24bde3d000643f7ab22 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/UserDto.java @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +/** + * @author: drobisch + */ +public class UserDto { + private String firstName; + private String lastName; + private String displayName; + + private String id; + + public UserDto(String id, String firstName, String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + + if (firstName == null && lastName == null) { + this.displayName = id; + }else { + this.displayName = (lastName != null) ? firstName + " " + lastName : firstName; + } + } + + public String getFirstName() { + return firstName; + } + + public String getId() { + return id; + } + + public String getLastName() { + return lastName; + } + + public String getDisplayName() { + return displayName; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + UserDto userDto = (UserDto) o; + + if (firstName != null ? !firstName.equals(userDto.firstName) : userDto.firstName != null) return false; + if (id != null ? !id.equals(userDto.id) : userDto.id != null) return false; + if (lastName != null ? !lastName.equals(userDto.lastName) : userDto.lastName != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = firstName != null ? firstName.hashCode() : 0; + result = 31 * result + (lastName != null ? lastName.hashCode() : 0); + result = 31 * result + (id != null ? id.hashCode() : 0); + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/UserIdDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/UserIdDto.java new file mode 100644 index 0000000000000000000000000000000000000000..440cc67fc20a0ecff54a6ec2b92ed5ff4669b2ac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/task/UserIdDto.java @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.task; + +public class UserIdDto { + + private String userId; + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/ApplicationServerDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/ApplicationServerDto.java new file mode 100644 index 0000000000000000000000000000000000000000..06253f6a717a680fa4e31d5c6f6b6e0a65d7f629 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/ApplicationServerDto.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +import static org.camunda.bpm.engine.impl.util.ParseUtil.parseServerVendor; + +import org.camunda.bpm.engine.telemetry.ApplicationServer; + +public class ApplicationServerDto { + + protected String vendor; + protected String version; + + public ApplicationServerDto(String vendor, String version) { + this.vendor = vendor; + this.version = version; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public static ApplicationServerDto fromEngineDto(ApplicationServer other) { + return new ApplicationServerDto( + other.getVendor(), + other.getVersion()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/CommandDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/CommandDto.java new file mode 100644 index 0000000000000000000000000000000000000000..4dfd1c03391607ac413ed712cfafae47973eca5f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/CommandDto.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +public class CommandDto { + + protected long count; + + public CommandDto(long count) { + this.count = count; + } + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/DatabaseDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/DatabaseDto.java new file mode 100644 index 0000000000000000000000000000000000000000..acfeda78a566370eb2f01c0dfe18ca48e5a0c4a9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/DatabaseDto.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +import org.camunda.bpm.engine.telemetry.Database; + +public class DatabaseDto { + + protected String vendor; + protected String version; + + public DatabaseDto(String vendor, String version) { + this.vendor = vendor; + this.version = version; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public static DatabaseDto fromEngineDto(Database other) { + return new DatabaseDto( + other.getVendor(), + other.getVersion()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/InternalsDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/InternalsDto.java new file mode 100644 index 0000000000000000000000000000000000000000..21e747aec03dcc06fc550891c9ae1050c0721432 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/InternalsDto.java @@ -0,0 +1,156 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.camunda.bpm.engine.telemetry.Internals; +import org.camunda.bpm.engine.telemetry.LicenseKeyData; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class InternalsDto { + + public static final String SERIALIZED_APPLICATION_SERVER = "application-server"; + public static final String SERIALIZED_CAMUNDA_INTEGRATION = "camunda-integration"; + public static final String SERIALIZED_LICENSE_KEY = "license-key"; + public static final String SERIALIZED_TELEMETRY_DATA_COLLECTION_START_DATE = "data-collection-start-date"; + + protected DatabaseDto database; + @JsonProperty(value = SERIALIZED_APPLICATION_SERVER) + protected ApplicationServerDto applicationServer; + @JsonProperty(value = SERIALIZED_LICENSE_KEY) + protected LicenseKeyDataDto licenseKey; + @JsonProperty(value = SERIALIZED_CAMUNDA_INTEGRATION) + protected Set camundaIntegration; + @JsonProperty(value = SERIALIZED_TELEMETRY_DATA_COLLECTION_START_DATE) + protected Date dataCollectionStartDate; + protected Map commands; + protected Map metrics; + protected Set webapps; + + protected JdkDto jdk; + + public InternalsDto(DatabaseDto database, ApplicationServerDto server, LicenseKeyDataDto licenseKey, JdkDto jdk) { + this.database = database; + this.applicationServer = server; + this.licenseKey = licenseKey; + this.commands = new HashMap<>(); + this.jdk = jdk; + this.camundaIntegration = new HashSet<>(); + } + + public DatabaseDto getDatabase() { + return database; + } + + public void setDatabase(DatabaseDto database) { + this.database = database; + } + + public ApplicationServerDto getApplicationServer() { + return applicationServer; + } + + public void setApplicationServer(ApplicationServerDto applicationServer) { + this.applicationServer = applicationServer; + } + + public Map getCommands() { + return commands; + } + + public void setCommands(Map commands) { + this.commands = commands; + } + + public Map getMetrics() { + return metrics; + } + + public void setMetrics(Map metrics) { + this.metrics = metrics; + } + + public JdkDto getJdk() { + return jdk; + } + + public void setJdk(JdkDto jdk) { + this.jdk = jdk; + } + + public Set getCamundaIntegration() { + return camundaIntegration; + } + + public void setCamundaIntegration(Set camundaIntegration) { + this.camundaIntegration = camundaIntegration; + } + + public LicenseKeyDataDto getLicenseKey() { + return licenseKey; + } + + public void setLicenseKey(LicenseKeyDataDto licenseKey) { + this.licenseKey = licenseKey; + } + + public Set getWebapps() { + return webapps; + } + + public void setWebapps(Set webapps) { + this.webapps = webapps; + } + + public Date getDataCollectionStartDate() { + return dataCollectionStartDate; + } + + public void setDataCollectionStartDate(Date dataCollectionStartDate) { + this.dataCollectionStartDate = dataCollectionStartDate; + } + + public static InternalsDto fromEngineDto(Internals other) { + + LicenseKeyData licenseKey = other.getLicenseKey(); + InternalsDto dto = new InternalsDto( + DatabaseDto.fromEngineDto(other.getDatabase()), + ApplicationServerDto.fromEngineDto(other.getApplicationServer()), + licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null, + JdkDto.fromEngineDto(other.getJdk())); + + dto.dataCollectionStartDate = other.getDataCollectionStartDate(); + + dto.commands = new HashMap<>(); + other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount()))); + + dto.metrics = new HashMap<>(); + other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount()))); + + dto.setWebapps(other.getWebapps()); + dto.setCamundaIntegration(other.getCamundaIntegration()); + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/JdkDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/JdkDto.java new file mode 100644 index 0000000000000000000000000000000000000000..ad46f9d937bd559fc23f468b10f0b98da363eb5b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/JdkDto.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +import org.camunda.bpm.engine.telemetry.Jdk; + +public class JdkDto { + + protected String version; + protected String vendor; + + public JdkDto(String vendor, String version) { + this.version = version; + this.vendor = vendor; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getVendor() { + return vendor; + } + + public void setVendor(String vendor) { + this.vendor = vendor; + } + + public static JdkDto fromEngineDto(Jdk other) { + return new JdkDto( + other.getVendor(), + other.getVersion()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/LicenseKeyDataDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/LicenseKeyDataDto.java new file mode 100644 index 0000000000000000000000000000000000000000..26392875be7f73ea26c219dbedc175ae8e6b31eb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/LicenseKeyDataDto.java @@ -0,0 +1,105 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +import java.util.Map; + +import org.camunda.bpm.engine.telemetry.LicenseKeyData; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class LicenseKeyDataDto { + + public static final String SERIALIZED_VALID_UNTIL = "valid-until"; + public static final String SERIALIZED_IS_UNLIMITED = "unlimited"; + + protected String customer; + protected String type; + @JsonProperty(value = SERIALIZED_VALID_UNTIL) + protected String validUntil; + @JsonProperty(value = SERIALIZED_IS_UNLIMITED) + protected Boolean isUnlimited; + protected Map features; + protected String raw; + + public LicenseKeyDataDto(String customer, String type, String validUntil, Boolean isUnlimited, Map features, String raw) { + this.customer = customer; + this.type = type; + this.validUntil = validUntil; + this.isUnlimited = isUnlimited; + this.features = features; + this.raw = raw; + } + + public String getCustomer() { + return customer; + } + + public void setCustomer(String customer) { + this.customer = customer; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValidUntil() { + return validUntil; + } + + public void setValidUntil(String validUntil) { + this.validUntil = validUntil; + } + + public Boolean isUnlimited() { + return isUnlimited; + } + + public void setUnlimited(Boolean isUnlimited) { + this.isUnlimited = isUnlimited; + } + + public Map getFeatures() { + return features; + } + + public void setFeatures(Map features) { + this.features = features; + } + + public String getRaw() { + return raw; + } + + public void setRaw(String raw) { + this.raw = raw; + } + + public static LicenseKeyDataDto fromEngineDto(LicenseKeyData other) { + return new LicenseKeyDataDto( + other.getCustomer(), + other.getType(), + other.getValidUntil(), + other.isUnlimited(), + other.getFeatures(), + other.getRaw()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/MetricDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/MetricDto.java new file mode 100644 index 0000000000000000000000000000000000000000..aa21b698e0086e306ad2946900db78282b787f76 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/MetricDto.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +public class MetricDto { + + protected long count; + + public MetricDto(long count) { + this.count = count; + } + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/ProductDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/ProductDto.java new file mode 100644 index 0000000000000000000000000000000000000000..8567378920a36fbfecdb42394878177f7662dc5e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/ProductDto.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +import org.camunda.bpm.engine.telemetry.Product; + +public class ProductDto { + + protected String name; + protected String version; + protected String edition; + protected InternalsDto internals; + + public ProductDto(String name, String version, String edition, InternalsDto internals) { + this.name = name; + this.version = version; + this.edition = edition; + this.internals = internals; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getEdition() { + return edition; + } + + public void setEdition(String edition) { + this.edition = edition; + } + + public InternalsDto getInternals() { + return internals; + } + + public void setInternals(InternalsDto internals) { + this.internals = internals; + } + + public static ProductDto fromEngineDto(Product other) { + return new ProductDto( + other.getName(), + other.getVersion(), + other.getEdition(), + InternalsDto.fromEngineDto(other.getInternals())); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/TelemetryDataDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/TelemetryDataDto.java new file mode 100644 index 0000000000000000000000000000000000000000..bf09bdeca631f34d214c590aef8428124e859a92 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/dto/telemetry/TelemetryDataDto.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.dto.telemetry; + +import org.camunda.bpm.engine.telemetry.TelemetryData; + +public class TelemetryDataDto { + + protected String installation; + protected ProductDto product; + + public TelemetryDataDto(String installation, ProductDto product) { + this.installation = installation; + this.product = product; + } + + public String getInstallation() { + return installation; + } + + public void setInstallation(String installation) { + this.installation = installation; + } + + public ProductDto getProduct() { + return product; + } + + public void setProduct(ProductDto product) { + this.product = product; + } + + public static TelemetryDataDto fromEngineDto(TelemetryData other) { + return new TelemetryDataDto( + other.getInstallation(), + ProductDto.fromEngineDto(other.getProduct())); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionHandler.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..06bd26041d881dbceab67ab0323bf50a5b041f4f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionHandler.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * Translates any {@link Throwable} to a HTTP 500 error and a JSON response. + * Response content format: {"type" : "ExceptionType", "message" : "some exception message"} + * @author nico.rehwaldt + */ +@Provider +public class ExceptionHandler implements ExceptionMapper { + + @Override + public Response toResponse(Throwable throwable) { + return ExceptionHandlerHelper.getInstance().getResponse(throwable); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionHandlerHelper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionHandlerHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..25aea6418ba17d0cbb06e5e66caffadad9cde25b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionHandlerHelper.java @@ -0,0 +1,142 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ParseException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.migration.MigratingProcessInstanceValidationException; +import org.camunda.bpm.engine.migration.MigrationPlanValidationException; +import org.camunda.bpm.engine.rest.dto.AuthorizationExceptionDto; +import org.camunda.bpm.engine.rest.dto.ExceptionDto; +import org.camunda.bpm.engine.rest.dto.ParseExceptionDto; +import org.camunda.bpm.engine.rest.dto.migration.MigratingProcessInstanceValidationExceptionDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationPlanValidationExceptionDto; + +/** + * @author Svetlana Dorokhova. + */ +public class ExceptionHandlerHelper { + + protected static final ExceptionLogger LOGGER = ExceptionLogger.REST_LOGGER; + protected static final ExceptionHandlerHelper INSTANCE = new ExceptionHandlerHelper(); + + private ExceptionHandlerHelper() { + } + + public static ExceptionHandlerHelper getInstance(){ + return INSTANCE; + } + + public Response getResponse(Throwable throwable) { + LOGGER.log(throwable); + + Response.Status responseStatus = getStatus(throwable); + ExceptionDto exceptionDto = fromException(throwable); + + return Response + .status(responseStatus) + .entity(exceptionDto) + .type(MediaType.APPLICATION_JSON_TYPE) + .build(); + } + + protected void provideExceptionCode(Throwable throwable, ExceptionDto exceptionDto) { + Integer code = null; + if (throwable instanceof ProcessEngineException) { + code = getCode(throwable); + + } else if (throwable instanceof RestException) { + Throwable cause = throwable.getCause(); + if (cause instanceof ProcessEngineException) { + code = getCode(cause); + + } + } + + if (code != null) { + exceptionDto.setCode(code); + } + } + + protected Integer getCode(Throwable throwable) { + ProcessEngineException pex = (ProcessEngineException) throwable; + return pex.getCode(); + } + + public ExceptionDto fromException(Throwable e) { + ExceptionDto exceptionDto; + if (e instanceof MigratingProcessInstanceValidationException) { + exceptionDto = MigratingProcessInstanceValidationExceptionDto.from((MigratingProcessInstanceValidationException)e); + } else if (e instanceof MigrationPlanValidationException) { + exceptionDto = MigrationPlanValidationExceptionDto.from((MigrationPlanValidationException)e); + } else if (e instanceof AuthorizationException) { + exceptionDto = AuthorizationExceptionDto.fromException((AuthorizationException)e); + } else if (e instanceof ParseException){ + exceptionDto = ParseExceptionDto.fromException((ParseException) e); + } else { + exceptionDto = ExceptionDto.fromException(e); + } + provideExceptionCode(e, exceptionDto); + + return exceptionDto; + } + + public Response.Status getStatus(Throwable exception) { + Response.Status responseStatus = Response.Status.INTERNAL_SERVER_ERROR; + + if (exception instanceof ProcessEngineException) { + responseStatus = getStatus((ProcessEngineException)exception); + } + else if (exception instanceof RestException) { + responseStatus = getStatus((RestException) exception); + } + else if (exception instanceof WebApplicationException) { + //we need to check this, as otherwise the logic for processing WebApplicationException will be overridden + final int statusCode = ((WebApplicationException) exception).getResponse().getStatus(); + responseStatus = Response.Status.fromStatusCode(statusCode); + } + return responseStatus; + } + + public Response.Status getStatus(ProcessEngineException exception) { + Response.Status responseStatus = Response.Status.INTERNAL_SERVER_ERROR; + + // provide custom handling of authorization exception + if (exception instanceof AuthorizationException) { + responseStatus = Response.Status.FORBIDDEN; + } + else if (exception instanceof MigrationPlanValidationException + || exception instanceof MigratingProcessInstanceValidationException + || exception instanceof BadUserRequestException + || exception instanceof ParseException) { + responseStatus = Response.Status.BAD_REQUEST; + } + return responseStatus; + } + + public Response.Status getStatus(RestException exception) { + if (exception.getStatus() != null) { + return exception.getStatus(); + } + return Response.Status.INTERNAL_SERVER_ERROR; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionLogger.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionLogger.java new file mode 100644 index 0000000000000000000000000000000000000000..7c6d1aab391164aec85e45da782a877e06784998 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ExceptionLogger.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import static org.camunda.bpm.engine.impl.util.ExceptionUtil.PERSISTENCE_CONNECTION_ERROR_CLASS; +import static org.camunda.bpm.engine.impl.util.ExceptionUtil.getExceptionStacktrace; + +import java.sql.SQLException; +import javax.ws.rs.core.Response; +import org.camunda.bpm.engine.ProcessEnginePersistenceException; +import org.camunda.commons.logging.BaseLogger; + +public class ExceptionLogger extends BaseLogger { + + public static final String PROJECT_CODE = "ENGINE-REST"; + public static final String REST_API = "org.camunda.bpm.engine.rest.exception"; + + public static final ExceptionLogger REST_LOGGER = BaseLogger.createLogger(ExceptionLogger.class, + PROJECT_CODE, + REST_API, + "HTTP" + ); + + public void log(Throwable throwable) { + Response.Status status = ExceptionHandlerHelper.getInstance().getStatus(throwable); + int statusCode = status.getStatusCode(); + + if (statusCode < 500) { + logDebug(String.valueOf(statusCode), getExceptionStacktrace(throwable)); + return; + } + + logInternalServerAndOtherStatusCodes(throwable, statusCode); + } + + protected void logInternalServerAndOtherStatusCodes(Throwable throwable, int statusCode) { + + if (isPersistenceConnectionError(throwable)) { + logError(String.valueOf(statusCode), getExceptionStacktrace(throwable)); + return; + } + + logWarn(String.valueOf(statusCode), getExceptionStacktrace(throwable)); + } + + protected boolean isPersistenceConnectionError(Throwable throwable) { + boolean isPersistenceException = (throwable instanceof ProcessEnginePersistenceException); + + if (!isPersistenceException) { + return false; + } + + SQLException sqlException = getSqlException((ProcessEnginePersistenceException) throwable); + + if (sqlException == null) { + return false; + } + + String sqlState = sqlException.getSQLState(); + + return sqlState != null && sqlState.startsWith(PERSISTENCE_CONNECTION_ERROR_CLASS); + } + + protected SQLException getSqlException(ProcessEnginePersistenceException e) { + boolean hasTwoCauses = e.getCause() != null && e.getCause().getCause() != null; + + if (!hasTwoCauses) { + return null; + } + + Throwable cause = e.getCause().getCause(); + + return cause instanceof SQLException ? (SQLException) cause : null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/InvalidRequestException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/InvalidRequestException.java new file mode 100644 index 0000000000000000000000000000000000000000..e6a098580e5fc6d179dad0e43f54e3bda7aaafb7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/InvalidRequestException.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import javax.ws.rs.core.Response.Status; + +/** + * This exception is used for any kind of errors that occur due to malformed + * parameters in a Http query. + * + * @author Thorben Lindhauer + * + */ +public class InvalidRequestException extends RestException { + + private static final long serialVersionUID = 1L; + + public InvalidRequestException(Status status, String message) { + super(status, message); + } + + public InvalidRequestException(Status status, Exception cause, String message) { + super(status, cause, message); + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/JsonMappingExceptionHandler.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/JsonMappingExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..be1a823d05e998b79e890baad52291c604a3dc80 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/JsonMappingExceptionHandler.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import com.fasterxml.jackson.databind.JsonMappingException; + +/** + * @author Thorben Lindhauer + * + */ +@Provider +public class JsonMappingExceptionHandler implements ExceptionMapper { + + @Override + public Response toResponse(JsonMappingException exception) { + InvalidRequestException badRequestException = new InvalidRequestException(Status.BAD_REQUEST, + exception, ""); + return ExceptionHandlerHelper.getInstance().getResponse(badRequestException); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/JsonParseExceptionHandler.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/JsonParseExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..cd4af2cf3d5a00af3579efde3318789757338f0d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/JsonParseExceptionHandler.java @@ -0,0 +1,41 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import com.fasterxml.jackson.core.JsonParseException; +import org.camunda.bpm.engine.rest.dto.ExceptionDto; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * @author Thorben Lindhauer + * + */ +@Provider +public class JsonParseExceptionHandler implements ExceptionMapper { + + @Override + public Response toResponse(JsonParseException exception) { + InvalidRequestException badRequestException = new InvalidRequestException(Status.BAD_REQUEST, + exception, ""); + return ExceptionHandlerHelper.getInstance().getResponse(badRequestException); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ProcessEngineExceptionHandler.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ProcessEngineExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..f2bc7ec508a3bb4bcefe277a3369b89f9cc930e0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/ProcessEngineExceptionHandler.java @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ProcessEngineException; + +/** + *

Translates any {@link ProcessEngineException} to a HTTP 500 error and a JSON response. + * Response content format: {"type" : "ExceptionType", "message" : "some exception message"} + *

+ * + *

Provides dedicated exception handling for {@link AuthorizationException AuthorizationExceptions}: + * The status code is always set to 403, "Forbidden" and details about the requested resource and + * violated permission are added to the response body

+ * + * + * @author Thorben Lindhauer + * @author Daniel Meyer + */ +@Provider +public class ProcessEngineExceptionHandler implements ExceptionMapper { + + @Override + public Response toResponse(ProcessEngineException exception) { + return ExceptionHandlerHelper.getInstance().getResponse(exception); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/RestException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/RestException.java new file mode 100644 index 0000000000000000000000000000000000000000..1ce49b02ff1c5087e32018af26acacf82023a72f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/RestException.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import javax.ws.rs.core.Response.Status; + +public class RestException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private Status status; + + public RestException(String message) { + super(message); + } + + public RestException(Status status, String message) { + super(message); + this.status = status; + } + + public RestException(Status status, Exception cause) { + super(cause); + this.status = status; + } + + public RestException(Status status, Exception cause, String message) { + super(message, cause); + this.status = status; + } + + public Status getStatus() { + return status; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/RestExceptionHandler.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/RestExceptionHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..e26426e67b341196644475740d0ebafdf0fcdab6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/exception/RestExceptionHandler.java @@ -0,0 +1,36 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.exception; + +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +/** + * Translates {@link RestException}s to error responses according to the status that is set in the exception. + * Response content format: {"type" : "ExceptionType", "message" : "some exception message"} + * + * @author Thorben Lindhauer + */ +@Provider +public class RestExceptionHandler implements ExceptionMapper { + + @Override + public Response toResponse(RestException exception) { + return ExceptionHandlerHelper.getInstance().getResponse(exception); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/AbstractEmptyBodyFilter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/AbstractEmptyBodyFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..af09664e6d21c56ea1beebbcbb6cc2752bc7ba07 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/AbstractEmptyBodyFilter.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.filter; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PushbackInputStream; +import java.nio.charset.StandardCharsets; +import java.util.regex.Pattern; + +/** + * @author Tassilo Weidner + */ +public abstract class AbstractEmptyBodyFilter implements Filter { + + protected static final Pattern CONTENT_TYPE_JSON_PATTERN = Pattern.compile("^application\\/json((;)(.*)?)?$", Pattern.CASE_INSENSITIVE); + + @Override + public void doFilter(final ServletRequest req, final ServletResponse resp, FilterChain chain) throws IOException, ServletException { + + final boolean isContentTypeJson = + CONTENT_TYPE_JSON_PATTERN.matcher(req.getContentType() == null ? "" : req.getContentType()).find(); + + if (isContentTypeJson) { + final PushbackInputStream requestBody = new PushbackInputStream(req.getInputStream()); + int firstByte = requestBody.read(); + final boolean isBodyEmpty = firstByte == -1; + requestBody.unread(firstByte); + + chain.doFilter(wrapRequest((HttpServletRequest) req, isBodyEmpty, requestBody), resp); + } else { + chain.doFilter(req, resp); + } + } + + public InputStream getRequestBody(boolean isBodyEmpty, PushbackInputStream requestBody) { + return isBodyEmpty ? new ByteArrayInputStream("{}".getBytes(StandardCharsets.UTF_8)) : requestBody; + } + + public abstract HttpServletRequestWrapper wrapRequest(HttpServletRequest req, boolean isBodyEmpty, PushbackInputStream requestBody); + + @Override + public void destroy() { + + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + public BufferedReader getReader(final ServletInputStream inputStream) { + return new BufferedReader(new InputStreamReader(inputStream)); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/CacheControlFilter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/CacheControlFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..cda7a23fa0b3c915e751d26d9e3a6cdebfc6f707 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/CacheControlFilter.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.filter; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + *

Cache control filter setting "Cache-Control: no-cache" on all GET requests. + * + * @author Daniel Meyer + * + */ +public class CacheControlFilter implements Filter { + + public void init(FilterConfig filterConfig) throws ServletException { + + } + + public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { + + final HttpServletRequest request = (HttpServletRequest) req; + final HttpServletResponse response = (HttpServletResponse) resp; + + if("GET".equals(request.getMethod()) && !request.getRequestURI().endsWith("xml")) { + response.setHeader("Cache-Control", "no-cache"); + } + + chain.doFilter(req, resp); + } + + public void destroy() { + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/EmptyBodyFilter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/EmptyBodyFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..983f3cbcdc3dd9769575f377549e25a06f75a3d3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/filter/EmptyBodyFilter.java @@ -0,0 +1,84 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.filter; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PushbackInputStream; +import java.io.InputStream; + +/** + * @author Tassilo Weidner + */ +public class EmptyBodyFilter extends AbstractEmptyBodyFilter { + + @Override + public HttpServletRequestWrapper wrapRequest(HttpServletRequest req, boolean isBodyEmpty, PushbackInputStream requestBody) { + return new HttpServletRequestWrapper(req) { + + @Override + public ServletInputStream getInputStream() throws IOException { + + return new ServletInputStream() { + + final InputStream inputStream = getRequestBody(isBodyEmpty, requestBody); + + @Override + public int read() throws IOException { + return inputStream.read(); + } + + @Override + public int available() throws IOException { + return inputStream.available(); + } + + @Override + public void close() throws IOException { + inputStream.close(); + } + + @Override + public synchronized void mark(int readlimit) { + inputStream.mark(readlimit); + } + + @Override + public synchronized void reset() throws IOException { + inputStream.reset(); + } + + @Override + public boolean markSupported() { + return inputStream.markSupported(); + } + + }; + } + + @Override + public BufferedReader getReader() throws IOException { + return EmptyBodyFilter.this.getReader(this.getInputStream()); + } + + }; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/EmptyHalCollection.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/EmptyHalCollection.java new file mode 100644 index 0000000000000000000000000000000000000000..ef9bc4a9d60164c825056f97f06bf568e3680075 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/EmptyHalCollection.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import java.util.Collections; + +/** + * @author Sebastian Menski + */ +public class EmptyHalCollection extends HalCollectionResource { + + public static final HalResource INSTANCE = new EmptyHalCollection(); + + public EmptyHalCollection() { + this(0); + } + + public EmptyHalCollection(long count) { + _links = Collections.emptyMap(); + _embedded = Collections.emptyMap(); + this.count = count; + } + + @SuppressWarnings("unchecked") + public static T emptyHalCollection() { + return (T) INSTANCE; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/EmptyHalResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/EmptyHalResource.java new file mode 100644 index 0000000000000000000000000000000000000000..f8b8832d9a86db6cf3e6d3f7f021a7bd092a0ffd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/EmptyHalResource.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import java.util.Collections; + +/** + * @author Sebastian Menski + */ +public class EmptyHalResource extends HalResource { + + public static final HalResource INSTANCE = new EmptyHalResource(); + + public EmptyHalResource() { + _links = Collections.emptyMap(); + _embedded = Collections.emptyMap(); + } + + @SuppressWarnings("unchecked") + public static T emptyHalResource() { + return (T) INSTANCE; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/Hal.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/Hal.java new file mode 100644 index 0000000000000000000000000000000000000000..f9d03b50bcb4992f7acdcc51627f229c534f1479 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/Hal.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.CaseDefinitionRestService; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.IdentityRestService; +import org.camunda.bpm.engine.rest.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.cache.Cache; +import org.camunda.bpm.engine.rest.hal.caseDefinition.HalCaseDefinitionResolver; +import org.camunda.bpm.engine.rest.hal.group.HalGroupResolver; +import org.camunda.bpm.engine.rest.hal.identitylink.HalIdentityLinkResolver; +import org.camunda.bpm.engine.rest.hal.processDefinition.HalProcessDefinitionResolver; +import org.camunda.bpm.engine.rest.hal.user.HalUserResolver; + +/** + * @author Daniel Meyer + * + */ +public class Hal { + + public static final String APPLICATION_HAL_JSON = "application/hal+json"; + public static final MediaType APPLICATION_HAL_JSON_TYPE = new MediaType("application", "hal+json"); + + public static Hal instance = new Hal(); + + protected Map, HalLinkResolver> halLinkResolvers = new HashMap, HalLinkResolver>(); + protected Map, Cache> halRelationCaches = new HashMap, Cache>(); + + public Hal() { + // register the built-in resolvers + halLinkResolvers.put(UserRestService.class, new HalUserResolver()); + halLinkResolvers.put(GroupRestService.class, new HalGroupResolver()); + halLinkResolvers.put(ProcessDefinitionRestService.class, new HalProcessDefinitionResolver()); + halLinkResolvers.put(CaseDefinitionRestService.class, new HalCaseDefinitionResolver()); + halLinkResolvers.put(IdentityRestService.class, new HalIdentityLinkResolver()); + } + + public static Hal getInstance() { + return instance; + } + + public HalLinker createLinker(HalResource resource) { + return new HalLinker(this, resource); + } + + public HalLinkResolver getLinkResolver(Class resourceClass) { + return halLinkResolvers.get(resourceClass); + } + + public void registerHalRelationCache(Class entityClass, Cache cache) { + halRelationCaches.put(entityClass, cache); + } + + public Cache getHalRelationCache(Class resourceClass) { + return halRelationCaches.get(resourceClass); + } + + public void destroyHalRelationCaches() { + for (Cache cache : halRelationCaches.values()) { + cache.destroy(); + } + halRelationCaches.clear(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalCollectionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalCollectionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..19e0162f378d8505755bf36a64c27e76b9067fc0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalCollectionResource.java @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +/** + * @author Sebastian Menski + */ +public abstract class HalCollectionResource> extends HalResource { + + protected long count = 0; + + public long getCount() { + return count; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalIdResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalIdResource.java new file mode 100644 index 0000000000000000000000000000000000000000..f66d070a9c033a33a49d29d810325f6add4c0dd4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalIdResource.java @@ -0,0 +1,24 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +public interface HalIdResource { + + /** return the identifier of the resource */ + String getId(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLink.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLink.java new file mode 100644 index 0000000000000000000000000000000000000000..34ccbc0a0957d34581f4f3e92ad1db12a1a437c7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLink.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +/** + * Partial implementation of the HAL link object as defined in + * json-hal-06#section-5 + * + * @author Daniel Meyer + * + */ +public class HalLink { + + protected String href; + + public HalLink(String href) { + this.href = href; + } + + public String getHref() { + return href; + } + + public void setHref(String href) { + this.href = href; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLinkResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLinkResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..b55fbc13e629097b8c5e067d89e409db12c30065 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLinkResolver.java @@ -0,0 +1,34 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import org.camunda.bpm.engine.ProcessEngine; + +import java.util.List; + +/** + * A link resolver is capable of resolving a set of resources by Id. + * Link resolvers are used for embedding relations. + * + * @author Daniel Meyer + * + */ +public interface HalLinkResolver { + + public List> resolveLinks(String[] linkedIds, ProcessEngine processEngine); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLinker.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLinker.java new file mode 100644 index 0000000000000000000000000000000000000000..5a7abd73cc0c7012be782078bbf5fca50fd18a38 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalLinker.java @@ -0,0 +1,122 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import org.camunda.bpm.engine.ProcessEngine; + +import java.util.*; +import java.util.Map.Entry; + +/** + * A stateful linker which collects information about the links it creates. + * + * @author Daniel Meyer + * + */ +public class HalLinker { + + /** + * linked resource ids by {@link HalRelation} + */ + Map> linkedResources = new HashMap>(); + + protected final Hal hal; + + /** + * The HalResource on which the links are constructed + */ + protected final HalResource resource; + + public HalLinker(Hal hal, HalResource resource) { + this.hal = hal; + this.resource = resource; + } + + /** + * Creates a link in a given relation. + * + * @param rel the {@link HalRelation} for which a link should be constructed + * @param pathParams the path params to populate the url template with. + * */ + public void createLink(HalRelation rel, String... pathParams) { + if(pathParams != null && pathParams.length > 0 && pathParams[0] != null) { + Set linkedResourceIds = linkedResources.get(rel); + if(linkedResourceIds == null) { + linkedResourceIds = new HashSet(); + linkedResources.put(rel, linkedResourceIds); + } + + // Hmm... use the last id in the pathParams as linked resource id + linkedResourceIds.add(pathParams[pathParams.length - 1]); + + resource.addLink(rel.relName, rel.uriTemplate.build((Object[])pathParams)); + } + } + + public Set getLinkedRelations() { + return linkedResources.keySet(); + } + + public Set getLinkedResourceIdsByRelation(HalRelation relation) { + Set result = linkedResources.get(relation); + if(result != null) { + return result; + } else { + return Collections.emptySet(); + } + } + + /** + * Resolves a relation. Locates a HalLinkResolver for resolving the set of all linked resources in the relation. + * + * @param relation the relation to resolve + * @param processEngine the process engine to use + * @return the list of resolved resources + * @throws RuntimeException if no HalLinkResolver can be found for the linked resource type. + */ + public List> resolve(HalRelation relation, ProcessEngine processEngine) { + HalLinkResolver linkResolver = hal.getLinkResolver(relation.resourceType); + if(linkResolver != null) { + Set linkedIds = getLinkedResourceIdsByRelation(relation); + if(!linkedIds.isEmpty()) { + return linkResolver.resolveLinks(linkedIds.toArray(new String[linkedIds.size()]), processEngine); + } else { + return Collections.emptyList(); + } + } else { + throw new RuntimeException("Cannot find HAL link resolver for resource type '"+relation.resourceType+"'."); + } + } + + /** + * merge the links of an embedded resource into this linker. + * This is useful when building resources which are actually resource collections. + * You can then merge the relations of all resources in the collection and the unique the set of linked resources to embed. + * + * @param embedded the embedded resource for which the links should be merged into this linker. + */ + public void mergeLinks(HalResource embedded) { + for (Entry> linkentry : embedded.linker.linkedResources.entrySet()) { + Set linkedIdSet = linkedResources.get(linkentry.getKey()); + if(linkedIdSet != null) { + linkedIdSet.addAll(linkentry.getValue()); + }else { + linkedResources.put(linkentry.getKey(), linkentry.getValue()); + } + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalRelation.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalRelation.java new file mode 100644 index 0000000000000000000000000000000000000000..07cf9d459064e0ba8e9cba1a473b39577ceab576 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalRelation.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import javax.ws.rs.core.UriBuilder; + +/** + * @author Daniel Meyer + * + */ +public class HalRelation { + + /** the name of the relation */ + protected String relName; + + /** the url template used by the relation to construct links */ + protected UriBuilder uriTemplate; + + /** the type of the resource we build a relation to. */ + protected Class resourceType; + + /** + * Build a relation to a resource. + * + * @param relName the name of the relation. + * @param resourceType the type of the resource + * @return the relation + */ + public static HalRelation build(String relName, Class resourceType, UriBuilder urlTemplate) { + HalRelation relation = new HalRelation(); + relation.relName = relName; + relation.uriTemplate = urlTemplate; + relation.resourceType = resourceType; + return relation; + } + + public String getRelName() { + return relName; + } + + public UriBuilder getUriTemplate() { + return uriTemplate; + } + + public Class getResourceType() { + return resourceType; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalResource.java new file mode 100644 index 0000000000000000000000000000000000000000..da428d7d78bc3287e3dd191aef8539ac047f208f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalResource.java @@ -0,0 +1,106 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import org.camunda.bpm.engine.ProcessEngine; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * Base class for implementing a HAL resource as defined in + * json-hal-06#section-4 + * + * @author Daniel Meyer + * + */ +public abstract class HalResource> { + + /** This resource links */ + protected Map _links; + + /** Embedded resources */ + protected Map _embedded; + + // the linker used by this resource + protected transient HalLinker linker; + + public HalResource() { + this.linker = Hal.getInstance().createLinker(this); + } + + public Map get_links() { + return _links; + } + + public Map get_embedded() { + return _embedded; + } + + public void addLink(String rel, String href) { + if(_links == null) { + _links = new TreeMap(); + } + _links.put(rel, new HalLink(href)); + } + + public void addLink(String rel, URI hrefUri) { + addLink(rel, hrefUri.toString()); + } + + public void addEmbedded(String name, HalResource embedded) { + linker.mergeLinks(embedded); + addEmbeddedObject(name, embedded); + } + + private void addEmbeddedObject(String name, Object embedded) { + if(_embedded == null) { + _embedded = new TreeMap(); + } + _embedded.put(name, embedded); + } + + public void addEmbedded(String name, List> embeddedCollection) { + for (HalResource resource : embeddedCollection) { + linker.mergeLinks(resource); + } + addEmbeddedObject(name, embeddedCollection); + } + + public Object getEmbedded(String name) { + return _embedded.get(name); + } + + /** + * Can be used to embed a relation. Embedded all linked resources in the given relation. + * + * @param relation the relation to embedded + * @param processEngine used to resolve the resources + * @return the resource itself. + */ + @SuppressWarnings("unchecked") + public T embed(HalRelation relation, ProcessEngine processEngine) { + List> resolvedLinks = linker.resolve(relation, processEngine); + if(resolvedLinks != null && resolvedLinks.size() > 0) { + addEmbedded(relation.relName, resolvedLinks); + } + return (T) this; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalVariableValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalVariableValue.java new file mode 100644 index 0000000000000000000000000000000000000000..9ccd3acd266c7971f26300c0a5a65074328d5cb7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/HalVariableValue.java @@ -0,0 +1,125 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + +import org.camunda.bpm.engine.rest.*; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.runtime.VariableInstance; + +import javax.ws.rs.core.UriBuilder; +import java.util.Map; + +/** + * @author Sebastian Menski + */ +public class HalVariableValue extends HalResource { + + // add leading / by hand because otherwise it will be encoded as %2F (see CAM-3091) + public static HalRelation REL_SELF = HalRelation.build("self", VariableResource.class, UriBuilder.fromPath("/{scopeResourcePath}").path("{scopeId}").path("{variablesName}").path("{variableName}")); + + protected String name; + protected Object value; + protected String type; + protected Map valueInfo; + + public static HalVariableValue generateVariableValue(VariableInstance variableInstance, String variableScopeId) { + if (variableScopeId.equals(variableInstance.getTaskId())) { + return generateTaskVariableValue(variableInstance, variableScopeId); + } + else if (variableScopeId.equals(variableInstance.getProcessInstanceId())) { + return generateProcessInstanceVariableValue(variableInstance, variableScopeId); + } + else if (variableScopeId.equals(variableInstance.getExecutionId())) { + return generateExecutionVariableValue(variableInstance, variableScopeId); + } + else if (variableScopeId.equals(variableInstance.getCaseInstanceId())) { + return generateCaseInstanceVariableValue(variableInstance, variableScopeId); + } + else if (variableScopeId.equals(variableInstance.getCaseExecutionId())) { + return generateCaseExecutionVariableValue(variableInstance, variableScopeId); + } + else { + throw new RestException("Variable scope id '" + variableScopeId + "' does not match with variable instance '" + variableInstance + "'"); + } + } + + public static HalVariableValue generateTaskVariableValue(VariableInstance variableInstance, String taskId) { + return fromVariableInstance(variableInstance) + .link(REL_SELF, TaskRestService.PATH, taskId, "localVariables"); + } + + public static HalVariableValue generateExecutionVariableValue(VariableInstance variableInstance, String executionId) { + return fromVariableInstance(variableInstance) + .link(REL_SELF, ExecutionRestService.PATH, executionId, "localVariables"); + } + + public static HalVariableValue generateProcessInstanceVariableValue(VariableInstance variableInstance, String processInstanceId) { + return fromVariableInstance(variableInstance) + .link(REL_SELF, ProcessInstanceRestService.PATH, processInstanceId, "variables"); + } + + public static HalVariableValue generateCaseExecutionVariableValue(VariableInstance variableInstance, String caseExecutionId) { + return fromVariableInstance(variableInstance) + .link(REL_SELF, CaseExecutionRestService.PATH, caseExecutionId, "localVariables"); + } + + public static HalVariableValue generateCaseInstanceVariableValue(VariableInstance variableInstance, String caseInstanceId) { + return fromVariableInstance(variableInstance) + .link(REL_SELF, CaseInstanceRestService.PATH, caseInstanceId, "variables"); + } + + private HalVariableValue link(HalRelation relation, String resourcePath, String resourceId, String variablesPath) { + if (resourcePath.startsWith("/")) { + // trim leading / because otherwise it will be encode as %2F (see CAM-3091) + resourcePath = resourcePath.substring(1); + } + this.linker.createLink(relation, resourcePath, resourceId, variablesPath, this.name); + return this; + } + + public static HalVariableValue fromVariableInstance(VariableInstance variableInstance) { + HalVariableValue dto = new HalVariableValue(); + + VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(variableInstance.getTypedValue()); + + dto.name = variableInstance.getName(); + dto.value = variableValueDto.getValue(); + dto.type = variableValueDto.getType(); + dto.valueInfo = variableValueDto.getValueInfo(); + + return dto; + } + + public String getName() { + return name; + } + + public Object getValue() { + return value; + } + + public String getType() { + return type; + } + + public Map getValueInfo() { + return valueInfo; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/JacksonHalJsonProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/JacksonHalJsonProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..be69b4f7d80c8537885e375a07c8f993ddb502d0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/JacksonHalJsonProvider.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Produces; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; + +/** + * @author Daniel Meyer + * + */ +@Provider +@Consumes({Hal.APPLICATION_HAL_JSON, "text/json"}) +@Produces({Hal.APPLICATION_HAL_JSON, "text/json"}) +public class JacksonHalJsonProvider extends JacksonJsonProvider implements + MessageBodyReader, + MessageBodyWriter { + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/DefaultHalResourceCache.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/DefaultHalResourceCache.java new file mode 100644 index 0000000000000000000000000000000000000000..8dfe93ddbb09f7ce3d34b70a5fdf406c0d7751ce --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/DefaultHalResourceCache.java @@ -0,0 +1,134 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.NavigableSet; +import java.util.TreeSet; + +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.rest.cache.Cache; + +public class DefaultHalResourceCache implements Cache { + + public final static Comparator COMPARATOR = HalResourceCacheEntryComparator.getInstance(); + + protected int capacity; + protected long secondsToLive; + protected Map cache; + + public DefaultHalResourceCache() { + this(100, 100); + } + + public DefaultHalResourceCache(int capacity, long secondsToLive) { + this.capacity = capacity; + this.secondsToLive = secondsToLive; + cache = new HashMap(); + } + + public int getCapacity() { + return capacity; + } + + public void setCapacity(int capacity) { + this.capacity = capacity; + } + + public long getSecondsToLive() { + return secondsToLive; + } + + public void setSecondsToLive(long secondsToLive) { + this.secondsToLive = secondsToLive; + } + + public int size() { + return cache.size(); + } + + public void put(String id, Object resource) { + cache.put(id, new HalResourceCacheEntry(id, resource)); + ensureCapacityLimit(); + } + + public void remove(String id) { + cache.remove(id); + } + + public Object get(String id) { + HalResourceCacheEntry cacheEntry = cache.get(id); + if (cacheEntry != null) { + if (expired(cacheEntry)) { + remove(cacheEntry.getId()); + return null; + } + else { + return cacheEntry.getResource(); + } + } + else { + return null; + } + } + + public void destroy() { + cache.clear(); + } + + protected void ensureCapacityLimit() { + if (size() > getCapacity()) { + List resources = new ArrayList(cache.values()); + NavigableSet remainingResources = new TreeSet(COMPARATOR); + + // remove expired resources + for (HalResourceCacheEntry resource : resources) { + if (expired(resource)) { + remove(resource.getId()); + } + else { + remainingResources.add(resource); + } + + if (size() <= getCapacity()) { + // abort if capacity is reached + return; + } + } + + // if still exceed capacity remove oldest + while (remainingResources.size() > capacity) { + HalResourceCacheEntry resourceToRemove = remainingResources.pollFirst(); + if (resourceToRemove != null) { + remove(resourceToRemove.getId()); + } + else { + break; + } + } + } + } + + protected boolean expired(HalResourceCacheEntry entry) { + return entry.getCreateTime() + secondsToLive * 1000 < ClockUtil.getCurrentTime().getTime(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalCachingLinkResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalCachingLinkResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..4e372aeeff9cc689428b6c2a392809c3e8c2936f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalCachingLinkResolver.java @@ -0,0 +1,130 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.cache.Cache; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.hal.HalLinkResolver; +import org.camunda.bpm.engine.rest.hal.HalResource; + +public abstract class HalCachingLinkResolver implements HalLinkResolver { + + /** + * Resolve resources for linked ids, if configured uses a cache. + */ + public List> resolveLinks(String[] linkedIds, ProcessEngine processEngine) { + Cache cache = getCache(); + + if (cache == null) { + return resolveNotCachedLinks(linkedIds, processEngine); + } + else { + ArrayList notCachedLinkedIds = new ArrayList(); + List> resolvedResources = resolveCachedLinks(linkedIds, cache, notCachedLinkedIds); + + if (!notCachedLinkedIds.isEmpty()) { + List> notCachedResources = resolveNotCachedLinks(notCachedLinkedIds.toArray(new String[notCachedLinkedIds.size()]), processEngine); + resolvedResources.addAll(notCachedResources); + putIntoCache(notCachedResources); + } + + sortResolvedResources(resolvedResources); + + return resolvedResources; + } + } + + /** + * Sort the resolved resources to ensure consistent order of resolved resources. + */ + protected void sortResolvedResources(List> resolvedResources) { + Comparator> comparator = getResourceComparator(); + if (comparator != null) { + Collections.sort(resolvedResources, comparator); + } + } + + /** + * @return the cache for this resolver + */ + protected Cache getCache() { + return Hal.getInstance().getHalRelationCache(getHalResourceClass()); + } + + /** + * Returns a list with all resources which are cached. + * + * @param linkedIds the ids to resolve + * @param cache the cache to use + * @param notCachedLinkedIds a list with ids which are not found in the cache + * @return the cached resources + */ + protected List> resolveCachedLinks(String[] linkedIds, Cache cache, List notCachedLinkedIds) { + ArrayList> resolvedResources = new ArrayList>(); + + for (String linkedId : linkedIds) { + HalResource resource = (HalResource) cache.get(linkedId); + if (resource != null) { + resolvedResources.add(resource); + } + else { + notCachedLinkedIds.add(linkedId); + } + } + + return resolvedResources; + } + + /** + * Put a resource into the cache. + */ + protected void putIntoCache(List> notCachedResources) { + Cache cache = getCache(); + for (HalResource notCachedResource : notCachedResources) { + cache.put(getResourceId(notCachedResource), notCachedResource); + } + } + + /** + * @return the class of the entity which is resolved + */ + protected abstract Class getHalResourceClass(); + + /** + * @return a comparator for this HAL resource if not overridden sorting is skipped + */ + protected Comparator> getResourceComparator() { + return null; + } + + /** + * @return the resolved resources which are currently not cached + */ + protected abstract List> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine); + + /** + * @return the id which identifies a resource in the cache + */ + protected abstract String getResourceId(HalResource resource); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalIdResourceCacheLinkResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalIdResourceCacheLinkResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..332528de4cf7307586ae02d3c6d872f79e9d254d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalIdResourceCacheLinkResolver.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +import java.util.Comparator; + +import org.camunda.bpm.engine.rest.hal.HalIdResource; +import org.camunda.bpm.engine.rest.hal.HalResource; + +public abstract class HalIdResourceCacheLinkResolver extends HalCachingLinkResolver { + + public final static Comparator> ID_COMPARATOR = new HalIdResourceComparator(); + + protected String getResourceId(HalResource resource) { + return ((HalIdResource) resource).getId(); + } + + @Override + protected Comparator> getResourceComparator() { + return ID_COMPARATOR; + } + + public static class HalIdResourceComparator implements Comparator> { + + public int compare(HalResource resource1, HalResource resource2) { + String id1 = ((HalIdResource) resource1).getId(); + String id2 = ((HalIdResource) resource2).getId(); + return id1.compareTo(id2); + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheBootstrap.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheBootstrap.java new file mode 100644 index 0000000000000000000000000000000000000000..c5654b2bd1832361b25b82ad87b50348c2dc8bd9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheBootstrap.java @@ -0,0 +1,110 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Map; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.util.ReflectUtil; +import org.camunda.bpm.engine.rest.cache.Cache; +import org.camunda.bpm.engine.rest.hal.Hal; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HalRelationCacheBootstrap implements ServletContextListener { + + public final static String CONTEXT_PARAM_NAME = "org.camunda.bpm.engine.rest.hal.cache.config"; + + protected ObjectMapper objectMapper = new ObjectMapper(); + + public void contextInitialized(ServletContextEvent sce) { + String contextParameter = sce.getServletContext().getInitParameter(CONTEXT_PARAM_NAME); + if (contextParameter != null) { + configureCaches(contextParameter); + } + } + + public void contextDestroyed(ServletContextEvent sce) { + Hal.getInstance().destroyHalRelationCaches(); + } + + public void configureCaches(String contextParameter) { + HalRelationCacheConfiguration configuration = new HalRelationCacheConfiguration(contextParameter); + configureCaches(configuration); + } + + public void configureCaches(HalRelationCacheConfiguration configuration) { + Class cacheClass = configuration.getCacheImplementationClass(); + for (Map.Entry, Map> cacheConfiguration : configuration.getCacheConfigurations().entrySet()) { + Cache cache = createCache(cacheClass, cacheConfiguration.getValue()); + registerCache(cacheConfiguration.getKey(), cache); + } + } + + protected Cache createCache(Class cacheClass, Map cacheConfiguration) { + Cache cache = createCacheInstance(cacheClass); + configureCache(cache, cacheConfiguration); + return cache; + } + + protected void configureCache(Cache cache, Map cacheConfiguration) { + for (Map.Entry configuration : cacheConfiguration.entrySet()) { + configureCache(cache, configuration.getKey(), configuration.getValue()); + } + } + + protected Cache createCacheInstance(Class cacheClass) { + try { + return ReflectUtil.instantiate(cacheClass); + } + catch (ProcessEngineException e) { + throw new HalRelationCacheConfigurationException("Unable to instantiate cache class " + cacheClass.getName(), e); + } + } + + protected void configureCache(Cache cache, String property, Object value) { + Method setter; + try { + setter = ReflectUtil.getSingleSetter(property, cache.getClass()); + } + catch (ProcessEngineException e) { + throw new HalRelationCacheConfigurationException("Unable to find setter for property " + property, e); + } + + if (setter == null) { + throw new HalRelationCacheConfigurationException("Unable to find setter for property " + property); + } + + try { + setter.invoke(cache, value); + } catch (IllegalAccessException e) { + throw new HalRelationCacheConfigurationException("Unable to access setter for property " + property); + } catch (InvocationTargetException e) { + throw new HalRelationCacheConfigurationException("Unable to invoke setter for property " + property); + } + } + + protected void registerCache(Class halResourceClass, Cache cache) { + Hal.getInstance().registerHalRelationCache(halResourceClass, cache); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheConfiguration.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheConfiguration.java new file mode 100644 index 0000000000000000000000000000000000000000..eedf213db87a678ec0d84333b83dab90f6d3833c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheConfiguration.java @@ -0,0 +1,132 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import org.camunda.bpm.engine.rest.cache.Cache; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HalRelationCacheConfiguration { + + public final static String CONFIG_CACHE_IMPLEMENTATION = "cacheImplementation"; + public static final String CONFIG_CACHES = "caches"; + + protected ObjectMapper objectMapper = new ObjectMapper(); + protected Class cacheImplementationClass; + protected Map, Map> cacheConfigurations; + + public HalRelationCacheConfiguration() { + cacheConfigurations = new HashMap, Map>(); + } + + public HalRelationCacheConfiguration(String configuration) { + this(); + parseConfiguration(configuration); + } + + public Class getCacheImplementationClass() { + return cacheImplementationClass; + } + + @SuppressWarnings("unchecked") + public void setCacheImplementationClass(Class cacheImplementationClass) { + if (Cache.class.isAssignableFrom(cacheImplementationClass)) { + this.cacheImplementationClass = (Class) cacheImplementationClass; + } + else { + throw new HalRelationCacheConfigurationException("Cache implementation class " + cacheImplementationClass.getName() + " does not implement the interface " + Cache.class.getName()); + } + } + + public Map, Map> getCacheConfigurations() { + return cacheConfigurations; + } + + public void setCacheConfigurations(Map, Map> cacheConfigurations) { + this.cacheConfigurations = cacheConfigurations; + } + + public void addCacheConfiguration(Class halResourceClass, Map cacheConfiguration) { + this.cacheConfigurations.put(halResourceClass, cacheConfiguration); + } + + protected void parseConfiguration(String configuration) { + try { + JsonNode jsonConfiguration = objectMapper.readTree(configuration); + parseConfiguration(jsonConfiguration); + } catch (IOException e) { + throw new HalRelationCacheConfigurationException("Unable to parse cache configuration", e); + } + } + + protected void parseConfiguration(JsonNode jsonConfiguration) { + parseCacheImplementationClass(jsonConfiguration); + parseCacheConfigurations(jsonConfiguration); + } + + protected void parseCacheImplementationClass(JsonNode jsonConfiguration) { + JsonNode jsonNode = jsonConfiguration.get(CONFIG_CACHE_IMPLEMENTATION); + if (jsonNode != null) { + String cacheImplementationClassName = jsonNode.textValue(); + Class cacheImplementationClass = loadClass(cacheImplementationClassName); + setCacheImplementationClass(cacheImplementationClass); + } + else { + throw new HalRelationCacheConfigurationException("Unable to find the " + CONFIG_CACHE_IMPLEMENTATION + " parameter"); + } + } + + protected void parseCacheConfigurations(JsonNode jsonConfiguration) { + JsonNode jsonNode = jsonConfiguration.get(CONFIG_CACHES); + if (jsonNode != null) { + Iterator> cacheConfigurations = jsonNode.fields(); + while (cacheConfigurations.hasNext()) { + Entry cacheConfiguration = cacheConfigurations.next(); + parseCacheConfiguration(cacheConfiguration.getKey(), cacheConfiguration.getValue()); + } + } + } + + @SuppressWarnings("unchecked") + protected void parseCacheConfiguration(String halResourceClassName, JsonNode jsonConfiguration) { + try { + Class halResourceClass = loadClass(halResourceClassName); + Map configuration = objectMapper.treeToValue(jsonConfiguration, Map.class); + addCacheConfiguration(halResourceClass, configuration); + } catch (IOException e) { + throw new HalRelationCacheConfigurationException("Unable to parse cache configuration for HAL resource " + halResourceClassName); + } + } + + protected Class loadClass(String className) { + try { + // use classloader which loaded the REST api classes + return Class.forName(className, true, HalRelationCacheConfiguration.class.getClassLoader()); + } + catch (ClassNotFoundException e) { + throw new HalRelationCacheConfigurationException("Unable to load class of cache configuration " + className, e); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheConfigurationException.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheConfigurationException.java new file mode 100644 index 0000000000000000000000000000000000000000..c462279c25e391981f45efb15b795da91e8c96b2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalRelationCacheConfigurationException.java @@ -0,0 +1,29 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +public class HalRelationCacheConfigurationException extends RuntimeException { + + public HalRelationCacheConfigurationException(String message) { + super(message); + } + + public HalRelationCacheConfigurationException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalResourceCacheEntry.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalResourceCacheEntry.java new file mode 100644 index 0000000000000000000000000000000000000000..c7231a9a6963ce619e34f0731358b27482a9a9fc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalResourceCacheEntry.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +import org.camunda.bpm.engine.impl.util.ClockUtil; + +public class HalResourceCacheEntry { + + protected String id; + protected long created; + protected Object resource; + + public HalResourceCacheEntry(String id, Object resource) { + this.id = id; + this.created = ClockUtil.getCurrentTime().getTime(); + this.resource = resource; + } + + public String getId() { + return id; + } + + public long getCreateTime() { + return created; + } + + public Object getResource() { + return resource; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalResourceCacheEntryComparator.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalResourceCacheEntryComparator.java new file mode 100644 index 0000000000000000000000000000000000000000..9d3d69f905e14f1c097dccad26d0c9a15aef22e7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/cache/HalResourceCacheEntryComparator.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.cache; + +import java.util.Collections; +import java.util.Comparator; + +public class HalResourceCacheEntryComparator implements Comparator { + + public final static Comparator INSTANCE = new HalResourceCacheEntryComparator(); + public final static Comparator REVERSE = Collections.reverseOrder(INSTANCE); + + /** Sort cache entries by ascending create time (oldest first) */ + public static Comparator getInstance() { + return INSTANCE; + } + + /** Sort cache entries by descending create time (newest first) */ + public static Comparator getReverse() { + return REVERSE; + } + + public int compare(HalResourceCacheEntry entry1, HalResourceCacheEntry entry2) { + int compareTime = ((Long) entry1.getCreateTime()).compareTo(entry2.getCreateTime()); + if (compareTime != 0) { + return compareTime; + } + else { + return entry1.getId().compareTo(entry2.getId()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/caseDefinition/HalCaseDefinition.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/caseDefinition/HalCaseDefinition.java new file mode 100644 index 0000000000000000000000000000000000000000..d2c03d9fc6b0d0dd8f52e75e014f3449e5b86d93 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/caseDefinition/HalCaseDefinition.java @@ -0,0 +1,106 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.caseDefinition; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.rest.CaseDefinitionRestService; +import org.camunda.bpm.engine.rest.DeploymentRestService; +import org.camunda.bpm.engine.rest.hal.HalIdResource; +import org.camunda.bpm.engine.rest.hal.HalRelation; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.sub.repository.DeploymentResourcesResource; +import org.camunda.bpm.engine.rest.util.ApplicationContextPathUtil; + +import javax.ws.rs.core.UriBuilder; + +/** + * @author Daniel Meyer + * + */ +public class HalCaseDefinition extends HalResource implements HalIdResource { + public static final HalRelation REL_SELF = + HalRelation.build("self", CaseDefinitionRestService.class, UriBuilder.fromPath(CaseDefinitionRestService.PATH).path("{id}")); + public static final HalRelation REL_DEPLOYMENT = + HalRelation.build("deployment", DeploymentRestService.class, UriBuilder.fromPath(DeploymentRestService.PATH).path("{id}")); + public static final HalRelation REL_DEPLOYMENT_RESOURCE = HalRelation.build("resource", DeploymentResourcesResource.class, + UriBuilder.fromPath(DeploymentRestService.PATH) + .path("{deploymentId}") + .path("resources") + .path("{resourceId}")); + + protected String id; + protected String key; + protected String category; + protected String name; + protected int version; + protected String resource; + protected String deploymentId; + protected String contextPath; + + public static HalCaseDefinition fromCaseDefinition(CaseDefinition caseDefinition, ProcessEngine processEngine) { + HalCaseDefinition halCaseDefinition = new HalCaseDefinition(); + + halCaseDefinition.id = caseDefinition.getId(); + halCaseDefinition.key = caseDefinition.getKey(); + halCaseDefinition.category = caseDefinition.getCategory(); + halCaseDefinition.name = caseDefinition.getName(); + halCaseDefinition.version = caseDefinition.getVersion(); + halCaseDefinition.resource = caseDefinition.getResourceName(); + halCaseDefinition.deploymentId = caseDefinition.getDeploymentId(); + halCaseDefinition.contextPath = ApplicationContextPathUtil.getApplicationPathForDeployment(processEngine, caseDefinition.getDeploymentId()); + + halCaseDefinition.linker.createLink(REL_SELF, caseDefinition.getId()); + halCaseDefinition.linker.createLink(REL_DEPLOYMENT, caseDefinition.getDeploymentId()); + halCaseDefinition.linker.createLink(REL_DEPLOYMENT_RESOURCE, caseDefinition.getDeploymentId(), caseDefinition.getResourceName()); + + return halCaseDefinition; + } + + public String getId() { + return id; + } + + public String getKey() { + return key; + } + + public String getCategory() { + return category; + } + + public String getName() { + return name; + } + + public int getVersion() { + return version; + } + + public String getResource() { + return resource; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getContextPath() { + return contextPath; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/caseDefinition/HalCaseDefinitionResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/caseDefinition/HalCaseDefinitionResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..3fb309951aae945c89db445419d766e78a58f808 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/caseDefinition/HalCaseDefinitionResolver.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.caseDefinition; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.hal.cache.HalIdResourceCacheLinkResolver; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Daniel Meyer + * + */ +public class HalCaseDefinitionResolver extends HalIdResourceCacheLinkResolver { + + protected Class getHalResourceClass() { + return HalCaseDefinition.class; + } + + protected List> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) { + RepositoryService repositoryService = processEngine.getRepositoryService(); + + List caseDefinitions = repositoryService.createCaseDefinitionQuery() + .caseDefinitionIdIn(linkedIds) + .listPage(0, linkedIds.length); + + List> resolved = new ArrayList>(); + for (CaseDefinition caseDefinition : caseDefinitions) { + resolved.add(HalCaseDefinition.fromCaseDefinition(caseDefinition, processEngine)); + } + + return resolved; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/group/HalGroup.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/group/HalGroup.java new file mode 100644 index 0000000000000000000000000000000000000000..b436c16b97b930c3a75c590b99e59ef14afbb775 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/group/HalGroup.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.group; + +import javax.ws.rs.core.UriBuilder; + +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.hal.HalIdResource; +import org.camunda.bpm.engine.rest.hal.HalRelation; +import org.camunda.bpm.engine.rest.hal.HalResource; + +public class HalGroup extends HalResource implements HalIdResource { + + public final static HalRelation REL_SELF = + HalRelation.build("self", GroupRestService.class, UriBuilder.fromPath(GroupRestService.PATH).path("{id}")); + + protected String id; + protected String name; + protected String type; + + public static HalGroup fromGroup(Group group) { + HalGroup halGroup = new HalGroup(); + + halGroup.id = group.getId(); + halGroup.name = group.getName(); + halGroup.type = group.getType(); + + halGroup.linker.createLink(REL_SELF, group.getId()); + + return halGroup; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getType() { + return type; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/group/HalGroupResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/group/HalGroupResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..dea8baa308e7a0ca0732c765ac74ca77ebf8adfa --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/group/HalGroupResolver.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.group; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.hal.cache.HalIdResourceCacheLinkResolver; + +public class HalGroupResolver extends HalIdResourceCacheLinkResolver { + + protected Class getHalResourceClass() { + return HalGroup.class; + } + + protected List> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) { + IdentityService identityService = processEngine.getIdentityService(); + + List groups = identityService.createGroupQuery() + .groupIdIn(linkedIds) + .listPage(0, linkedIds.length); + + List> resolvedGroups = new ArrayList>(); + for (Group group : groups) { + resolvedGroups.add(HalGroup.fromGroup(group)); + } + + return resolvedGroups; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/identitylink/HalIdentityLink.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/identitylink/HalIdentityLink.java new file mode 100644 index 0000000000000000000000000000000000000000..95ca0fbb97f31d6a1f59d703b9cf07d1f659a434 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/identitylink/HalIdentityLink.java @@ -0,0 +1,70 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.identitylink; + +import javax.ws.rs.core.UriBuilder; + +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.hal.HalRelation; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.task.IdentityLink; + +public class HalIdentityLink extends HalResource { + + public final static HalRelation REL_GROUP = HalRelation.build("group", GroupRestService.class, UriBuilder.fromPath(GroupRestService.PATH).path("{id}")); + public final static HalRelation REL_USER = HalRelation.build("user", UserRestService.class, UriBuilder.fromPath(UserRestService.PATH).path("{id}")); + public final static HalRelation REL_TASK = HalRelation.build("task", TaskRestService.class, UriBuilder.fromPath(TaskRestService.PATH).path("{id}")); + + protected String type; + protected String userId; + protected String groupId; + protected String taskId; + + public static HalIdentityLink fromIdentityLink(IdentityLink identityLink) { + HalIdentityLink halIdentityLink = new HalIdentityLink(); + + halIdentityLink.type = identityLink.getType(); + halIdentityLink.userId = identityLink.getUserId(); + halIdentityLink.groupId = identityLink.getGroupId(); + halIdentityLink.taskId = identityLink.getTaskId(); + + halIdentityLink.linker.createLink(REL_USER, identityLink.getUserId()); + halIdentityLink.linker.createLink(REL_GROUP, identityLink.getGroupId()); + halIdentityLink.linker.createLink(REL_TASK, identityLink.getTaskId()); + + return halIdentityLink; + } + + public String getType() { + return type; + } + + public String getUserId() { + return userId; + } + + public String getGroupId() { + return groupId; + } + + public String getTaskId() { + return taskId; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/identitylink/HalIdentityLinkResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/identitylink/HalIdentityLinkResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..8b6f90a7bb15c6e4da2f9507cc3ffff98b08473c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/identitylink/HalIdentityLinkResolver.java @@ -0,0 +1,70 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.identitylink; + +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.hal.cache.HalCachingLinkResolver; +import org.camunda.bpm.engine.task.IdentityLink; + +public class HalIdentityLinkResolver extends HalCachingLinkResolver { + + protected Class getHalResourceClass() { + return HalIdentityLink.class; + } + + @Override + public List> resolveLinks(String[] linkedIds, ProcessEngine processEngine) { + if (linkedIds.length > 1) { + throw new InvalidRequestException(Response.Status.INTERNAL_SERVER_ERROR, "The identity link resolver can only handle one task id"); + } + + return super.resolveLinks(linkedIds, processEngine); + } + + protected List> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) { + TaskService taskService = processEngine.getTaskService(); + + List identityLinks = taskService.getIdentityLinksForTask(linkedIds[0]); + + List> resolvedIdentityLinks = new ArrayList>(); + for (IdentityLink identityLink : identityLinks) { + resolvedIdentityLinks.add(HalIdentityLink.fromIdentityLink(identityLink)); + } + + return resolvedIdentityLinks; + } + + protected void putIntoCache(List> notCachedResources) { + // this resolver only can handle a single task and resolves a list of hal resources for this task + if (notCachedResources != null && !notCachedResources.isEmpty()) { + String taskId = getResourceId(notCachedResources.get(0)); + getCache().put(taskId, notCachedResources); + } + } + + protected String getResourceId(HalResource resource) { + return ((HalIdentityLink) resource).getTaskId(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/processDefinition/HalProcessDefinition.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/processDefinition/HalProcessDefinition.java new file mode 100644 index 0000000000000000000000000000000000000000..c555214db791149b1947960c98d2445029ae2eae --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/processDefinition/HalProcessDefinition.java @@ -0,0 +1,131 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.processDefinition; + +import javax.ws.rs.core.UriBuilder; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.rest.DeploymentRestService; +import org.camunda.bpm.engine.rest.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.hal.HalIdResource; +import org.camunda.bpm.engine.rest.hal.HalRelation; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.sub.repository.DeploymentResourcesResource; +import org.camunda.bpm.engine.rest.util.ApplicationContextPathUtil; + +/** + * @author Daniel Meyer + * + */ +public class HalProcessDefinition extends HalResource implements HalIdResource { + + public static final HalRelation REL_SELF = + HalRelation.build("self", ProcessDefinitionRestService.class, UriBuilder.fromPath(ProcessDefinitionRestService.PATH).path("{id}")); + public static final HalRelation REL_DEPLOYMENT = + HalRelation.build("deployment", DeploymentRestService.class, UriBuilder.fromPath(DeploymentRestService.PATH).path("{id}")); + public static final HalRelation REL_DEPLOYMENT_RESOURCE = HalRelation.build("resource", DeploymentResourcesResource.class, + UriBuilder.fromPath(DeploymentRestService.PATH) + .path("{deploymentId}") + .path("resources") + .path("{resourceId}")); + + protected String id; + protected String key; + protected String category; + protected String description; + protected String name; + protected String versionTag; + protected int version; + protected String resource; + protected String deploymentId; + protected String diagram; + protected boolean suspended; + protected String contextPath; + + public static HalProcessDefinition fromProcessDefinition(ProcessDefinition processDefinition, ProcessEngine processEngine) { + HalProcessDefinition halProcDef = new HalProcessDefinition(); + + halProcDef.id = processDefinition.getId(); + halProcDef.key = processDefinition.getKey(); + halProcDef.category = processDefinition.getCategory(); + halProcDef.description = processDefinition.getDescription(); + halProcDef.name = processDefinition.getName(); + halProcDef.version = processDefinition.getVersion(); + halProcDef.versionTag = processDefinition.getVersionTag(); + halProcDef.resource = processDefinition.getResourceName(); + halProcDef.deploymentId = processDefinition.getDeploymentId(); + halProcDef.diagram = processDefinition.getDiagramResourceName(); + halProcDef.suspended = processDefinition.isSuspended(); + halProcDef.contextPath = ApplicationContextPathUtil.getApplicationPathForDeployment(processEngine, processDefinition.getDeploymentId()); + + halProcDef.linker.createLink(REL_SELF, processDefinition.getId()); + halProcDef.linker.createLink(REL_DEPLOYMENT, processDefinition.getDeploymentId()); + halProcDef.linker.createLink(REL_DEPLOYMENT_RESOURCE, processDefinition.getDeploymentId(), processDefinition.getResourceName()); + + return halProcDef; + } + + public String getId() { + return id; + } + + public String getKey() { + return key; + } + + public String getCategory() { + return category; + } + + public String getDescription() { + return description; + } + + public String getName() { + return name; + } + + public int getVersion() { + return version; + } + + public String getVersionTag() { + return versionTag; + } + + public String getResource() { + return resource; + } + + public String getDeploymentId() { + return deploymentId; + } + + public String getDiagram() { + return diagram; + } + + public boolean isSuspended() { + return suspended; + } + + public String getContextPath() { + return contextPath; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/processDefinition/HalProcessDefinitionResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/processDefinition/HalProcessDefinitionResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..9baff3aebd1ba3c79bf89ed84e5934f0907fb5d9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/processDefinition/HalProcessDefinitionResolver.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.processDefinition; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.hal.cache.HalIdResourceCacheLinkResolver; + +/** + * @author Daniel Meyer + * + */ +public class HalProcessDefinitionResolver extends HalIdResourceCacheLinkResolver { + + protected Class getHalResourceClass() { + return HalProcessDefinition.class; + } + + protected List> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) { + RepositoryService repositoryService = processEngine.getRepositoryService(); + + List processDefinitions = repositoryService.createProcessDefinitionQuery() + .processDefinitionIdIn(linkedIds) + .listPage(0, linkedIds.length); + + List> resolved = new ArrayList>(); + for (ProcessDefinition procDef : processDefinitions) { + resolved.add(HalProcessDefinition.fromProcessDefinition(procDef, processEngine)); + } + + return resolved; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/task/HalTask.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/task/HalTask.java new file mode 100644 index 0000000000000000000000000000000000000000..f7b6d80112b81a26b9e5654e5ef680d0f9ba0bc6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/task/HalTask.java @@ -0,0 +1,239 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.task; + +import java.util.Date; + +import javax.ws.rs.core.UriBuilder; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.form.CamundaFormRef; +import org.camunda.bpm.engine.rest.CaseDefinitionRestService; +import org.camunda.bpm.engine.rest.CaseExecutionRestService; +import org.camunda.bpm.engine.rest.CaseInstanceRestService; +import org.camunda.bpm.engine.rest.ExecutionRestService; +import org.camunda.bpm.engine.rest.IdentityRestService; +import org.camunda.bpm.engine.rest.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.ProcessInstanceRestService; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.hal.HalRelation; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.hal.identitylink.HalIdentityLink; +import org.camunda.bpm.engine.task.DelegationState; +import org.camunda.bpm.engine.task.Task; + +/** + * @author Daniel Meyer + * + */ +public class HalTask extends HalResource { + + public static HalRelation REL_SELF = + HalRelation.build("self", TaskRestService.class, UriBuilder.fromPath(TaskRestService.PATH).path("{id}")); + public static HalRelation REL_ASSIGNEE = + HalRelation.build("assignee", UserRestService.class, UriBuilder.fromPath(UserRestService.PATH).path("{id}")); + public static HalRelation REL_OWNER = + HalRelation.build("owner", UserRestService.class, UriBuilder.fromPath(UserRestService.PATH).path("{id}")); + public static HalRelation REL_EXECUTION = + HalRelation.build("execution", ExecutionRestService.class, UriBuilder.fromPath(ExecutionRestService.PATH).path("{id}")); + public static HalRelation REL_PARENT_TASK = + HalRelation.build("parentTask", TaskRestService.class, UriBuilder.fromPath(TaskRestService.PATH).path("{id}")); + public static HalRelation REL_PROCESS_DEFINITION = + HalRelation.build("processDefinition", ProcessDefinitionRestService.class, UriBuilder.fromPath(ProcessDefinitionRestService.PATH).path("{id}")); + public static HalRelation REL_PROCESS_INSTANCE = + HalRelation.build("processInstance", ProcessInstanceRestService.class, UriBuilder.fromPath(ProcessInstanceRestService.PATH).path("{id}")); + public static HalRelation REL_CASE_INSTANCE = + HalRelation.build("caseInstance", CaseInstanceRestService.class, UriBuilder.fromPath(CaseInstanceRestService.PATH).path("{id}")); + public static HalRelation REL_CASE_EXECUTION = + HalRelation.build("caseExecution", CaseExecutionRestService.class, UriBuilder.fromPath(CaseExecutionRestService.PATH).path("{id}")); + public static HalRelation REL_CASE_DEFINITION = + HalRelation.build("caseDefinition", CaseDefinitionRestService.class, UriBuilder.fromPath(CaseDefinitionRestService.PATH).path("{id}")); + public static HalRelation REL_IDENTITY_LINKS = + HalRelation.build("identityLink", IdentityRestService.class, UriBuilder.fromPath(TaskRestService.PATH).path("{taskId}").path("identity-links")); + + private String id; + private String name; + private String assignee; + private Date created; + private Date due; + private Date followUp; + private DelegationState delegationState; + private String description; + private String executionId; + private String owner; + private String parentTaskId; + private int priority; + private String processDefinitionId; + private String processInstanceId; + private String taskDefinitionKey; + private String caseExecutionId; + private String caseInstanceId; + private String caseDefinitionId; + private boolean suspended; + private String formKey; + private CamundaFormRef camundaFormRef; + private String tenantId; + + public static HalTask generate(Task task, ProcessEngine engine) { + return fromTask(task) + .embed(HalTask.REL_PROCESS_DEFINITION, engine) + .embed(HalTask.REL_CASE_DEFINITION, engine) + .embed(HalTask.REL_IDENTITY_LINKS, engine) + .embed(HalIdentityLink.REL_USER, engine) + .embed(HalIdentityLink.REL_GROUP, engine); + } + + public static HalTask fromTask(Task task) { + HalTask dto = new HalTask(); + + // task state + dto.id = task.getId(); + dto.name = task.getName(); + dto.assignee = task.getAssignee(); + dto.created = task.getCreateTime(); + dto.due = task.getDueDate(); + dto.followUp = task.getFollowUpDate(); + dto.delegationState = task.getDelegationState(); + dto.description = task.getDescription(); + dto.executionId = task.getExecutionId(); + dto.owner = task.getOwner(); + dto.parentTaskId = task.getParentTaskId(); + dto.priority = task.getPriority(); + dto.processDefinitionId = task.getProcessDefinitionId(); + dto.processInstanceId = task.getProcessInstanceId(); + dto.taskDefinitionKey = task.getTaskDefinitionKey(); + dto.caseDefinitionId = task.getCaseDefinitionId(); + dto.caseExecutionId = task.getCaseExecutionId(); + dto.caseInstanceId = task.getCaseInstanceId(); + dto.suspended = task.isSuspended(); + dto.tenantId = task.getTenantId(); + try { + dto.formKey = task.getFormKey(); + dto.camundaFormRef = task.getCamundaFormRef(); + } + catch (BadUserRequestException e) { + // ignore (initializeFormKeys was not called) + } + + // links + dto.linker.createLink(REL_SELF, task.getId()); + dto.linker.createLink(REL_ASSIGNEE, task.getAssignee()); + dto.linker.createLink(REL_OWNER, task.getOwner()); + dto.linker.createLink(REL_EXECUTION,task.getExecutionId()); + dto.linker.createLink(REL_PARENT_TASK, task.getParentTaskId()); + dto.linker.createLink(REL_PROCESS_DEFINITION, task.getProcessDefinitionId()); + dto.linker.createLink(REL_PROCESS_INSTANCE, task.getProcessInstanceId()); + dto.linker.createLink(REL_CASE_INSTANCE, task.getCaseInstanceId()); + dto.linker.createLink(REL_CASE_EXECUTION, task.getCaseExecutionId()); + dto.linker.createLink(REL_CASE_DEFINITION, task.getCaseDefinitionId()); + dto.linker.createLink(REL_IDENTITY_LINKS, task.getId()); + + return dto; + } + + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getAssignee() { + return assignee; + } + + public Date getCreated() { + return created; + } + + public Date getDue() { + return due; + } + + public DelegationState getDelegationState() { + return delegationState; + } + + public String getDescription() { + return description; + } + + public String getExecutionId() { + return executionId; + } + + public String getOwner() { + return owner; + } + + public String getParentTaskId() { + return parentTaskId; + } + + public int getPriority() { + return priority; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getTaskDefinitionKey() { + return taskDefinitionKey; + } + + public Date getFollowUp() { + return followUp; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public boolean isSuspended() { + return suspended; + } + + public String getFormKey() { + return formKey; + } + + public CamundaFormRef getCamundaFormRef() { + return camundaFormRef; + } + + public String getTenantId() { + return tenantId; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/task/HalTaskList.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/task/HalTaskList.java new file mode 100644 index 0000000000000000000000000000000000000000..12f68c3b1ed95a17f2ba42c5614523cc10260302 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/task/HalTaskList.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.task; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.hal.HalCollectionResource; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.task.Task; + +import java.util.ArrayList; +import java.util.List; + +import static javax.ws.rs.core.UriBuilder.fromPath; + +/** + * @author Daniel Meyer + * + */ +public class HalTaskList extends HalCollectionResource { + + public static HalTaskList generate(List tasks, long count, ProcessEngine engine) { + return fromTaskList(tasks, count) + .embed(HalTask.REL_ASSIGNEE, engine) + .embed(HalTask.REL_OWNER, engine) + .embed(HalTask.REL_PROCESS_DEFINITION, engine) + .embed(HalTask.REL_CASE_DEFINITION, engine); + } + + public static HalTaskList fromTaskList(List tasks, long count) { + + HalTaskList taskList = new HalTaskList(); + + // embed tasks + List> embeddedTasks = new ArrayList>(); + for (Task task : tasks) { + embeddedTasks.add(HalTask.fromTask(task)); + } + + taskList.addEmbedded("task", embeddedTasks); + + // links + taskList.addLink("self", fromPath(TaskRestService.PATH).build()); + + taskList.count = count; + + return taskList; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/tenant/HalTenant.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/tenant/HalTenant.java new file mode 100644 index 0000000000000000000000000000000000000000..56d5a347e77a200f1b1a0b686d5fae943a6bf4ba --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/tenant/HalTenant.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.tenant; + +import javax.ws.rs.core.UriBuilder; + +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.hal.HalIdResource; +import org.camunda.bpm.engine.rest.hal.HalRelation; +import org.camunda.bpm.engine.rest.hal.HalResource; + +public class HalTenant extends HalResource implements HalIdResource { + + public final static HalRelation REL_SELF = + HalRelation.build("self", TenantRestService.class, UriBuilder.fromPath(TenantRestService.PATH).path("{id}")); + + protected String id; + protected String name; + + public static HalTenant fromTenant(Tenant tenant) { + HalTenant halTenant = new HalTenant(); + + halTenant.id = tenant.getId(); + halTenant.name = tenant.getName(); + + halTenant.linker.createLink(REL_SELF, tenant.getId()); + + return halTenant; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUser.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUser.java new file mode 100644 index 0000000000000000000000000000000000000000..20c7b24477515f7a607ce4a7eaf7161667b90160 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUser.java @@ -0,0 +1,73 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.user; + +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.hal.HalIdResource; +import org.camunda.bpm.engine.rest.hal.HalRelation; +import org.camunda.bpm.engine.rest.hal.HalResource; + +import javax.ws.rs.core.UriBuilder; + +/** + * @author Daniel Meyer + * + */ +public class HalUser extends HalResource implements HalIdResource { + + public final static HalRelation REL_SELF = + HalRelation.build("self", UserRestService.class, UriBuilder.fromPath(UserRestService.PATH).path("{id}")); + + protected String id; + protected String firstName; + protected String lastName; + protected String email; + + + public static HalUser fromUser(User user) { + + HalUser halUser = new HalUser(); + + halUser.id = user.getId(); + halUser.firstName = user.getFirstName(); + halUser.lastName = user.getLastName(); + halUser.email = user.getEmail(); + + halUser.linker.createLink(REL_SELF, user.getId()); + + return halUser; + + } + + public String getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getEmail() { + return email; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUserList.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUserList.java new file mode 100644 index 0000000000000000000000000000000000000000..68142678113872b2ae62f7f22cfb7560b09f2636 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUserList.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.user; + +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.hal.HalResource; + +import javax.ws.rs.core.UriBuilder; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Daniel Meyer + * + */ +public class HalUserList extends HalResource { + + public static HalUserList fromUserList(List users) { + HalUserList result = new HalUserList(); + + List> halUsers = new ArrayList>(); + for (User user : users) { + halUsers.add(HalUser.fromUser(user)); + } + + // embedd the user list + result.addEmbedded("users", halUsers); + + // self link + result.addLink("self", UriBuilder.fromResource(UserRestService.class).build()); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUserResolver.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUserResolver.java new file mode 100644 index 0000000000000000000000000000000000000000..229eabf0fc229de7923a47bbc84d2ec3cef8d7cc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/hal/user/HalUserResolver.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.hal.user; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.hal.cache.HalIdResourceCacheLinkResolver; + +/** + * @author Daniel Meyer + * + */ +public class HalUserResolver extends HalIdResourceCacheLinkResolver { + + protected Class getHalResourceClass() { + return HalUser.class; + } + + protected List> resolveNotCachedLinks(String[] linkedIds, ProcessEngine processEngine) { + IdentityService identityService = processEngine.getIdentityService(); + + List users = identityService.createUserQuery() + .userIdIn(linkedIds) + .listPage(0, linkedIds.length); + + List> resolvedUsers = new ArrayList>(); + for (User user : users) { + resolvedUsers.add(HalUser.fromUser(user)); + } + + return resolvedUsers; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..c5235ed78616d4d15f013152597a233cb4a1cd81 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestService.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityInstanceQueryDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricActivityInstanceResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Path(HistoricActivityInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricActivityInstanceRestService { + + public static final String PATH = "/activity-instance"; + + @Path("/{id}") + HistoricActivityInstanceResource getHistoricCaseInstance(@PathParam("id") String activityInstanceId); + + /** + * Exposes the {@link HistoricActivityInstanceQuery} interface as a REST + * service. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricActivityInstances(@Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + /** + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricActivityInstances(HistoricActivityInstanceQueryDto query, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricActivityInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryHistoricActivityInstancesCount(HistoricActivityInstanceQueryDto query); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..355bc2e3ebda2c23a493d86770085f24c0940d2b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestService.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.batch.CleanableHistoricBatchReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchDto; +import org.camunda.bpm.engine.rest.dto.history.batch.removaltime.SetRemovalTimeToHistoricBatchesDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricBatchResource; + +@Path(HistoricBatchRestService.PATH) +public interface HistoricBatchRestService { + + String PATH = "/batch"; + + @Path("/{id}") + HistoricBatchResource getHistoricBatch(@PathParam("id") String batchId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricBatches(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricBatchesCount(@Context UriInfo uriInfo); + + @GET + @Path("/cleanable-batch-report") + @Produces(MediaType.APPLICATION_JSON) + List getCleanableHistoricBatchesReport(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/cleanable-batch-report/count") + @Produces(MediaType.APPLICATION_JSON) + public CountResultDto getCleanableHistoricBatchesReportCount(@Context UriInfo uriInfo); + + @POST + @Path("/set-removal-time") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricBatchesDto dto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..44a2514436ca3db3290581b60a5d516c7f06d9ff --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestService.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.history.HistoricCaseActivityInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseActivityInstanceDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricCaseActivityInstanceResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Path(HistoricCaseActivityInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricCaseActivityInstanceRestService { + + public static final String PATH = "/case-activity-instance"; + + @Path("/{id}") + HistoricCaseActivityInstanceResource getHistoricCaseInstance(@PathParam("id") String caseActivityInstanceId); + + /** + * Exposes the {@link HistoricCaseActivityInstanceQuery} interface as a REST service. + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricCaseActivityInstances(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricCaseActivityInstancesCount(@Context UriInfo uriInfo); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..f7f36d94cfdc2673d6b83531ff161416cfd1bbe1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseDefinitionRestService.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseActivityStatisticsDto; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricCaseInstanceReportResultDto; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +/** + * @author Roman Smirnov + * + */ +@Path(HistoricCaseDefinitionRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricCaseDefinitionRestService { + + public static final String PATH = "/case-definition"; + + @GET + @Path("/{id}/statistics") + @Produces(MediaType.APPLICATION_JSON) + public List getHistoricCaseActivityStatistics(@PathParam("id") String caseDefinitionId); + + @GET + @Path("/cleanable-case-instance-report") + @Produces(MediaType.APPLICATION_JSON) + public List getCleanableHistoricCaseInstanceReport(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/cleanable-case-instance-report/count") + @Produces(MediaType.APPLICATION_JSON) + public CountResultDto getCleanableHistoricCaseInstanceReportCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..b04ce7cd6fcc06bebd160605a41c4d1b47186a08 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestService.java @@ -0,0 +1,68 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.history.HistoricCaseInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseInstanceQueryDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricCaseInstanceResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Path(HistoricCaseInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricCaseInstanceRestService { + + public static final String PATH = "/case-instance"; + + @Path("/{id}") + HistoricCaseInstanceResource getHistoricCaseInstance(@PathParam("id") String caseInstanceId); + + /** + * Exposes the {@link HistoricCaseInstanceQuery} interface as a REST + * service. + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricCaseInstances(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricCaseInstances(HistoricCaseInstanceQueryDto query, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricCaseInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryHistoricCaseInstancesCount(HistoricCaseInstanceQueryDto query); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..86857c8ae13e7a3a372d8e81e473b9299bc81667 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionDefinitionRestService.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricDecisionInstanceReportResultDto; + +@Path(HistoricDecisionDefinitionRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricDecisionDefinitionRestService { + + public static final String PATH = "/decision-definition"; + + @GET + @Path("/cleanable-decision-instance-report") + @Produces(MediaType.APPLICATION_JSON) + public List getCleanableHistoricDecisionInstanceReport(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/cleanable-decision-instance-report/count") + @Produces(MediaType.APPLICATION_JSON) + public CountResultDto getCleanableHistoricDecisionInstanceReportCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..8bfe61976e464a3c71fe72e5353da70508bee964 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestService.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.history.HistoricDecisionInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.batch.removaltime.SetRemovalTimeToHistoricDecisionInstancesDto; +import org.camunda.bpm.engine.rest.dto.history.batch.DeleteHistoricDecisionInstancesDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricDecisionInstanceResource; + +@Path(HistoricDecisionInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricDecisionInstanceRestService { + + public static final String PATH = "/decision-instance"; + + @Path("/{id}") + HistoricDecisionInstanceResource getHistoricDecisionInstance(@PathParam("id") String decisionInstanceId); + + /** + * Exposes the {@link HistoricDecisionInstanceQuery} interface as a REST + * service. + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricDecisionInstances(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricDecisionInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/delete") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto deleteAsync(DeleteHistoricDecisionInstancesDto dto); + + @POST + @Path("/set-removal-time") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricDecisionInstancesDto dto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionStatisticsRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionStatisticsRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..9e980319b57ad39072aa384b05faec3f5e37d6d1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDecisionStatisticsRestService.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceStatisticsDto; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import java.util.List; + +/** + * @author Askar Akhmerov + */ +@Path(HistoricDecisionStatisticsRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricDecisionStatisticsRestService { + public static final String PATH = "/decision-requirements-definition"; + + @GET + @Path("/{id}/statistics") + @Produces(MediaType.APPLICATION_JSON) + List getDecisionStatistics(@PathParam("id") String decisionRequirementsDefinitionId, + @QueryParam("decisionInstanceId") String decisionInstanceId); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..9855bbad31a7beb21089c4eb2d9f186e0df4d535 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestService.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDetailDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDetailQueryDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.history.HistoricDetailResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * + * @author Roman Smirnov + * + */ +@Path(HistoricVariableInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricDetailRestService { + + public static final String PATH = "/detail"; + + @Path("/{id}") + HistoricDetailResource historicDetail(@PathParam("id") String detailId); + + /** + * Exposes the {@link HistoricActivityInstanceQuery} interface as a REST + * service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricDetails( + @Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValues); + + /** + * Exposes the {@link HistoricActivityInstanceQuery} interface as a REST + * service with additional query parameters (compared to the GET alternative). + * + * @param queryDto + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricDetails( + HistoricDetailQueryDto queryDto, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValues); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricDetailsCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..7f317e57560f48715bcbf33e5612e6f9dad978de --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestService.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricExternalTaskLogDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricExternalTaskLogQueryDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricExternalTaskLogResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @since 7.7 + */ +@Path(HistoricExternalTaskLogRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricExternalTaskLogRestService { + + public static final String PATH = "/external-task-log"; + + @Path("/{id}") + HistoricExternalTaskLogResource getHistoricExternalTaskLog(@PathParam("id") String historicExternalTaskLogId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricExternalTaskLogs(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricExternalTaskLogs(HistoricExternalTaskLogQueryDto queryDto, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricExternalTaskLogsCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryHistoricExternalTaskLogsCount(HistoricExternalTaskLogQueryDto queryDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricIdentityLinkLogRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricIdentityLinkLogRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..afb29e702561b4bcd04b2d251443ad8510aca694 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricIdentityLinkLogRestService.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricIdentityLinkLogDto; + +/** + * @author Deivarayan Azhagappan + * + */ +@Path(HistoricIdentityLinkLogRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricIdentityLinkLogRestService { + + public static final String PATH = "/identity-link-log"; + + /** + * Exposes the {@link HistoricIdentityLinkLogQuery} interface as a REST service. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricIdentityLinks(@Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricIdentityLinksCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricIncidentRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricIncidentRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..9319aba9f43c1c53c5aba4ae4562b68a78ba7c76 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricIncidentRestService.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricIncidentDto; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author Roman Smirnov + * + */ +@Path(HistoricIncidentRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricIncidentRestService { + + + public static final String PATH = "/incident"; + + /** + * Exposes the {@link HistoricActivityInstanceQuery} interface as a REST + * service. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricIncidents(@Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricIncidentsCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..65b9d86e51a3a6392debf3b0a0eebc78ec856a00 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestService.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricJobLogDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricJobLogQueryDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricJobLogResource; + +/** + * @author Roman Smirnov + * + * @since 7.3 + * + */ +@Path(HistoricJobLogRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricJobLogRestService { + + public static final String PATH = "/job-log"; + + @Path("/{id}") + HistoricJobLogResource getHistoricJobLog(@PathParam("id") String historicJobLogId); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricJobLogs(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricJobLogs(HistoricJobLogQueryDto queryDto, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricJobLogsCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryHistoricJobLogsCount(HistoricJobLogQueryDto queryDto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricProcessDefinitionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricProcessDefinitionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..9b503868ba27f002122ba683a42690996c8ea8d7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricProcessDefinitionRestService.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricProcessInstanceReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityStatisticsDto; + +/** +* +* @author Roman Smirnov +* +*/ +@Path(HistoricProcessDefinitionRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricProcessDefinitionRestService { + + public static final String PATH = "/process-definition"; + + @GET + @Path("/{id}/statistics") + @Produces(MediaType.APPLICATION_JSON) + public List getHistoricActivityStatistics(@Context UriInfo uriInfo, @PathParam("id") String processDefinitionId); + + @GET + @Path("/cleanable-process-instance-report") + @Produces(MediaType.APPLICATION_JSON) + public List getCleanableHistoricProcessInstanceReport(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/cleanable-process-instance-report/count") + @Produces(MediaType.APPLICATION_JSON) + public CountResultDto getCleanableHistoricProcessInstanceReportCount(@Context UriInfo uriInfo); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..fd6481f98b60adfff7c1e0cdfd7d148179016a54 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestService.java @@ -0,0 +1,110 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.DeleteHistoricProcessInstancesDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.history.batch.removaltime.SetRemovalTimeToHistoricProcessInstancesDto; +import org.camunda.bpm.engine.rest.sub.history.HistoricProcessInstanceResource; + +@Path(HistoricProcessInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricProcessInstanceRestService { + + public static final String PATH = "/process-instance"; + + @Path("/{id}") + HistoricProcessInstanceResource getHistoricProcessInstance(@PathParam("id") String processInstanceId); + + /** + * Exposes the {@link HistoricProcessInstanceQuery} interface as a REST + * service. + * + * @param uriInfo + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricProcessInstances(@Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + /** + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricProcessInstances(HistoricProcessInstanceQueryDto query, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricProcessInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryHistoricProcessInstancesCount(HistoricProcessInstanceQueryDto query); + + @GET + @Path("/report") + @Produces({ MediaType.APPLICATION_JSON, "text/csv", "application/csv" }) + Response getHistoricProcessInstancesReport(@Context UriInfo uriInfo, @Context Request request); + + @POST + @Path("/delete") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto deleteAsync(DeleteHistoricProcessInstancesDto dto); + + @POST + @Path("/set-removal-time") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricProcessInstancesDto dto); + + @DELETE + @Path("/{id}/variable-instances") + Response deleteHistoricVariableInstancesByProcessInstanceId(@PathParam("id") String processInstanceId); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceReportService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceReportService.java new file mode 100644 index 0000000000000000000000000000000000000000..733057a2b867135eb15fcd3643032cc85419c2b7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceReportService.java @@ -0,0 +1,53 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.ReportResultDto; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author Stefan Hentschel. + */ +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricTaskInstanceReportService { + + String PATH = "/report"; + + /** + * creates a historic task instance report + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getTaskReportResults(@Context UriInfo uriInfo); + + /** + * creates a historic task instance duration report. + */ + @GET + @Path("/duration") + @Produces(MediaType.APPLICATION_JSON) + List getTaskDurationReportResults(@Context UriInfo uriInfo); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..94ae55fbfe265101052987da9e09c53f5f52f364 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceRestService.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceQueryDto; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * @author Roman Smirnov + * + */ +@Path(HistoricVariableInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricTaskInstanceRestService { + + public static final String PATH = "/task"; + + /** + * Exposes the {@link HistoricTaskInstanceQuery} interface as a REST + * service. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricTaskInstances(@Context UriInfo uriInfo, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + /** + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricTaskInstances(HistoricTaskInstanceQueryDto queryDto, @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricTaskInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryHistoricTaskInstancesCount(HistoricTaskInstanceQueryDto queryDto); + + /** + * Provides a report sub module + */ + @GET + @Path("report") + @Produces(MediaType.APPLICATION_JSON) + Response getHistoricTaskInstanceReport(@Context UriInfo uriInfo); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..34435b618d99d88f532cce04d134de165f7a9e7b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestService.java @@ -0,0 +1,83 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricVariableInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricVariableInstanceQueryDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.history.HistoricVariableInstanceResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +@Path(HistoricVariableInstanceRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoricVariableInstanceRestService { + + public static final String PATH = "/variable-instance"; + + @Path("/{id}") + HistoricVariableInstanceResource variableInstanceResource(@PathParam("id") String id); + + /** + * Exposes the {@link HistoricVariableInstanceQuery} interface as a REST + * service. + * + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + List getHistoricVariableInstances( + @Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeValues); + + /** + * @param query + * @param firstResult + * @param maxResults + * @return + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List queryHistoricVariableInstances( + HistoricVariableInstanceQueryDto query, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeValues); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto getHistoricVariableInstancesCount(@Context UriInfo uriInfo); + + @POST + @Path("/count") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryHistoricVariableInstancesCount(HistoricVariableInstanceQueryDto query); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoryCleanupRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoryCleanupRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..e604d0f9ff704492b68b6dba28debbd29167325b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoryCleanupRestService.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import java.util.List; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.history.HistoryCleanupConfigurationDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDto; + +public interface HistoryCleanupRestService { + + public static final String PATH = "/cleanup"; + + @POST + @Produces(MediaType.APPLICATION_JSON) + JobDto cleanupAsync(@QueryParam("immediatelyDue") @DefaultValue("true") boolean immediatelyDue); + + @GET + @Path("/job") + @Produces(MediaType.APPLICATION_JSON) + JobDto findCleanupJob(); + + @GET + @Path("/jobs") + @Produces(MediaType.APPLICATION_JSON) + List findCleanupJobs(); + + @GET + @Path("/configuration") + @Produces(MediaType.APPLICATION_JSON) + HistoryCleanupConfigurationDto getHistoryCleanupConfiguration(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoryRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoryRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..9070b5937341ff8c1ac95257fc767185302249e6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/HistoryRestService.java @@ -0,0 +1,85 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path(HistoryRestService.PATH) +@Produces(MediaType.APPLICATION_JSON) +public interface HistoryRestService { + + public static final String PATH = "/history"; + + @Path(HistoricProcessInstanceRestService.PATH) + HistoricProcessInstanceRestService getProcessInstanceService(); + + @Path(HistoricCaseInstanceRestService.PATH) + HistoricCaseInstanceRestService getCaseInstanceService(); + + @Path(HistoricActivityInstanceRestService.PATH) + HistoricActivityInstanceRestService getActivityInstanceService(); + + @Path(HistoricCaseActivityInstanceRestService.PATH) + HistoricCaseActivityInstanceRestService getCaseActivityInstanceService(); + + @Path(HistoricVariableInstanceRestService.PATH) + HistoricVariableInstanceRestService getVariableInstanceService(); + + @Path(HistoricProcessDefinitionRestService.PATH) + HistoricProcessDefinitionRestService getProcessDefinitionService(); + + @Path(HistoricDecisionDefinitionRestService.PATH) + HistoricDecisionDefinitionRestService getDecisionDefinitionService(); + + @Path(HistoricCaseDefinitionRestService.PATH) + HistoricCaseDefinitionRestService getCaseDefinitionService(); + + @Path(HistoricDecisionStatisticsRestService.PATH) + HistoricDecisionStatisticsRestService getDecisionStatisticsService(); + + @Path(UserOperationLogRestService.PATH) + UserOperationLogRestService getUserOperationLogRestService(); + + @Path(HistoricDetailRestService.PATH) + HistoricDetailRestService getDetailService(); + + @Path(HistoricTaskInstanceRestService.PATH) + HistoricTaskInstanceRestService getTaskInstanceService(); + + @Path(HistoricIncidentRestService.PATH) + HistoricIncidentRestService getIncidentService(); + + @Path(HistoricJobLogRestService.PATH) + HistoricJobLogRestService getJobLogService(); + + @Path(HistoricDecisionInstanceRestService.PATH) + HistoricDecisionInstanceRestService getDecisionInstanceService(); + + @Path(HistoricIdentityLinkLogRestService.PATH) + HistoricIdentityLinkLogRestService getIdentityLinkService(); + + @Path(HistoricBatchRestService.PATH) + HistoricBatchRestService getBatchService(); + + @Path(HistoricExternalTaskLogRestService.PATH) + HistoricExternalTaskLogRestService getExternalTaskLogService(); + + @Path(HistoryCleanupRestService.PATH) + HistoryCleanupRestService getHistoryCleanupRestService(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/UserOperationLogRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/UserOperationLogRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..12bccab0cd01abb8ada00adf7adba2c23720ce66 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/history/UserOperationLogRestService.java @@ -0,0 +1,68 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.UserOperationLogEntryDto; +import org.camunda.bpm.engine.rest.dto.AnnotationDto; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.List; + +/** + * Exposes the {@link org.camunda.bpm.engine.history.UserOperationLogQuery} as REST service. + * + * @author Danny Gräf + */ +@Path(UserOperationLogRestService.PATH) +public interface UserOperationLogRestService { + + public static final String PATH = "/user-operation"; + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto queryUserOperationCount(@Context UriInfo uriInfo); + + @GET + @Produces(MediaType.APPLICATION_JSON) + List queryUserOperationEntries(@Context UriInfo uriInfo, + @QueryParam("firstResult") Integer firstResult, + @QueryParam("maxResults") Integer maxResults); + + @PUT + @Path("/{operationId}/set-annotation") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + Response setAnnotation(@PathParam("operationId") String operationId, AnnotationDto annotationDto); + + @PUT + @Path("/{operationId}/clear-annotation") + @Produces(MediaType.APPLICATION_JSON) + Response clearAnnotation(@PathParam("operationId") String operationId); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractAuthorizedRestResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractAuthorizedRestResource.java new file mode 100644 index 0000000000000000000000000000000000000000..6948d70ba9ba25f14e6067b2bbba368b136fca92 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractAuthorizedRestResource.java @@ -0,0 +1,70 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.impl.identity.Authentication; + +/** + * @author Daniel Meyer + * + */ +public abstract class AbstractAuthorizedRestResource extends AbstractRestProcessEngineAware { + + protected final Resource resource; + protected final String resourceId; + + public AbstractAuthorizedRestResource(String processEngineName, Resource resource, String resourceId, ObjectMapper objectMapper) { + super(processEngineName, objectMapper); + this.resource = resource; + this.resourceId = resourceId; + } + + protected boolean isAuthorized(Permission permission, Resource resource, String resourceId) { + ProcessEngine processEngine = getProcessEngine(); + if (!processEngine.getProcessEngineConfiguration().isAuthorizationEnabled()) { + // if authorization is disabled everyone is authorized + return true; + } + + final IdentityService identityService = processEngine.getIdentityService(); + final AuthorizationService authorizationService = processEngine.getAuthorizationService(); + + Authentication authentication = identityService.getCurrentAuthentication(); + if(authentication == null) { + return true; + + } else { + return authorizationService + .isUserAuthorized(authentication.getUserId(), authentication.getGroupIds(), permission, resource, resourceId); + } + } + + protected boolean isAuthorized(Permission permission, Resource resource) { + return isAuthorized(permission, resource, resourceId); + } + + protected boolean isAuthorized(Permission permission) { + return isAuthorized(permission, resource); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractProcessEngineRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractProcessEngineRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a4ebe99710eb5018f7fcccf2c8949fca96796661 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractProcessEngineRestServiceImpl.java @@ -0,0 +1,324 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.net.URI; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Providers; + +import org.camunda.bpm.engine.rest.AuthorizationRestService; +import org.camunda.bpm.engine.rest.BatchRestService; +import org.camunda.bpm.engine.rest.CaseDefinitionRestService; +import org.camunda.bpm.engine.rest.CaseExecutionRestService; +import org.camunda.bpm.engine.rest.CaseInstanceRestService; +import org.camunda.bpm.engine.rest.ConditionRestService; +import org.camunda.bpm.engine.rest.DecisionDefinitionRestService; +import org.camunda.bpm.engine.rest.DecisionRequirementsDefinitionRestService; +import org.camunda.bpm.engine.rest.DeploymentRestService; +import org.camunda.bpm.engine.rest.EventSubscriptionRestService; +import org.camunda.bpm.engine.rest.ExecutionRestService; +import org.camunda.bpm.engine.rest.ExternalTaskRestService; +import org.camunda.bpm.engine.rest.FilterRestService; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.IdentityRestService; +import org.camunda.bpm.engine.rest.IncidentRestService; +import org.camunda.bpm.engine.rest.JobDefinitionRestService; +import org.camunda.bpm.engine.rest.JobRestService; +import org.camunda.bpm.engine.rest.MessageRestService; +import org.camunda.bpm.engine.rest.MetricsRestService; +import org.camunda.bpm.engine.rest.MigrationRestService; +import org.camunda.bpm.engine.rest.ModificationRestService; +import org.camunda.bpm.engine.rest.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.ProcessInstanceRestService; +import org.camunda.bpm.engine.rest.SchemaLogRestService; +import org.camunda.bpm.engine.rest.SignalRestService; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.TelemetryRestService; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.VariableInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoryRestService; +import org.camunda.bpm.engine.rest.impl.history.HistoryRestServiceImpl; +import org.camunda.bpm.engine.rest.impl.optimize.OptimizeRestService; +import org.camunda.bpm.engine.rest.util.ProvidersUtil; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + *

Abstract process engine resource that provides instantiations of all REST resources.

+ * + *

Subclasses can add JAX-RS to methods as required annotations. For example, if only + * the process definition resource should be exposed, it is sufficient to add JAX-RS annotations to that + * resource. The engineName parameter of all the provided methods may be null + * to instantiate a resource for the default engine.

+ * + * @author Thorben Lindhauer + */ +public abstract class AbstractProcessEngineRestServiceImpl { + + @Context + protected Providers providers; + + public ProcessDefinitionRestService getProcessDefinitionService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + ProcessDefinitionRestServiceImpl subResource = new ProcessDefinitionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public ProcessInstanceRestService getProcessInstanceService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + ProcessInstanceRestServiceImpl subResource = new ProcessInstanceRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public ExecutionRestService getExecutionService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + ExecutionRestServiceImpl subResource = new ExecutionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public TaskRestService getTaskRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + TaskRestServiceImpl subResource = new TaskRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + + return subResource; + } + + public IdentityRestService getIdentityRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + IdentityRestServiceImpl subResource = new IdentityRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public MessageRestService getMessageRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + MessageRestServiceImpl subResource = new MessageRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public VariableInstanceRestService getVariableInstanceService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + VariableInstanceRestServiceImpl subResource = new VariableInstanceRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public JobDefinitionRestService getJobDefinitionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + JobDefinitionRestServiceImpl subResource = new JobDefinitionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public JobRestService getJobRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + JobRestServiceImpl subResource = new JobRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public GroupRestService getGroupRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + GroupRestServiceImpl subResource = new GroupRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public UserRestService getUserRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + UserRestServiceImpl subResource = new UserRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public AuthorizationRestService getAuthorizationRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + AuthorizationRestServiceImpl subResource = new AuthorizationRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public IncidentRestService getIncidentService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + IncidentRestServiceImpl subResource = new IncidentRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public HistoryRestService getHistoryRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + HistoryRestServiceImpl subResource = new HistoryRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public DeploymentRestService getDeploymentRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + DeploymentRestServiceImpl subResource = new DeploymentRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public CaseDefinitionRestService getCaseDefinitionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + CaseDefinitionRestServiceImpl subResource = new CaseDefinitionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public CaseInstanceRestService getCaseInstanceRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + CaseInstanceRestServiceImpl subResource = new CaseInstanceRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public CaseExecutionRestService getCaseExecutionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + CaseExecutionRestServiceImpl subResource = new CaseExecutionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public FilterRestService getFilterRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + FilterRestServiceImpl subResource = new FilterRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public MetricsRestService getMetricsRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + MetricsRestServiceImpl subResource = new MetricsRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public DecisionDefinitionRestService getDecisionDefinitionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + DecisionDefinitionRestServiceImpl subResource = new DecisionDefinitionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public DecisionRequirementsDefinitionRestService getDecisionRequirementsDefinitionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + DecisionRequirementsDefinitionRestServiceImpl subResource = new DecisionRequirementsDefinitionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public ExternalTaskRestService getExternalTaskRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + ExternalTaskRestServiceImpl subResource = new ExternalTaskRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public MigrationRestService getMigrationRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + MigrationRestServiceImpl subResource = new MigrationRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public ModificationRestService getModificationRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + ModificationRestServiceImpl subResource = new ModificationRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public BatchRestService getBatchRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + BatchRestServiceImpl subResource = new BatchRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public TenantRestService getTenantRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + TenantRestServiceImpl subResource = new TenantRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public SignalRestService getSignalRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + SignalRestServiceImpl subResource = new SignalRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public ConditionRestService getConditionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + ConditionRestServiceImpl subResource = new ConditionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public OptimizeRestService getOptimizeRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + OptimizeRestService subResource = new OptimizeRestService(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public VersionRestService getVersionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + VersionRestService subResource = new VersionRestService(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public SchemaLogRestService getSchemaLogRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + SchemaLogRestServiceImpl subResource = new SchemaLogRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public EventSubscriptionRestService getEventSubscriptionRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + EventSubscriptionRestServiceImpl subResource = new EventSubscriptionRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + public TelemetryRestService getTelemetryRestService(String engineName) { + String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); + TelemetryRestServiceImpl subResource = new TelemetryRestServiceImpl(engineName, getObjectMapper()); + subResource.setRelativeRootResourceUri(rootResourcePath); + return subResource; + } + + protected abstract URI getRelativeEngineUri(String engineName); + + protected ObjectMapper getObjectMapper() { + return ProvidersUtil + .resolveFromContext(providers, ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE, this.getClass()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractRestProcessEngineAware.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractRestProcessEngineAware.java new file mode 100644 index 0000000000000000000000000000000000000000..ca6d19c9310c13f09c3ccf8af4d5218e59b90e0a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AbstractRestProcessEngineAware.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.EngineUtil; + +public abstract class AbstractRestProcessEngineAware { + + /* + * private to enforce the use of getProcessEngine in subclasses + * for consistent error handling for unknown process engines + */ + private ProcessEngine processEngine; + + protected ObjectMapper objectMapper; + + protected String relativeRootResourcePath = "/"; + + public AbstractRestProcessEngineAware(String engineName, final ObjectMapper objectMapper) { + this.processEngine = EngineUtil.lookupProcessEngine(engineName); + this.objectMapper = objectMapper; + } + + /** + * Override the root resource path, if this resource is a sub-resource. + * The relative root resource path is used for generation of links to resources in results. + * + * @param relativeRootResourcePath + */ + public void setRelativeRootResourceUri(String relativeRootResourcePath) { + this.relativeRootResourcePath = relativeRootResourcePath; + } + + protected ObjectMapper getObjectMapper() { + return objectMapper; + } + + protected ProcessEngine getProcessEngine() { + if (processEngine == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "No process engine available"); + } + return processEngine; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AuthorizationRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AuthorizationRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..ab75b4497b13a3c19aaea432293662f244b541a4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/AuthorizationRestServiceImpl.java @@ -0,0 +1,209 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Resources.AUTHORIZATION; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.AuthorizationQuery; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Permissions; +import org.camunda.bpm.engine.authorization.Resources; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.AuthorizationRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCheckResultDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationCreateDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.authorization.AuthorizationResource; +import org.camunda.bpm.engine.rest.sub.authorization.impl.AuthorizationResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.rest.util.ResourceUtil; + +/** + * @author Daniel Meyer + * + */ +public class AuthorizationRestServiceImpl extends AbstractAuthorizedRestResource implements AuthorizationRestService { + + public AuthorizationRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName,AUTHORIZATION, ANY, objectMapper); + } + + @Override + public AuthorizationCheckResultDto isUserAuthorized(String permissionName, String resourceName, Integer resourceType, String resourceId, String userId) { + + // validate request: + if(permissionName == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Query parameter 'permissionName' cannot be null"); + + } else if(resourceName == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Query parameter 'resourceName' cannot be null"); + + } else if(resourceType == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Query parameter 'resourceType' cannot be null"); + + } + + final Authentication currentAuthentication = getProcessEngine().getIdentityService().getCurrentAuthentication(); + if(currentAuthentication == null) { + throw new InvalidRequestException(Status.UNAUTHORIZED, "You must be authenticated in order to use this resource."); + } + + final AuthorizationService authorizationService = getProcessEngine().getAuthorizationService(); + + ResourceUtil resource = new ResourceUtil(resourceName, resourceType); + ProcessEngineConfigurationImpl processEngineConfiguration = (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + Permission permission = processEngineConfiguration.getPermissionProvider().getPermissionForName(permissionName, resourceType); + String currentUserId = currentAuthentication.getUserId(); + + boolean isUserAuthorized = false; + + String userIdToCheck; + List groupIdsToCheck = new ArrayList<>(); + + if(userId != null && !userId.equals(currentUserId)) { + boolean isCurrentUserAuthorized = authorizationService.isUserAuthorized(currentUserId, currentAuthentication.getGroupIds(), Permissions.READ, Resources.AUTHORIZATION); + if (!isCurrentUserAuthorized) { + throw new InvalidRequestException(Status.FORBIDDEN, "You must have READ permission for Authorization resource."); + } + userIdToCheck = userId; + groupIdsToCheck = getUserGroups(userId); + } else { + // userId == null || userId.equals(currentUserId) + userIdToCheck = currentUserId; + groupIdsToCheck = currentAuthentication.getGroupIds(); + } + + if(resourceId == null || Authorization.ANY.equals(resourceId)) { + isUserAuthorized = authorizationService.isUserAuthorized(userIdToCheck, groupIdsToCheck, permission, resource); + } else { + isUserAuthorized = authorizationService.isUserAuthorized(userIdToCheck, groupIdsToCheck, permission, resource, resourceId); + } + + return new AuthorizationCheckResultDto(isUserAuthorized, permissionName, resource, resourceId); + } + + @Override + public AuthorizationResource getAuthorization(String id) { + return new AuthorizationResourceImpl(getProcessEngine().getName(), id, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List queryAuthorizations(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + AuthorizationQueryDto queryDto = new AuthorizationQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryAuthorizations(queryDto, firstResult, maxResults); + } + + @Override + public ResourceOptionsDto availableOperations(UriInfo context) { + + UriBuilder baseUriBuilder = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(AuthorizationRestService.PATH); + + ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); + + // GET / + URI baseUri = baseUriBuilder.build(); + resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); + + // GET /count + URI countUri = baseUriBuilder.clone().path("/count").build(); + resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); + + // POST /create + if(isAuthorized(CREATE)) { + URI createUri = baseUriBuilder.clone().path("/create").build(); + resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); + } + + return resourceOptionsDto; + } + + public List queryAuthorizations(AuthorizationQueryDto queryDto, Integer firstResult, Integer maxResults) { + + queryDto.setObjectMapper(getObjectMapper()); + AuthorizationQuery query = queryDto.toQuery(getProcessEngine()); + + List resultList = QueryUtil.list(query, firstResult, maxResults); + + return AuthorizationDto.fromAuthorizationList(resultList, getProcessEngine().getProcessEngineConfiguration()); + } + + @Override + public CountResultDto getAuthorizationCount(UriInfo uriInfo) { + AuthorizationQueryDto queryDto = new AuthorizationQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return getAuthorizationCount(queryDto); + } + + protected CountResultDto getAuthorizationCount(AuthorizationQueryDto queryDto) { + AuthorizationQuery query = queryDto.toQuery(getProcessEngine()); + long count = query.count(); + return new CountResultDto(count); + } + + @Override + public AuthorizationDto createAuthorization(UriInfo context, AuthorizationCreateDto dto) { + final AuthorizationService authorizationService = getProcessEngine().getAuthorizationService(); + + Authorization newAuthorization = authorizationService.createNewAuthorization(dto.getType()); + AuthorizationCreateDto.update(dto, newAuthorization, getProcessEngine().getProcessEngineConfiguration()); + + newAuthorization = authorizationService.saveAuthorization(newAuthorization); + + return getAuthorization(newAuthorization.getId()).getAuthorization(context); + } + + // utility methods ////////////////////////////////////// + + protected IdentityService getIdentityService() { + return getProcessEngine().getIdentityService(); + } + + protected List getUserGroups(String userId) { + List userGroups = getIdentityService().createGroupQuery() + .groupMember(userId) + .unlimitedList(); + + List groupIds = new ArrayList<>(); + for (Group group : userGroups) { + groupIds.add(group.getId()); + } + + return groupIds; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/BatchRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/BatchRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..40b0ba16fe8066bdfcf8e784211266bdbe24e787 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/BatchRestServiceImpl.java @@ -0,0 +1,97 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.batch.BatchQuery; +import org.camunda.bpm.engine.batch.BatchStatistics; +import org.camunda.bpm.engine.batch.BatchStatisticsQuery; +import org.camunda.bpm.engine.rest.BatchRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchQueryDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchStatisticsDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchStatisticsQueryDto; +import org.camunda.bpm.engine.rest.sub.batch.BatchResource; +import org.camunda.bpm.engine.rest.sub.batch.impl.BatchResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class BatchRestServiceImpl extends AbstractRestProcessEngineAware implements BatchRestService { + + public BatchRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public BatchResource getBatch(String batchId) { + return new BatchResourceImpl(getProcessEngine(), batchId); + } + + @Override + public List getBatches(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + BatchQueryDto queryDto = new BatchQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + BatchQuery query = queryDto.toQuery(getProcessEngine()); + + List matchingBatches = QueryUtil.list(query, firstResult, maxResults); + + List batchResults = new ArrayList(); + for (Batch matchingBatch : matchingBatches) { + batchResults.add(BatchDto.fromBatch(matchingBatch)); + } + return batchResults; + } + + @Override + public CountResultDto getBatchesCount(UriInfo uriInfo) { + ProcessEngine processEngine = getProcessEngine(); + BatchQueryDto queryDto = new BatchQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + BatchQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + return new CountResultDto(count); + } + + @Override + public List getStatistics(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + BatchStatisticsQueryDto queryDto = new BatchStatisticsQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + BatchStatisticsQuery query = queryDto.toQuery(getProcessEngine()); + + List batchStatisticsList = QueryUtil.list(query, firstResult, maxResults); + + List statisticsResults = new ArrayList(); + for (BatchStatistics batchStatistics : batchStatisticsList) { + statisticsResults.add(BatchStatisticsDto.fromBatchStatistics(batchStatistics)); + } + + return statisticsResults; + } + + @Override + public CountResultDto getStatisticsCount(UriInfo uriInfo) { + BatchStatisticsQueryDto queryDto = new BatchStatisticsQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + BatchStatisticsQuery query = queryDto.toQuery(getProcessEngine()); + + long count = query.count(); + return new CountResultDto(count); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CamundaRestResources.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CamundaRestResources.java new file mode 100644 index 0000000000000000000000000000000000000000..bc08b6292258bbace6123928f3037f11c3a8cd9e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CamundaRestResources.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import org.camunda.bpm.engine.rest.exception.ExceptionHandler; +import org.camunda.bpm.engine.rest.exception.JsonMappingExceptionHandler; +import org.camunda.bpm.engine.rest.exception.JsonParseExceptionHandler; +import org.camunda.bpm.engine.rest.exception.ProcessEngineExceptionHandler; +import org.camunda.bpm.engine.rest.exception.RestExceptionHandler; +import org.camunda.bpm.engine.rest.hal.JacksonHalJsonProvider; +import org.camunda.bpm.engine.rest.mapper.JacksonConfigurator; +import org.camunda.bpm.engine.rest.mapper.MultipartPayloadProvider; + +import java.util.HashSet; +import java.util.Set; + +/** + *

Class providing static methods returning all the resource classes provided by Camunda Platform.

+ * + * @author Daniel Meyer + * + */ +public class CamundaRestResources { + + private static final Set> RESOURCE_CLASSES = new HashSet>(); + + private static final Set> CONFIGURATION_CLASSES = new HashSet>(); + + static { + RESOURCE_CLASSES.add(NamedProcessEngineRestServiceImpl.class); + RESOURCE_CLASSES.add(DefaultProcessEngineRestServiceImpl.class); + + CONFIGURATION_CLASSES.add(JacksonConfigurator.class); + CONFIGURATION_CLASSES.add(JacksonJsonProvider.class); + CONFIGURATION_CLASSES.add(JsonMappingExceptionHandler.class); + CONFIGURATION_CLASSES.add(JsonParseExceptionHandler.class); + CONFIGURATION_CLASSES.add(ProcessEngineExceptionHandler.class); + CONFIGURATION_CLASSES.add(RestExceptionHandler.class); + CONFIGURATION_CLASSES.add(MultipartPayloadProvider.class); + CONFIGURATION_CLASSES.add(JacksonHalJsonProvider.class); + CONFIGURATION_CLASSES.add(ExceptionHandler.class); + } + + /** + * Returns a set containing all resource classes provided by Camunda Platform. + * @return a set of resource classes. + */ + public static Set> getResourceClasses() { + return RESOURCE_CLASSES; + } + + /** + * Returns a set containing all provider / mapper / config classes used in the + * default setup of the camunda REST api. + * @return a set of provider / mapper / config classes. + */ + public static Set> getConfigurationClasses() { + return CONFIGURATION_CLASSES; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1608051c86428cbb31bb391e5b2d690ba46a0f8d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseDefinitionRestServiceImpl.java @@ -0,0 +1,122 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.rest.CaseDefinitionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.CaseDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.CaseDefinitionQueryDto; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.CaseDefinitionResource; +import org.camunda.bpm.engine.rest.sub.repository.impl.CaseDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseDefinitionRestServiceImpl extends AbstractRestProcessEngineAware implements CaseDefinitionRestService { + + public CaseDefinitionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public CaseDefinitionResource getCaseDefinitionByKey(String caseDefinitionKey) { + + CaseDefinition caseDefinition = getProcessEngine() + .getRepositoryService() + .createCaseDefinitionQuery() + .caseDefinitionKey(caseDefinitionKey) + .withoutTenantId() + .latestVersion() + .singleResult(); + + if (caseDefinition == null) { + String errorMessage = String.format("No matching case definition with key: %s and no tenant-id", caseDefinitionKey); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getCaseDefinitionById(caseDefinition.getId()); + } + } + + @Override + public CaseDefinitionResource getCaseDefinitionByKeyAndTenantId(String caseDefinitionKey, String tenantId) { + + CaseDefinition caseDefinition = getProcessEngine() + .getRepositoryService() + .createCaseDefinitionQuery() + .caseDefinitionKey(caseDefinitionKey) + .tenantIdIn(tenantId) + .latestVersion() + .singleResult(); + + if (caseDefinition == null) { + String errorMessage = String.format("No matching case definition with key: %s and tenant-id: %s", caseDefinitionKey, tenantId); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getCaseDefinitionById(caseDefinition.getId()); + } + } + + @Override + public CaseDefinitionResource getCaseDefinitionById(String caseDefinitionId) { + return new CaseDefinitionResourceImpl(getProcessEngine(), caseDefinitionId, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List getCaseDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + CaseDefinitionQueryDto queryDto = new CaseDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + List definitions = new ArrayList(); + + ProcessEngine engine = getProcessEngine(); + CaseDefinitionQuery query = queryDto.toQuery(engine); + + List matchingDefinitions = QueryUtil.list(query, firstResult, maxResults); + + for (CaseDefinition definition : matchingDefinitions) { + CaseDefinitionDto def = CaseDefinitionDto.fromCaseDefinition(definition); + definitions.add(def); + } + return definitions; + } + + @Override + public CountResultDto getCaseDefinitionsCount(UriInfo uriInfo) { + CaseDefinitionQueryDto queryDto = new CaseDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + ProcessEngine engine = getProcessEngine(); + CaseDefinitionQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseExecutionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseExecutionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..b2a550d6baf6455e891c3b8a46435705ad4a7aba --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseExecutionRestServiceImpl.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.CaseExecutionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionQueryDto; +import org.camunda.bpm.engine.rest.sub.runtime.CaseExecutionResource; +import org.camunda.bpm.engine.rest.sub.runtime.impl.CaseExecutionResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.CaseExecution; +import org.camunda.bpm.engine.runtime.CaseExecutionQuery; + +public class CaseExecutionRestServiceImpl extends AbstractRestProcessEngineAware implements CaseExecutionRestService { + + public CaseExecutionRestServiceImpl(String engineName, final ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public CaseExecutionResource getCaseExecution(String caseExecutionId) { + return new CaseExecutionResourceImpl(getProcessEngine(), caseExecutionId, getObjectMapper()); + } + + @Override + public List getCaseExecutions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryCaseExecutions(queryDto, firstResult, maxResults); + } + + @Override + public List queryCaseExecutions(CaseExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + CaseExecutionQuery query = queryDto.toQuery(engine); + + List matchingExecutions = QueryUtil.list(query, firstResult, maxResults); + + List executionResults = new ArrayList(); + for (CaseExecution execution : matchingExecutions) { + CaseExecutionDto resultExecution = CaseExecutionDto.fromCaseExecution(execution); + executionResults.add(resultExecution); + } + return executionResults; + } + + @Override + public CountResultDto getCaseExecutionsCount(UriInfo uriInfo) { + CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryCaseExecutionsCount(queryDto); + } + + @Override + public CountResultDto queryCaseExecutionsCount(CaseExecutionQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + CaseExecutionQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..05b28efd76d351d11f516b5429e75b5c888ec166 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/CaseInstanceRestServiceImpl.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.CaseInstanceRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceQueryDto; +import org.camunda.bpm.engine.rest.sub.runtime.CaseInstanceResource; +import org.camunda.bpm.engine.rest.sub.runtime.impl.CaseInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.CaseInstance; +import org.camunda.bpm.engine.runtime.CaseInstanceQuery; + +/** + * @author Roman Smirnov + * + */ +public class CaseInstanceRestServiceImpl extends AbstractRestProcessEngineAware implements CaseInstanceRestService { + + public CaseInstanceRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public CaseInstanceResource getCaseInstance(String caseInstanceId) { + return new CaseInstanceResourceImpl(getProcessEngine(), caseInstanceId, getObjectMapper()); + } + + @Override + public List getCaseInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + CaseInstanceQueryDto queryDto = new CaseInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryCaseInstances(queryDto, firstResult, maxResults); + } + + @Override + public List queryCaseInstances(CaseInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + CaseInstanceQuery query = queryDto.toQuery(engine); + + List matchingInstances = QueryUtil.list(query, firstResult, maxResults); + + List instanceResults = new ArrayList(); + for (CaseInstance instance : matchingInstances) { + CaseInstanceDto resultInstance = CaseInstanceDto.fromCaseInstance(instance); + instanceResults.add(resultInstance); + } + return instanceResults; + } + + @Override + public CountResultDto getCaseInstancesCount(UriInfo uriInfo) { + CaseInstanceQueryDto queryDto = new CaseInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryCaseInstancesCount(queryDto); + } + + @Override + public CountResultDto queryCaseInstancesCount(CaseInstanceQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + CaseInstanceQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ConditionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ConditionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..066254dd0e2f9aa613de3c1f655efb817c6bcc05 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ConditionRestServiceImpl.java @@ -0,0 +1,87 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.rest.ConditionRestService; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.condition.EvaluationConditionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.ConditionEvaluationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.variable.VariableMap; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ConditionRestServiceImpl extends AbstractRestProcessEngineAware implements ConditionRestService { + + public ConditionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public List evaluateCondition(EvaluationConditionDto conditionDto) { + if (conditionDto.getTenantId() != null && conditionDto.isWithoutTenantId()) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Parameter 'tenantId' cannot be used together with parameter 'withoutTenantId'."); + } + ConditionEvaluationBuilder builder = createConditionEvaluationBuilder(conditionDto); + List processInstances = builder.evaluateStartConditions(); + + List result = new ArrayList<>(); + for (ProcessInstance processInstance : processInstances) { + result.add(ProcessInstanceDto.fromProcessInstance(processInstance)); + } + return result; + } + + protected ConditionEvaluationBuilder createConditionEvaluationBuilder(EvaluationConditionDto conditionDto) { + RuntimeService runtimeService = getProcessEngine().getRuntimeService(); + + ObjectMapper objectMapper = getObjectMapper(); + + VariableMap variables = VariableValueDto.toMap(conditionDto.getVariables(), getProcessEngine(), objectMapper); + + ConditionEvaluationBuilder builder = runtimeService.createConditionEvaluation(); + + if (variables != null && !variables.isEmpty()) { + builder.setVariables(variables); + } + + if (conditionDto.getBusinessKey() != null) { + builder.processInstanceBusinessKey(conditionDto.getBusinessKey()); + } + + if (conditionDto.getProcessDefinitionId() != null) { + builder.processDefinitionId(conditionDto.getProcessDefinitionId()); + } + + if (conditionDto.getTenantId() != null) { + builder.tenantId(conditionDto.getTenantId()); + } else if (conditionDto.isWithoutTenantId()) { + builder.withoutTenantId(); + } + + return builder; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DecisionDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DecisionDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..c792a710643994ca83633103344167aea4c04602 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DecisionDefinitionRestServiceImpl.java @@ -0,0 +1,117 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.DecisionDefinition; +import org.camunda.bpm.engine.repository.DecisionDefinitionQuery; +import org.camunda.bpm.engine.rest.DecisionDefinitionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionDefinitionQueryDto; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.DecisionDefinitionResource; +import org.camunda.bpm.engine.rest.sub.repository.impl.DecisionDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class DecisionDefinitionRestServiceImpl extends AbstractRestProcessEngineAware implements DecisionDefinitionRestService { + + public DecisionDefinitionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public DecisionDefinitionResource getDecisionDefinitionByKey(String decisionDefinitionKey) { + + DecisionDefinition decisionDefinition = getProcessEngine() + .getRepositoryService() + .createDecisionDefinitionQuery() + .decisionDefinitionKey(decisionDefinitionKey) + .withoutTenantId() + .latestVersion() + .singleResult(); + + if (decisionDefinition == null) { + String errorMessage = String.format("No matching decision definition with key: %s and no tenant-id", decisionDefinitionKey); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getDecisionDefinitionById(decisionDefinition.getId()); + } + } + + @Override + public DecisionDefinitionResource getDecisionDefinitionByKeyAndTenantId(String decisionDefinitionKey, String tenantId) { + + DecisionDefinition decisionDefinition = getProcessEngine() + .getRepositoryService() + .createDecisionDefinitionQuery() + .decisionDefinitionKey(decisionDefinitionKey) + .tenantIdIn(tenantId) + .latestVersion() + .singleResult(); + + if (decisionDefinition == null) { + String errorMessage = String.format("No matching decision definition with key: %s and tenant-id: %s", decisionDefinitionKey, tenantId); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getDecisionDefinitionById(decisionDefinition.getId()); + } + } + + @Override + public DecisionDefinitionResource getDecisionDefinitionById(String decisionDefinitionId) { + return new DecisionDefinitionResourceImpl(getProcessEngine(), decisionDefinitionId, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List getDecisionDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + DecisionDefinitionQueryDto queryDto = new DecisionDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + List definitions = new ArrayList(); + + ProcessEngine engine = getProcessEngine(); + DecisionDefinitionQuery query = queryDto.toQuery(engine); + + List matchingDefinitions = QueryUtil.list(query, firstResult, maxResults); + + for (DecisionDefinition definition : matchingDefinitions) { + DecisionDefinitionDto def = DecisionDefinitionDto.fromDecisionDefinition(definition); + definitions.add(def); + } + return definitions; + } + + @Override + public CountResultDto getDecisionDefinitionsCount(UriInfo uriInfo) { + DecisionDefinitionQueryDto queryDto = new DecisionDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + ProcessEngine engine = getProcessEngine(); + DecisionDefinitionQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DecisionRequirementsDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DecisionRequirementsDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..22f81c93e7eaea96793ecb421fec020226a80eca --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DecisionRequirementsDefinitionRestServiceImpl.java @@ -0,0 +1,109 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinition; +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinitionQuery; +import org.camunda.bpm.engine.rest.DecisionRequirementsDefinitionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionRequirementsDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionRequirementsDefinitionQueryDto; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.DecisionRequirementsDefinitionResource; +import org.camunda.bpm.engine.rest.sub.repository.impl.DecisionRequirementsDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class DecisionRequirementsDefinitionRestServiceImpl extends AbstractRestProcessEngineAware implements DecisionRequirementsDefinitionRestService { + + public DecisionRequirementsDefinitionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public List getDecisionRequirementsDefinitions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + DecisionRequirementsDefinitionQueryDto queryDto = new DecisionRequirementsDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + List dtos = new ArrayList(); + + ProcessEngine engine = getProcessEngine(); + DecisionRequirementsDefinitionQuery query = queryDto.toQuery(engine); + + List matchingDefinitions = QueryUtil.list(query, firstResult, maxResults); + + for (DecisionRequirementsDefinition definition : matchingDefinitions) { + DecisionRequirementsDefinitionDto dto = DecisionRequirementsDefinitionDto.fromDecisionRequirementsDefinition(definition); + dtos.add(dto); + } + return dtos; + } + + @Override + public CountResultDto getDecisionRequirementsDefinitionsCount(UriInfo uriInfo) { + DecisionRequirementsDefinitionQueryDto queryDto = new DecisionRequirementsDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + ProcessEngine engine = getProcessEngine(); + DecisionRequirementsDefinitionQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + return result; + } + + @Override + public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionById(String decisionRequirementsDefinitionId) { + return new DecisionRequirementsDefinitionResourceImpl(getProcessEngine(), decisionRequirementsDefinitionId); + } + + @Override + public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKey(String decisionRequirementsDefinitionKey) { + DecisionRequirementsDefinition decisionRequirementsDefinition = getProcessEngine().getRepositoryService() + .createDecisionRequirementsDefinitionQuery() + .decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey) + .withoutTenantId().latestVersion().singleResult(); + + if (decisionRequirementsDefinition == null) { + String errorMessage = String.format("No matching decision requirements definition with key: %s and no tenant-id", decisionRequirementsDefinitionKey); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getDecisionRequirementsDefinitionById(decisionRequirementsDefinition.getId()); + } + } + + @Override + public DecisionRequirementsDefinitionResource getDecisionRequirementsDefinitionByKeyAndTenantId(String decisionRequirementsDefinitionKey, String tenantId) { + DecisionRequirementsDefinition decisionRequirementsDefinition = getProcessEngine().getRepositoryService() + .createDecisionRequirementsDefinitionQuery() + .decisionRequirementsDefinitionKey(decisionRequirementsDefinitionKey) + .tenantIdIn(tenantId).latestVersion().singleResult(); + + if (decisionRequirementsDefinition == null) { + String errorMessage = String.format("No matching decision requirements definition with key: %s and tenant-id: %s", decisionRequirementsDefinitionKey, tenantId); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getDecisionRequirementsDefinitionById(decisionRequirementsDefinition.getId()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DefaultProcessEngineRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DefaultProcessEngineRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..81d3084c2190ba241c7ed4443628ea70fcc42675 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DefaultProcessEngineRestServiceImpl.java @@ -0,0 +1,237 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.net.URI; + +import javax.ws.rs.Path; + +import org.camunda.bpm.engine.rest.AuthorizationRestService; +import org.camunda.bpm.engine.rest.BatchRestService; +import org.camunda.bpm.engine.rest.CaseDefinitionRestService; +import org.camunda.bpm.engine.rest.CaseExecutionRestService; +import org.camunda.bpm.engine.rest.CaseInstanceRestService; +import org.camunda.bpm.engine.rest.ConditionRestService; +import org.camunda.bpm.engine.rest.DecisionDefinitionRestService; +import org.camunda.bpm.engine.rest.DecisionRequirementsDefinitionRestService; +import org.camunda.bpm.engine.rest.DeploymentRestService; +import org.camunda.bpm.engine.rest.EventSubscriptionRestService; +import org.camunda.bpm.engine.rest.ExecutionRestService; +import org.camunda.bpm.engine.rest.ExternalTaskRestService; +import org.camunda.bpm.engine.rest.FilterRestService; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.IdentityRestService; +import org.camunda.bpm.engine.rest.IncidentRestService; +import org.camunda.bpm.engine.rest.JobDefinitionRestService; +import org.camunda.bpm.engine.rest.JobRestService; +import org.camunda.bpm.engine.rest.MessageRestService; +import org.camunda.bpm.engine.rest.MetricsRestService; +import org.camunda.bpm.engine.rest.MigrationRestService; +import org.camunda.bpm.engine.rest.ModificationRestService; +import org.camunda.bpm.engine.rest.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.ProcessInstanceRestService; +import org.camunda.bpm.engine.rest.SchemaLogRestService; +import org.camunda.bpm.engine.rest.SignalRestService; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.TelemetryRestService; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.VariableInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoryRestService; +import org.camunda.bpm.engine.rest.impl.optimize.OptimizeRestService; + +@Path(DefaultProcessEngineRestServiceImpl.PATH) +public class DefaultProcessEngineRestServiceImpl extends AbstractProcessEngineRestServiceImpl { + + public static final String PATH = ""; + + @Path(ProcessDefinitionRestService.PATH) + public ProcessDefinitionRestService getProcessDefinitionService() { + return super.getProcessDefinitionService(null); + } + + @Path(ProcessInstanceRestService.PATH) + public ProcessInstanceRestService getProcessInstanceService() { + return super.getProcessInstanceService(null); + } + + @Path(ExecutionRestService.PATH) + public ExecutionRestService getExecutionService() { + return super.getExecutionService(null); + } + + @Path(TaskRestService.PATH) + public TaskRestService getTaskRestService() { + return super.getTaskRestService(null); + } + + @Path(IdentityRestService.PATH) + public IdentityRestService getIdentityRestService() { + return super.getIdentityRestService(null); + } + + @Path(MessageRestService.PATH) + public MessageRestService getMessageRestService() { + return super.getMessageRestService(null); + } + + @Path(VariableInstanceRestService.PATH) + public VariableInstanceRestService getVariableInstanceService() { + return super.getVariableInstanceService(null); + } + + @Path(JobDefinitionRestService.PATH) + public JobDefinitionRestService getJobDefinitionRestService() { + return super.getJobDefinitionRestService(null); + } + + @Path(JobRestService.PATH) + public JobRestService getJobRestService() { + return super.getJobRestService(null); + } + + @Path(GroupRestService.PATH) + public GroupRestService getGroupRestService() { + return super.getGroupRestService(null); + } + + @Path(UserRestService.PATH) + public UserRestService getUserRestService() { + return super.getUserRestService(null); + } + + @Path(AuthorizationRestService.PATH) + public AuthorizationRestService getAuthorizationRestService() { + return super.getAuthorizationRestService(null); + } + + @Path(IncidentRestService.PATH) + public IncidentRestService getIncidentService() { + return super.getIncidentService(null); + } + + @Path(HistoryRestService.PATH) + public HistoryRestService getHistoryRestService() { + return super.getHistoryRestService(null); + } + + @Path(DeploymentRestService.PATH) + public DeploymentRestService getDeploymentRestService() { + return super.getDeploymentRestService(null); + } + + @Path(CaseDefinitionRestService.PATH) + public CaseDefinitionRestService getCaseDefinitionRestService() { + return super.getCaseDefinitionRestService(null); + } + + @Path(CaseInstanceRestService.PATH) + public CaseInstanceRestService getCaseInstanceRestService() { + return super.getCaseInstanceRestService(null); + } + + @Path(CaseExecutionRestService.PATH) + public CaseExecutionRestService getCaseExecutionRestService() { + return super.getCaseExecutionRestService(null); + } + + @Path(FilterRestService.PATH) + public FilterRestService getFilterRestService() { + return super.getFilterRestService(null); + } + + @Path(MetricsRestService.PATH) + public MetricsRestService getMetricsRestService() { + return super.getMetricsRestService(null); + } + + @Path(DecisionDefinitionRestService.PATH) + public DecisionDefinitionRestService getDecisionDefinitionRestService() { + return super.getDecisionDefinitionRestService(null); + } + + @Path(DecisionRequirementsDefinitionRestService.PATH) + public DecisionRequirementsDefinitionRestService getDecisionRequirementsDefinitionRestService() { + return super.getDecisionRequirementsDefinitionRestService(null); + } + + @Path(ExternalTaskRestService.PATH) + public ExternalTaskRestService getExternalTaskRestService() { + return super.getExternalTaskRestService(null); + } + + @Path(MigrationRestService.PATH) + public MigrationRestService getMigrationRestService() { + return super.getMigrationRestService(null); + } + + @Path(ModificationRestService.PATH) + public ModificationRestService getModificationRestService() { + return super.getModificationRestService(null); + } + + @Path(BatchRestService.PATH) + public BatchRestService getBatchRestService() { + return super.getBatchRestService(null); + } + + @Path(TenantRestService.PATH) + public TenantRestService getTenantRestService() { + return super.getTenantRestService(null); + } + + @Path(SignalRestService.PATH) + public SignalRestService getSignalRestService() { + return super.getSignalRestService(null); + } + + @Path(ConditionRestService.PATH) + public ConditionRestService getConditionRestService() { + return super.getConditionRestService(null); + } + + @Path(OptimizeRestService.PATH) + public OptimizeRestService getOptimizeRestService() { + return super.getOptimizeRestService(null); + } + + @Path(VersionRestService.PATH) + public VersionRestService getVersionRestService() { + return super.getVersionRestService(null); + } + + @Path(SchemaLogRestService.PATH) + public SchemaLogRestService getSchemaLogRestService() { + return super.getSchemaLogRestService(null); + } + + @Path(EventSubscriptionRestService.PATH) + public EventSubscriptionRestService getEventSubscriptionRestService() { + return super.getEventSubscriptionRestService(null); + } + + @Path(TelemetryRestService.PATH) + public TelemetryRestService getTelemetryRestService() { + return super.getTelemetryRestService(null); + } + + @Override + protected URI getRelativeEngineUri(String engineName) { + // the default engine + return URI.create("/"); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DeploymentRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DeploymentRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e6acaac265aba12399c7c35b69a8d8a64d128ff5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/DeploymentRestServiceImpl.java @@ -0,0 +1,200 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayInputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.repository.DeploymentBuilder; +import org.camunda.bpm.engine.repository.DeploymentQuery; +import org.camunda.bpm.engine.repository.DeploymentWithDefinitions; +import org.camunda.bpm.engine.rest.DeploymentRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.repository.DeploymentDto; +import org.camunda.bpm.engine.rest.dto.repository.DeploymentQueryDto; +import org.camunda.bpm.engine.rest.dto.repository.DeploymentWithDefinitionsDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData.FormPart; +import org.camunda.bpm.engine.rest.sub.repository.DeploymentResource; +import org.camunda.bpm.engine.rest.sub.repository.impl.DeploymentResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class DeploymentRestServiceImpl extends AbstractRestProcessEngineAware implements DeploymentRestService { + + public final static String DEPLOYMENT_NAME = "deployment-name"; + public final static String DEPLOYMENT_ACTIVATION_TIME = "deployment-activation-time"; + public final static String ENABLE_DUPLICATE_FILTERING = "enable-duplicate-filtering"; + public final static String DEPLOY_CHANGED_ONLY = "deploy-changed-only"; + public final static String DEPLOYMENT_SOURCE = "deployment-source"; + public final static String TENANT_ID = "tenant-id"; + + protected static final Set RESERVED_KEYWORDS = new HashSet(); + + static { + RESERVED_KEYWORDS.add(DEPLOYMENT_NAME); + RESERVED_KEYWORDS.add(DEPLOYMENT_ACTIVATION_TIME); + RESERVED_KEYWORDS.add(ENABLE_DUPLICATE_FILTERING); + RESERVED_KEYWORDS.add(DEPLOY_CHANGED_ONLY); + RESERVED_KEYWORDS.add(DEPLOYMENT_SOURCE); + RESERVED_KEYWORDS.add(TENANT_ID); + } + + public DeploymentRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public DeploymentResource getDeployment(String deploymentId) { + return new DeploymentResourceImpl(getProcessEngine().getName(), deploymentId, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List getDeployments(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + DeploymentQueryDto queryDto = new DeploymentQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + ProcessEngine engine = getProcessEngine(); + DeploymentQuery query = queryDto.toQuery(engine); + + List matchingDeployments = QueryUtil.list(query, firstResult, maxResults); + + List deployments = new ArrayList(); + for (Deployment deployment : matchingDeployments) { + DeploymentDto def = DeploymentDto.fromDeployment(deployment); + deployments.add(def); + } + return deployments; + } + + @Override + public DeploymentWithDefinitionsDto createDeployment(UriInfo uriInfo, MultipartFormData payload) { + DeploymentBuilder deploymentBuilder = extractDeploymentInformation(payload); + + if(!deploymentBuilder.getResourceNames().isEmpty()) { + DeploymentWithDefinitions deployment = deploymentBuilder.deployWithResult(); + + DeploymentWithDefinitionsDto deploymentDto = DeploymentWithDefinitionsDto.fromDeployment(deployment); + + + URI uri = uriInfo.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(DeploymentRestService.PATH) + .path(deployment.getId()) + .build(); + + // GET + deploymentDto.addReflexiveLink(uri, HttpMethod.GET, "self"); + + return deploymentDto; + + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "No deployment resources contained in the form upload."); + } + } + + private DeploymentBuilder extractDeploymentInformation(MultipartFormData payload) { + DeploymentBuilder deploymentBuilder = getProcessEngine().getRepositoryService().createDeployment(); + + Set partNames = payload.getPartNames(); + + for (String name : partNames) { + FormPart part = payload.getNamedPart(name); + + if (!RESERVED_KEYWORDS.contains(name)) { + String fileName = part.getFileName(); + if (fileName != null) { + deploymentBuilder.addInputStream(part.getFileName(), new ByteArrayInputStream(part.getBinaryContent())); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "No file name found in the deployment resource described by form parameter '" + fileName + "'."); + } + } + } + + FormPart deploymentName = payload.getNamedPart(DEPLOYMENT_NAME); + if (deploymentName != null) { + deploymentBuilder.name(deploymentName.getTextContent()); + } + + FormPart deploymentActivationTime = payload.getNamedPart(DEPLOYMENT_ACTIVATION_TIME); + if (deploymentActivationTime != null && !deploymentActivationTime.getTextContent().isEmpty()) { + deploymentBuilder.activateProcessDefinitionsOn(DateTimeUtil.parseDate(deploymentActivationTime.getTextContent())); + } + + FormPart deploymentSource = payload.getNamedPart(DEPLOYMENT_SOURCE); + if (deploymentSource != null) { + deploymentBuilder.source(deploymentSource.getTextContent()); + } + + FormPart deploymentTenantId = payload.getNamedPart(TENANT_ID); + if (deploymentTenantId != null) { + deploymentBuilder.tenantId(deploymentTenantId.getTextContent()); + } + + extractDuplicateFilteringForDeployment(payload, deploymentBuilder); + return deploymentBuilder; + } + + private void extractDuplicateFilteringForDeployment(MultipartFormData payload, DeploymentBuilder deploymentBuilder) { + boolean enableDuplicateFiltering = false; + boolean deployChangedOnly = false; + + FormPart deploymentEnableDuplicateFiltering = payload.getNamedPart(ENABLE_DUPLICATE_FILTERING); + if (deploymentEnableDuplicateFiltering != null) { + enableDuplicateFiltering = Boolean.parseBoolean(deploymentEnableDuplicateFiltering.getTextContent()); + } + + FormPart deploymentDeployChangedOnly = payload.getNamedPart(DEPLOY_CHANGED_ONLY); + if (deploymentDeployChangedOnly != null) { + deployChangedOnly = Boolean.parseBoolean(deploymentDeployChangedOnly.getTextContent()); + } + + // deployChangedOnly overrides the enableDuplicateFiltering setting + if (deployChangedOnly) { + deploymentBuilder.enableDuplicateFiltering(true); + } else if (enableDuplicateFiltering) { + deploymentBuilder.enableDuplicateFiltering(false); + } + } + + @Override + public CountResultDto getDeploymentsCount(UriInfo uriInfo) { + DeploymentQueryDto queryDto = new DeploymentQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + ProcessEngine engine = getProcessEngine(); + DeploymentQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + return result; + } + + @Override + public Set getRegisteredDeployments(final UriInfo uriInfo) { + return getProcessEngine().getManagementService().getRegisteredDeployments(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/EventSubscriptionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/EventSubscriptionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..53ada22ff262b17182fec5c85a8ad7962509e088 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/EventSubscriptionRestServiceImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.EventSubscriptionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.EventSubscriptionDto; +import org.camunda.bpm.engine.rest.dto.runtime.EventSubscriptionQueryDto; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.EventSubscription; +import org.camunda.bpm.engine.runtime.EventSubscriptionQuery; + +public class EventSubscriptionRestServiceImpl extends AbstractRestProcessEngineAware implements EventSubscriptionRestService { + + public EventSubscriptionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public List getEventSubscriptions(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + EventSubscriptionQueryDto queryDto = new EventSubscriptionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryEventSubscriptions(queryDto, firstResult, maxResults); + } + + public List queryEventSubscriptions(EventSubscriptionQueryDto queryDto, Integer firstResult, Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + EventSubscriptionQuery query = queryDto.toQuery(engine); + + List matchingEventSubscriptions = QueryUtil.list(query, firstResult, maxResults); + + List eventSubscriptionResults = new ArrayList(); + for (EventSubscription eventSubscription : matchingEventSubscriptions) { + EventSubscriptionDto resultEventSubscription = EventSubscriptionDto.fromEventSubscription(eventSubscription); + eventSubscriptionResults.add(resultEventSubscription); + } + return eventSubscriptionResults; + } + + @Override + public CountResultDto getEventSubscriptionsCount(UriInfo uriInfo) { + EventSubscriptionQueryDto queryDto = new EventSubscriptionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryEventSubscriptionsCount(queryDto); + } + + public CountResultDto queryEventSubscriptionsCount(EventSubscriptionQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + EventSubscriptionQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ExecutionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ExecutionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..d9f6354609a3175673081fd8101c605999e7d6e3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ExecutionRestServiceImpl.java @@ -0,0 +1,87 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.ExecutionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionQueryDto; +import org.camunda.bpm.engine.rest.sub.runtime.ExecutionResource; +import org.camunda.bpm.engine.rest.sub.runtime.impl.ExecutionResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.Execution; +import org.camunda.bpm.engine.runtime.ExecutionQuery; + +public class ExecutionRestServiceImpl extends AbstractRestProcessEngineAware implements ExecutionRestService { + + public ExecutionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public ExecutionResource getExecution(String executionId) { + return new ExecutionResourceImpl(getProcessEngine(), executionId, getObjectMapper()); + } + + @Override + public List getExecutions(UriInfo uriInfo, Integer firstResult, + Integer maxResults) { + ExecutionQueryDto queryDto = new ExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryExecutions(queryDto, firstResult, maxResults); + } + + @Override + public List queryExecutions( + ExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + ExecutionQuery query = queryDto.toQuery(engine); + + List matchingExecutions = QueryUtil.list(query, firstResult, maxResults); + + List executionResults = new ArrayList(); + for (Execution execution : matchingExecutions) { + ExecutionDto resultExecution = ExecutionDto.fromExecution(execution); + executionResults.add(resultExecution); + } + return executionResults; + } + + @Override + public CountResultDto getExecutionsCount(UriInfo uriInfo) { + ExecutionQueryDto queryDto = new ExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryExecutionsCount(queryDto); + } + + @Override + public CountResultDto queryExecutionsCount(ExecutionQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + ExecutionQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ExternalTaskRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ExternalTaskRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..ff7d95f9944e4d6cf65e3b0f1a4d5e5ec75cc31f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ExternalTaskRestServiceImpl.java @@ -0,0 +1,197 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.container.AsyncResponse; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.externaltask.ExternalTaskQuery; +import org.camunda.bpm.engine.externaltask.UpdateExternalTaskRetriesBuilder; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.rest.ExternalTaskRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskQueryDto; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto; +import org.camunda.bpm.engine.rest.dto.externaltask.SetRetriesForExternalTasksDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.spi.FetchAndLockHandler; +import org.camunda.bpm.engine.rest.sub.externaltask.ExternalTaskResource; +import org.camunda.bpm.engine.rest.sub.externaltask.impl.ExternalTaskResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; + +/** + * @author Thorben Lindhauer + * + */ +public class ExternalTaskRestServiceImpl extends AbstractRestProcessEngineAware implements ExternalTaskRestService { + + public ExternalTaskRestServiceImpl(String processEngine, ObjectMapper objectMapper) { + super(processEngine, objectMapper); + } + + @Override + public List getExternalTasks(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + ExternalTaskQueryDto queryDto = new ExternalTaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryExternalTasks(queryDto, firstResult, maxResults); + } + + @Override + public List queryExternalTasks(ExternalTaskQueryDto queryDto, Integer firstResult, Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + ExternalTaskQuery query = queryDto.toQuery(engine); + + List matchingTasks = QueryUtil.list(query, firstResult, maxResults); + + List taskResults = new ArrayList<>(); + for (ExternalTask task : matchingTasks) { + ExternalTaskDto resultInstance = ExternalTaskDto.fromExternalTask(task); + taskResults.add(resultInstance); + } + return taskResults; + } + + @Override + public CountResultDto getExternalTasksCount(UriInfo uriInfo) { + ExternalTaskQueryDto queryDto = new ExternalTaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryExternalTasksCount(queryDto); + } + + @Override + public CountResultDto queryExternalTasksCount(ExternalTaskQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + ExternalTaskQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public void fetchAndLock(FetchExternalTasksExtendedDto dto, AsyncResponse asyncResponse) { + FetchAndLockHandler fetchAndLockHandler = FetchAndLockContextListener.getFetchAndLockHandler(); + fetchAndLockHandler.addPendingRequest(dto, asyncResponse, getProcessEngine()); + } + + @Override + public ExternalTaskResource getExternalTask(String externalTaskId) { + return new ExternalTaskResourceImpl(getProcessEngine(), externalTaskId, getObjectMapper()); + } + + @Override + public BatchDto setRetriesAsync(SetRetriesForExternalTasksDto retriesDto) { + + UpdateExternalTaskRetriesBuilder builder = updateRetries(retriesDto); + Integer retries = retriesDto.getRetries(); + + if (retries == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "The number of retries cannot be null."); + } + + try { + Batch batch = builder.setAsync(retries); + return BatchDto.fromBatch(batch); + } + catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + + } + + @Override + public List getTopicNames(boolean withLockedTasks, boolean withUnlockedTasks, + boolean withRetriesLeft) { + return getProcessEngine().getExternalTaskService() + .getTopicNames(withLockedTasks, withUnlockedTasks, withRetriesLeft); + } + + @Override + public void setRetries(SetRetriesForExternalTasksDto retriesDto){ + + UpdateExternalTaskRetriesBuilder builder = updateRetries(retriesDto); + Integer retries = retriesDto.getRetries(); + + if (retries == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "The number of retries cannot be null."); + } + + try { + builder.set(retries); + } + catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + protected UpdateExternalTaskRetriesBuilder updateRetries(SetRetriesForExternalTasksDto retriesDto) { + + ExternalTaskService externalTaskService = getProcessEngine().getExternalTaskService(); + + List externalTaskIds = retriesDto.getExternalTaskIds(); + List processInstanceIds = retriesDto.getProcessInstanceIds(); + + ExternalTaskQuery externalTaskQuery = null; + ProcessInstanceQuery processInstanceQuery = null; + HistoricProcessInstanceQuery historicProcessInstanceQuery = null; + + ExternalTaskQueryDto externalTaskQueryDto = retriesDto.getExternalTaskQuery(); + if (externalTaskQueryDto != null) { + externalTaskQuery = externalTaskQueryDto.toQuery(getProcessEngine()); + } + + ProcessInstanceQueryDto processInstanceQueryDto = retriesDto.getProcessInstanceQuery(); + if (processInstanceQueryDto != null) { + processInstanceQuery = processInstanceQueryDto.toQuery(getProcessEngine()); + } + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = retriesDto.getHistoricProcessInstanceQuery(); + if (historicProcessInstanceQueryDto != null) { + historicProcessInstanceQuery = historicProcessInstanceQueryDto.toQuery(getProcessEngine()); + } + + return externalTaskService.updateRetries() + .externalTaskIds(externalTaskIds) + .processInstanceIds(processInstanceIds) + .externalTaskQuery(externalTaskQuery) + .processInstanceQuery(processInstanceQuery) + .historicProcessInstanceQuery(historicProcessInstanceQuery); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockContextListener.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockContextListener.java new file mode 100644 index 0000000000000000000000000000000000000000..1976a083329fcc14c391043d6e13c3c5dd51d871 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockContextListener.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.spi.FetchAndLockHandler; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.ws.rs.core.Response; +import java.util.Iterator; +import java.util.ServiceLoader; + +/** + * @author Tassilo Weidner + */ +public class FetchAndLockContextListener implements ServletContextListener { + + protected static FetchAndLockHandler fetchAndLockHandler; + + @Override + public void contextInitialized(ServletContextEvent sce) { + if (fetchAndLockHandler == null) { + fetchAndLockHandler = lookupFetchAndLockHandler(); + fetchAndLockHandler.contextInitialized(sce); + fetchAndLockHandler.start(); + } + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + fetchAndLockHandler.shutdown(); + } + + public static FetchAndLockHandler getFetchAndLockHandler() { + return fetchAndLockHandler; + } + + protected FetchAndLockHandler lookupFetchAndLockHandler() { + ServiceLoader serviceLoader = ServiceLoader.load(FetchAndLockHandler.class); + Iterator iterator = serviceLoader.iterator(); + if(iterator.hasNext()) { + return iterator.next(); + } else { + throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, + "Could not find an implementation of the " + FetchAndLockHandler.class.getSimpleName() + "- SPI"); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockHandlerImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockHandlerImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..9cabe426000216d224491513718f719a4c999697 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockHandlerImpl.java @@ -0,0 +1,392 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.ws.rs.container.AsyncResponse; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.externaltask.ExternalTaskQueryTopicBuilder; +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.impl.ProcessEngineImpl; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.impl.util.SingleConsumerCondition; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto; +import org.camunda.bpm.engine.rest.dto.externaltask.LockedExternalTaskDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.spi.FetchAndLockHandler; +import org.camunda.bpm.engine.rest.util.EngineUtil; + + +/** + * @author Tassilo Weidner + */ +public class FetchAndLockHandlerImpl implements Runnable, FetchAndLockHandler { + + private static final Logger LOG = Logger.getLogger(FetchAndLockHandlerImpl.class.getName()); + + protected static final String UNIQUE_WORKER_REQUEST_PARAM_NAME = "fetch-and-lock-unique-worker-request"; + protected static final String BLOCKING_QUEUE_CAPACITY_PARAM_NAME = "fetch-and-lock-queue-capacity"; + + protected static final long PENDING_REQUEST_FETCH_INTERVAL = 30L * 1000; + protected static final long MAX_BACK_OFF_TIME = Long.MAX_VALUE; + protected static final long MAX_REQUEST_TIMEOUT = 1800000; // 30 minutes + protected static final int DEFAULT_BLOCKING_QUEUE_CAPACITY = 200; + + protected SingleConsumerCondition condition; + + protected BlockingQueue queue; + protected List pendingRequests = new ArrayList<>(); + protected List newRequests = new ArrayList<>(); + + protected Thread handlerThread = new Thread(this, this.getClass().getSimpleName()); + + protected volatile boolean isRunning = false; + + protected boolean isUniqueWorkerRequest = false; + + public FetchAndLockHandlerImpl() { + this.condition = new SingleConsumerCondition(handlerThread); + } + + @Override + public void run() { + while (isRunning) { + try { + acquire(); + } + catch (Exception e) { + // what ever happens, don't leave the loop + } + } + + rejectPendingRequests(); + } + + protected void acquire() { + LOG.log(Level.FINEST, "Acquire start"); + + queue.drainTo(newRequests); + + if (!newRequests.isEmpty()) { + if (isUniqueWorkerRequest) { + removeDuplicates(); + } + + pendingRequests.addAll(newRequests); + newRequests.clear(); + } + + LOG.log(Level.FINEST, "Number of pending requests {0}", pendingRequests.size()); + + long backoffTime = MAX_BACK_OFF_TIME; //timestamp + + Iterator iterator = pendingRequests.iterator(); + while (iterator.hasNext()) { + + FetchAndLockRequest pendingRequest = iterator.next(); + + LOG.log(Level.FINEST, "Fetching tasks for request {0}", pendingRequest); + + FetchAndLockResult result = tryFetchAndLock(pendingRequest); + + LOG.log(Level.FINEST, "Fetch and lock result: {0}", result); + + if (result.wasSuccessful()) { + + List lockedTasks = result.getTasks(); + + if (!lockedTasks.isEmpty() || isExpired(pendingRequest)) { + AsyncResponse asyncResponse = pendingRequest.getAsyncResponse(); + asyncResponse.resume(lockedTasks); + + LOG.log(Level.FINEST, "resume and remove request with {0}", lockedTasks); + + iterator.remove(); + } + else { + final long msUntilTimeout = pendingRequest.getTimeoutTimestamp() - ClockUtil.getCurrentTime().getTime(); + backoffTime = Math.min(backoffTime, msUntilTimeout); + } + } + else { + AsyncResponse asyncResponse = pendingRequest.getAsyncResponse(); + Throwable processEngineException = result.getThrowable(); + asyncResponse.resume(processEngineException); + + LOG.log(Level.FINEST, "Resume and remove request with error", processEngineException); + + iterator.remove(); + } + } + + final long waitTime = Math.max(0, backoffTime); + + if (pendingRequests.isEmpty()) { + suspend(waitTime); + } + else { + // if there are pending requests, try fetch periodically to ensure tasks created on other + // cluster nodes and tasks with expired timeouts can be fetched in a timely manner + suspend(Math.min(PENDING_REQUEST_FETCH_INTERVAL, waitTime)); + } + } + + protected void removeDuplicates() { + for (FetchAndLockRequest newRequest : newRequests) { + // remove any request from pendingRequests with the same worker id + Iterator iterator = pendingRequests.iterator(); + while (iterator.hasNext()) { + FetchAndLockRequest pendingRequest = iterator.next(); + if (pendingRequest.getDto().getWorkerId().equals(newRequest.getDto().getWorkerId())) { + AsyncResponse asyncResponse = pendingRequest.getAsyncResponse(); + asyncResponse.cancel(); + + iterator.remove(); + } + } + + } + } + + @Override + public void start() { + if (isRunning) { + return; + } + + isRunning = true; + handlerThread.start(); + if (queue == null) { + initializeQueue(DEFAULT_BLOCKING_QUEUE_CAPACITY); + } + + ProcessEngineImpl.EXT_TASK_CONDITIONS.addConsumer(condition); + } + + @Override + public void shutdown() { + try { + ProcessEngineImpl.EXT_TASK_CONDITIONS.removeConsumer(condition); + } + finally { + isRunning = false; + condition.signal(); + } + + try { + handlerThread.join(); + } catch (InterruptedException e) { + LOG.log(Level.WARNING, "Shutting down the handler thread failed", e); + } + } + + protected void suspend(long millis) { + if (millis <= 0) { + return; + } + + suspendAcquisition(millis); + } + + protected void suspendAcquisition(long millis) { + try { + if (queue.isEmpty() && isRunning) { + LOG.log(Level.FINEST, "Suspend acquisition for {0}ms", millis); + condition.await(millis); + LOG.log(Level.FINEST, "Acquisition woke up"); + } + } + finally { + if (handlerThread.isInterrupted()) { + Thread.currentThread().interrupt(); + } + } + } + + protected void addRequest(FetchAndLockRequest request) { + if (!queue.offer(request)) { + AsyncResponse asyncResponse = request.getAsyncResponse(); + errorTooManyRequests(asyncResponse); + } + + condition.signal(); + } + + protected FetchAndLockResult tryFetchAndLock(FetchAndLockRequest request) { + + ProcessEngine processEngine = null; + IdentityService identityService = null; + FetchAndLockResult result = null; + + try { + processEngine = getProcessEngine(request); + + identityService = processEngine.getIdentityService(); + identityService.setAuthentication(request.getAuthentication()); + + FetchExternalTasksExtendedDto fetchingDto = request.getDto(); + List lockedTasks = executeFetchAndLock(fetchingDto, processEngine); + result = FetchAndLockResult.successful(lockedTasks); + } + catch (Exception e) { + result = FetchAndLockResult.failed(e); + } + finally { + if (identityService != null) { + identityService.clearAuthentication(); + } + } + + return result; + } + + protected List executeFetchAndLock(FetchExternalTasksExtendedDto fetchingDto, ProcessEngine processEngine) { + ExternalTaskQueryTopicBuilder fetchBuilder = fetchingDto.buildQuery(processEngine); + List externalTasks = fetchBuilder.execute(); + + return LockedExternalTaskDto.fromLockedExternalTasks(externalTasks); + } + + protected void errorTooManyRequests(AsyncResponse asyncResponse) { + String errorMessage = "At the moment the server has to handle too many requests at the same time. Please try again later."; + asyncResponse.resume(new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, errorMessage)); + } + + protected void rejectPendingRequests() { + for (FetchAndLockRequest pendingRequest : pendingRequests) { + AsyncResponse asyncResponse = pendingRequest.getAsyncResponse(); + asyncResponse.resume(new RestException(Status.INTERNAL_SERVER_ERROR, "Request rejected due to shutdown of application server.")); + } + } + + protected ProcessEngine getProcessEngine(FetchAndLockRequest request) { + String processEngineName = request.getProcessEngineName(); + return EngineUtil.lookupProcessEngine(processEngineName); + } + + protected boolean isExpired(FetchAndLockRequest request) { + long currentTime = ClockUtil.getCurrentTime().getTime(); + long timeout = request.getTimeoutTimestamp(); + return timeout <= currentTime; + } + + @Override + public void addPendingRequest(FetchExternalTasksExtendedDto dto, AsyncResponse asyncResponse, ProcessEngine processEngine) { + Long asyncResponseTimeout = dto.getAsyncResponseTimeout(); + if (asyncResponseTimeout != null && asyncResponseTimeout > MAX_REQUEST_TIMEOUT) { + asyncResponse.resume(new InvalidRequestException(Status.BAD_REQUEST, "The asynchronous response timeout cannot be set to a value greater than " + + MAX_REQUEST_TIMEOUT + " milliseconds")); + return; + } + + IdentityService identityService = processEngine.getIdentityService(); + Authentication authentication = identityService.getCurrentAuthentication(); + String processEngineName = processEngine.getName(); + + FetchAndLockRequest incomingRequest = new FetchAndLockRequest() + .setProcessEngineName(processEngineName) + .setAsyncResponse(asyncResponse) + .setAuthentication(authentication) + .setDto(dto); + + LOG.log(Level.FINEST, "New request: {0}", incomingRequest); + + FetchAndLockResult result = tryFetchAndLock(incomingRequest); + + LOG.log(Level.FINEST, "Fetch and lock result: {0}", result); + + if (result.wasSuccessful()) { + List lockedTasks = result.getTasks(); + if (!lockedTasks.isEmpty() || dto.getAsyncResponseTimeout() == null) { // response immediately if tasks available + asyncResponse.resume(lockedTasks); + + LOG.log(Level.FINEST, "Resuming request with {0}", lockedTasks); + } else { + addRequest(incomingRequest); + + LOG.log(Level.FINEST, "Deferred request"); + } + } + else { + Throwable processEngineException = result.getThrowable(); + asyncResponse.resume(processEngineException); + + LOG.log(Level.FINEST, "Resuming request with error", processEngineException); + } + } + + public void contextInitialized(ServletContextEvent servletContextEvent) { + ServletContext servletContext; + int queueCapacity = DEFAULT_BLOCKING_QUEUE_CAPACITY; + + if (servletContextEvent != null) { + servletContext = servletContextEvent.getServletContext(); + + if (servletContext != null) { + parseUniqueWorkerRequestParam(servletContext.getInitParameter(UNIQUE_WORKER_REQUEST_PARAM_NAME)); + queueCapacity = parseBlockingQueueCapacityParam(servletContext.getInitParameter(BLOCKING_QUEUE_CAPACITY_PARAM_NAME)); + } + } + + initializeQueue(queueCapacity); + } + + protected void parseUniqueWorkerRequestParam(String uniqueWorkerRequestParam) { + if (uniqueWorkerRequestParam != null) { + isUniqueWorkerRequest = Boolean.parseBoolean(uniqueWorkerRequestParam); + } else { + isUniqueWorkerRequest = false; // default configuration + } + } + + protected void initializeQueue(int capacity) { + LOG.log(Level.FINEST, "Initializing queue with capacity [{0}]", capacity); + queue = new ArrayBlockingQueue<>(capacity); + } + + private static int parseBlockingQueueCapacityParam(String queueSizeRequestParam) { + int capacity = DEFAULT_BLOCKING_QUEUE_CAPACITY; + if (queueSizeRequestParam != null) { + try { + final int parsedCapacity = Integer.parseInt(queueSizeRequestParam); + if (parsedCapacity <= 0) { + throw new NumberFormatException("Parameter " + BLOCKING_QUEUE_CAPACITY_PARAM_NAME + " has to be greater than zero"); + } + capacity = parsedCapacity; + } catch (NumberFormatException e) { + LOG.log(Level.WARNING, "Invalid blocking queue capacity parameter: [" + queueSizeRequestParam + "], falling back to default value", e); + } + } + return capacity; + } + + public List getPendingRequests() { + return pendingRequests; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockRequest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockRequest.java new file mode 100644 index 0000000000000000000000000000000000000000..72063798d9e6c4a4c7774169888252a791f29ba6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockRequest.java @@ -0,0 +1,96 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.Date; + +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto; + +import javax.ws.rs.container.AsyncResponse; + +/** + * @author Tassilo Weidner + */ +public class FetchAndLockRequest { + + protected Date requestTime = ClockUtil.getCurrentTime(); + protected FetchExternalTasksExtendedDto dto; + protected AsyncResponse asyncResponse; + protected String processEngineName; + protected Authentication authentication; + + public Date getRequestTime() { + return requestTime; + } + + public FetchAndLockRequest setRequestTime(Date requestTime) { + this.requestTime = requestTime; + return this; + } + + public FetchExternalTasksExtendedDto getDto() { + return dto; + } + + public FetchAndLockRequest setDto(FetchExternalTasksExtendedDto dto) { + this.dto = dto; + return this; + } + + public AsyncResponse getAsyncResponse() { + return asyncResponse; + } + + public FetchAndLockRequest setAsyncResponse(AsyncResponse asyncResponse) { + this.asyncResponse = asyncResponse; + return this; + } + + public String getProcessEngineName() { + return processEngineName; + } + + public FetchAndLockRequest setProcessEngineName(String processEngineName) { + this.processEngineName = processEngineName; + return this; + } + + public Authentication getAuthentication() { + return authentication; + } + + public FetchAndLockRequest setAuthentication(Authentication authentication) { + this.authentication = authentication; + return this; + } + + public long getTimeoutTimestamp() { + FetchExternalTasksExtendedDto dto = getDto(); + long requestTime = getRequestTime().getTime(); + long asyncResponseTimeout = dto.getAsyncResponseTimeout(); + return requestTime + asyncResponseTimeout; + } + + @Override + public String toString() { + return "FetchAndLockRequest [requestTime=" + requestTime + ", dto=" + dto + ", asyncResponse=" + asyncResponse + ", processEngineName=" + processEngineName + + ", authentication=" + authentication + "]"; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockResult.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockResult.java new file mode 100644 index 0000000000000000000000000000000000000000..fb56669d913404cb778ed891b6ec04313492b23a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FetchAndLockResult.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.camunda.bpm.engine.rest.dto.externaltask.LockedExternalTaskDto; + +/** + * @author Tassilo Weidner + */ +public class FetchAndLockResult { + + protected List tasks = new ArrayList(); + protected Throwable throwable; + + public FetchAndLockResult(List tasks) { + this.tasks = tasks; + } + + public FetchAndLockResult(Throwable throwable) { + this.throwable = throwable; + } + + public List getTasks() { + return tasks; + } + + public Throwable getThrowable() { + return throwable; + } + + public boolean wasSuccessful() { + return throwable == null; + } + + public static FetchAndLockResult successful(List tasks) { + return new FetchAndLockResult(tasks); + } + + public static FetchAndLockResult failed(Throwable throwable) { + return new FetchAndLockResult(throwable); + } + + @Override + public String toString() { + return "FetchAndLockResult [tasks=" + tasks + ", throwable=" + throwable + "]"; + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FilterRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FilterRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f5eaa88c8f702aa8998336277883155d944d6d9e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/FilterRestServiceImpl.java @@ -0,0 +1,147 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Resources.FILTER; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.EntityTypes; +import org.camunda.bpm.engine.FilterService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.filter.FilterQuery; +import org.camunda.bpm.engine.rest.FilterRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.runtime.FilterDto; +import org.camunda.bpm.engine.rest.dto.runtime.FilterQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.runtime.FilterResource; +import org.camunda.bpm.engine.rest.sub.runtime.impl.FilterResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + + +/** + * @author Sebastian Menski + */ +public class FilterRestServiceImpl extends AbstractAuthorizedRestResource implements FilterRestService { + + public FilterRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, FILTER, ANY, objectMapper); + } + + @Override + public FilterResource getFilter(String filterId) { + return new FilterResourceImpl(getProcessEngine().getName(), getObjectMapper(), filterId, relativeRootResourcePath); + } + + @Override + public List getFilters(UriInfo uriInfo, Boolean itemCount, Integer firstResult, Integer maxResults) { + FilterService filterService = getProcessEngine().getFilterService(); + FilterQuery query = getQueryFromQueryParameters(uriInfo.getQueryParameters()); + + List matchingFilters = QueryUtil.list(query, firstResult, maxResults); + + List filters = new ArrayList(); + for (Filter filter : matchingFilters) { + FilterDto dto = FilterDto.fromFilter(filter); + if (itemCount != null && itemCount) { + dto.setItemCount(filterService.count(filter.getId())); + } + filters.add(dto); + } + + return filters; + } + + @Override + public CountResultDto getFiltersCount(UriInfo uriInfo) { + FilterQuery query = getQueryFromQueryParameters(uriInfo.getQueryParameters()); + return new CountResultDto(query.count()); + } + + @Override + public FilterDto createFilter(FilterDto filterDto) { + FilterService filterService = getProcessEngine().getFilterService(); + + String resourceType = filterDto.getResourceType(); + + Filter filter; + + if (EntityTypes.TASK.equals(resourceType)) { + filter = filterService.newTaskFilter(); + } + else { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Unable to create filter with invalid resource type '" + resourceType + "'"); + } + + try { + filterDto.updateFilter(filter, getProcessEngine()); + } + catch (NotValidException e) { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, e, "Unable to create filter with invalid content"); + } + + filterService.saveFilter(filter); + + return FilterDto.fromFilter(filter); + } + + protected FilterQuery getQueryFromQueryParameters(MultivaluedMap queryParameters) { + ProcessEngine engine = getProcessEngine(); + FilterQueryDto queryDto = new FilterQueryDto(getObjectMapper(), queryParameters); + return queryDto.toQuery(engine); + } + + @Override + public ResourceOptionsDto availableOperations(UriInfo context) { + + UriBuilder baseUriBuilder = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(FilterRestService.PATH); + + ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); + + // GET / + URI baseUri = baseUriBuilder.build(); + resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); + + // GET /count + URI countUri = baseUriBuilder.clone().path("/count").build(); + resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); + + // POST /create + if (isAuthorized(CREATE)) { + URI createUri = baseUriBuilder.clone().path("/create").build(); + resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); + } + + return resourceOptionsDto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/GroupRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/GroupRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e35a0076cc02e1bbd0c665ea6d75ee6acc173526 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/GroupRestServiceImpl.java @@ -0,0 +1,138 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Resources.GROUP; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.util.List; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.GroupDto; +import org.camunda.bpm.engine.rest.dto.identity.GroupQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.identity.GroupResource; +import org.camunda.bpm.engine.rest.sub.identity.impl.GroupResourceImpl; +import org.camunda.bpm.engine.rest.util.PathUtil; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Daniel Meyer + * + */ +public class GroupRestServiceImpl extends AbstractAuthorizedRestResource implements GroupRestService { + + public GroupRestServiceImpl(String engineName, final ObjectMapper objectMapper) { + super(engineName, GROUP, ANY, objectMapper); + } + + @Override + public GroupResource getGroup(String id) { + id = PathUtil.decodePathParam(id); + return new GroupResourceImpl(getProcessEngine().getName(), id, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List queryGroups(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + GroupQueryDto queryDto = new GroupQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryGroups(queryDto, firstResult, maxResults); + } + + @Override + public List queryGroups(GroupQueryDto queryDto, Integer firstResult, Integer maxResults) { + + queryDto.setObjectMapper(getObjectMapper()); + GroupQuery query = queryDto.toQuery(getProcessEngine()); + + List resultList = QueryUtil.list(query, firstResult, maxResults); + + return GroupDto.fromGroupList(resultList); + } + + @Override + public CountResultDto getGroupCount(UriInfo uriInfo) { + GroupQueryDto queryDto = new GroupQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryGroupCount(queryDto); + } + + @Override + public CountResultDto queryGroupCount(GroupQueryDto queryDto) { + GroupQuery query = queryDto.toQuery(getProcessEngine()); + long count = query.count(); + return new CountResultDto(count); + } + + @Override + public void createGroup(GroupDto groupDto) { + final IdentityService identityService = getIdentityService(); + + if(identityService.isReadOnly()) { + throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only."); + } + + Group newGroup = identityService.newGroup(groupDto.getId()); + groupDto.update(newGroup); + identityService.saveGroup(newGroup); + + } + + @Override + public ResourceOptionsDto availableOperations(UriInfo context) { + + final IdentityService identityService = getIdentityService(); + + UriBuilder baseUriBuilder = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(GroupRestService.PATH); + + ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); + + // GET / + URI baseUri = baseUriBuilder.build(); + resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); + + // GET /count + URI countUri = baseUriBuilder.clone().path("/count").build(); + resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); + + // POST /create + if(!identityService.isReadOnly() && isAuthorized(CREATE)) { + URI createUri = baseUriBuilder.clone().path("/create").build(); + resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); + } + + return resourceOptionsDto; + } + + // utility methods ////////////////////////////////////// + + protected IdentityService getIdentityService() { + return getProcessEngine().getIdentityService(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/IdentityRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/IdentityRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..7a3207050b1a3dd7214f92ebf76cbba5782cccd7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/IdentityRestServiceImpl.java @@ -0,0 +1,152 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.PasswordPolicyResult; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.rest.IdentityRestService; +import org.camunda.bpm.engine.rest.dto.identity.BasicUserCredentialsDto; +import org.camunda.bpm.engine.rest.dto.identity.CheckPasswordPolicyResultDto; +import org.camunda.bpm.engine.rest.dto.identity.PasswordPolicyRequestDto; +import org.camunda.bpm.engine.rest.dto.identity.PasswordPolicyDto; +import org.camunda.bpm.engine.rest.dto.identity.UserProfileDto; +import org.camunda.bpm.engine.rest.dto.task.GroupDto; +import org.camunda.bpm.engine.rest.dto.task.GroupInfoDto; +import org.camunda.bpm.engine.rest.dto.task.UserDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.security.auth.AuthenticationResult; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class IdentityRestServiceImpl extends AbstractRestProcessEngineAware implements IdentityRestService { + + public IdentityRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public GroupInfoDto getGroupInfo(String userId) { + if (userId == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "No user id was supplied"); + } + + IdentityService identityService = getProcessEngine().getIdentityService(); + + GroupQuery query = identityService.createGroupQuery(); + List userGroups = query.groupMember(userId) + .orderByGroupName() + .asc() + .unlimitedList(); + + Set allGroupUsers = new HashSet<>(); + List allGroups = new ArrayList<>(); + + for (Group group : userGroups) { + List groupUsers = identityService.createUserQuery() + .memberOfGroup(group.getId()) + .unlimitedList(); + + for (User user : groupUsers) { + if (!user.getId().equals(userId)) { + allGroupUsers.add(new UserDto(user.getId(), user.getFirstName(), user.getLastName())); + } + } + allGroups.add(new GroupDto(group.getId(), group.getName())); + } + + return new GroupInfoDto(allGroups, allGroupUsers); + } + + @Override + public AuthenticationResult verifyUser(BasicUserCredentialsDto credentialsDto) { + if (credentialsDto.getUsername() == null || credentialsDto.getPassword() == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Username and password are required"); + } + IdentityService identityService = getProcessEngine().getIdentityService(); + boolean valid = identityService.checkPassword(credentialsDto.getUsername(), credentialsDto.getPassword()); + if (valid) { + return AuthenticationResult.successful(credentialsDto.getUsername()); + } else { + return AuthenticationResult.unsuccessful(credentialsDto.getUsername()); + } + } + + @Override + public Response getPasswordPolicy() { + boolean isEnabled = getProcessEngine().getProcessEngineConfiguration().isEnablePasswordPolicy(); + + if (isEnabled) { + IdentityService identityService = getProcessEngine().getIdentityService(); + + return Response.status(Status.OK.getStatusCode()) + .entity(PasswordPolicyDto.fromPasswordPolicy(identityService.getPasswordPolicy())) + .build(); + + } else { + return Response.status(Status.NOT_FOUND.getStatusCode()).build(); + + } + } + + @Override + public Response checkPassword(PasswordPolicyRequestDto dto) { + boolean isEnabled = getProcessEngine().getProcessEngineConfiguration().isEnablePasswordPolicy(); + + if (isEnabled) { + IdentityService identityService = getProcessEngine().getIdentityService(); + + User user = null; + UserProfileDto profileDto = dto.getProfile(); + if (profileDto != null) { + String id = sanitizeUserId(profileDto.getId()); + user = identityService.newUser(id); + + user.setFirstName(profileDto.getFirstName()); + user.setLastName(profileDto.getLastName()); + user.setEmail(profileDto.getEmail()); + + } + + String candidatePassword = dto.getPassword(); + PasswordPolicyResult result = identityService.checkPasswordAgainstPolicy(candidatePassword, user); + + return Response.status(Status.OK.getStatusCode()) + .entity(CheckPasswordPolicyResultDto.fromPasswordPolicyResult(result)) + .build(); + + } else { + return Response.status(Status.NOT_FOUND.getStatusCode()).build(); + + } + } + + protected String sanitizeUserId(String userId) { + return userId != null ? userId : ""; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/IncidentRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/IncidentRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..d50e0035ea52513afe76e031fca2c0dd2b1d5dcf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/IncidentRestServiceImpl.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.rest.IncidentRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.IncidentDto; +import org.camunda.bpm.engine.rest.dto.runtime.IncidentQueryDto; +import org.camunda.bpm.engine.rest.sub.repository.impl.IncidentResourceImpl; +import org.camunda.bpm.engine.rest.sub.runtime.IncidentResource; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.runtime.IncidentQuery; + +/** + * @author Roman Smirnov + * + */ +public class IncidentRestServiceImpl extends AbstractRestProcessEngineAware implements IncidentRestService { + + public IncidentRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public List getIncidents(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + IncidentQueryDto queryDto = new IncidentQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + IncidentQuery query = queryDto.toQuery(getProcessEngine()); + + List queryResult = QueryUtil.list(query, firstResult, maxResults); + + List result = new ArrayList<>(); + for (Incident incident : queryResult) { + IncidentDto dto = IncidentDto.fromIncident(incident); + result.add(dto); + } + + return result; + } + + @Override + public CountResultDto getIncidentsCount(UriInfo uriInfo) { + IncidentQueryDto queryDto = new IncidentQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + IncidentQuery query = queryDto.toQuery(getProcessEngine()); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public IncidentResource getIncident(String incidentId) { + return new IncidentResourceImpl(getProcessEngine(), incidentId, getObjectMapper()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/JobDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/JobDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..3511115de39e23535b94b60a1fbe69189f41632b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/JobDefinitionRestServiceImpl.java @@ -0,0 +1,108 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.management.JobDefinition; +import org.camunda.bpm.engine.management.JobDefinitionQuery; +import org.camunda.bpm.engine.rest.JobDefinitionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionQueryDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.management.JobDefinitionResource; +import org.camunda.bpm.engine.rest.sub.management.JobDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author roman.smirnov + */ +public class JobDefinitionRestServiceImpl extends AbstractRestProcessEngineAware implements JobDefinitionRestService { + + public JobDefinitionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public JobDefinitionResource getJobDefinition(String jobDefinitionId) { + return new JobDefinitionResourceImpl(getProcessEngine(), jobDefinitionId); + } + + @Override + public List getJobDefinitions(UriInfo uriInfo, Integer firstResult, + Integer maxResults) { + JobDefinitionQueryDto queryDto = new JobDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryJobDefinitions(queryDto, firstResult, maxResults); + + } + + @Override + public CountResultDto getJobDefinitionsCount(UriInfo uriInfo) { + JobDefinitionQueryDto queryDto = new JobDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryJobDefinitionsCount(queryDto); + } + + @Override + public List queryJobDefinitions(JobDefinitionQueryDto queryDto, Integer firstResult, Integer maxResults) { + queryDto.setObjectMapper(getObjectMapper()); + JobDefinitionQuery query = queryDto.toQuery(getProcessEngine()); + + List matchingJobDefinitions = QueryUtil.list(query, firstResult, maxResults); + + List jobDefinitionResults = new ArrayList(); + for (JobDefinition jobDefinition : matchingJobDefinitions) { + JobDefinitionDto result = JobDefinitionDto.fromJobDefinition(jobDefinition); + jobDefinitionResults.add(result); + } + + return jobDefinitionResults; + } + + @Override + public CountResultDto queryJobDefinitionsCount(JobDefinitionQueryDto queryDto) { + queryDto.setObjectMapper(getObjectMapper()); + JobDefinitionQuery query = queryDto.toQuery(getProcessEngine()); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public void updateSuspensionState(JobDefinitionSuspensionStateDto dto) { + if (dto.getJobDefinitionId() != null) { + String message = "Either processDefinitionId or processDefinitionKey can be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + try { + dto.updateSuspensionState(getProcessEngine()); + + } catch (IllegalArgumentException e) { + String message = String.format("Could not update the suspension state of Job Definitions due to: %s", e.getMessage()) ; + throw new InvalidRequestException(Status.BAD_REQUEST, e, message); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/JobRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/JobRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..c1b1242c0de89f5c85ee053df3663e7c6c8d2553 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/JobRestServiceImpl.java @@ -0,0 +1,139 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.impl.util.EnsureUtil; +import org.camunda.bpm.engine.management.SetJobRetriesByJobsAsyncBuilder; +import org.camunda.bpm.engine.rest.JobRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.SetJobRetriesDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.runtime.JobResource; +import org.camunda.bpm.engine.rest.sub.runtime.impl.JobResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.Job; +import org.camunda.bpm.engine.runtime.JobQuery; + +public class JobRestServiceImpl extends AbstractRestProcessEngineAware + implements JobRestService { + + public JobRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public JobResource getJob(String jobId) { + return new JobResourceImpl(getProcessEngine(), jobId); + } + + @Override + public List getJobs(UriInfo uriInfo, Integer firstResult, + Integer maxResults) { + JobQueryDto queryDto = new JobQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryJobs(queryDto, firstResult, maxResults); + } + + @Override + public List queryJobs(JobQueryDto queryDto, Integer firstResult, + Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + JobQuery query = queryDto.toQuery(engine); + + List matchingJobs = QueryUtil.list(query, firstResult, maxResults); + + List jobResults = new ArrayList<>(); + for (Job job : matchingJobs) { + JobDto resultJob = JobDto.fromJob(job); + jobResults.add(resultJob); + } + return jobResults; + } + + @Override + public CountResultDto getJobsCount(UriInfo uriInfo) { + JobQueryDto queryDto = new JobQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryJobsCount(queryDto); + } + + @Override + public CountResultDto queryJobsCount(JobQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + JobQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public BatchDto setRetries(SetJobRetriesDto setJobRetriesDto) { + try { + EnsureUtil.ensureNotNull("setJobRetriesDto", setJobRetriesDto); + EnsureUtil.ensureNotNull("retries", setJobRetriesDto.getRetries()); + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + JobQuery jobQuery = null; + if (setJobRetriesDto.getJobQuery() != null) { + JobQueryDto jobQueryDto = setJobRetriesDto.getJobQuery(); + jobQueryDto.setObjectMapper(getObjectMapper()); + jobQuery = jobQueryDto.toQuery(getProcessEngine()); + } + + try { + SetJobRetriesByJobsAsyncBuilder builder = getProcessEngine().getManagementService() + .setJobRetriesByJobsAsync(setJobRetriesDto.getRetries().intValue()) + .jobIds(setJobRetriesDto.getJobIds()) + .jobQuery(jobQuery); + if(setJobRetriesDto.isDueDateSet()) { + builder.dueDate(setJobRetriesDto.getDueDate()); + } + Batch batch = builder.executeAsync(); + return BatchDto.fromBatch(batch); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public void updateSuspensionState(JobSuspensionStateDto dto) { + if (dto.getJobId() != null) { + String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + dto.updateSuspensionState(getProcessEngine()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MessageRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MessageRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..ff088b4e599eb21fb4cbf2dd43ca3beb993234b2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MessageRestServiceImpl.java @@ -0,0 +1,176 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.Map; +import java.util.Map.Entry; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.MismatchingMessageCorrelationException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.rest.MessageRestService; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.message.CorrelationMessageDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.camunda.bpm.engine.rest.dto.message.MessageCorrelationResultDto; +import org.camunda.bpm.engine.rest.dto.message.MessageCorrelationResultWithVariableDto; +import org.camunda.bpm.engine.runtime.MessageCorrelationResult; +import org.camunda.bpm.engine.runtime.MessageCorrelationResultWithVariables; + +public class MessageRestServiceImpl extends AbstractRestProcessEngineAware implements MessageRestService { + + public MessageRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public Response deliverMessage(CorrelationMessageDto messageDto) { + if (messageDto.getMessageName() == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "No message name supplied"); + } + if (messageDto.getTenantId() != null && messageDto.isWithoutTenantId()) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Parameter 'tenantId' cannot be used together with parameter 'withoutTenantId'."); + } + boolean variablesInResultEnabled = messageDto.isVariablesInResultEnabled(); + if (!messageDto.isResultEnabled() && variablesInResultEnabled) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Parameter 'variablesInResultEnabled' cannot be used without 'resultEnabled' set to true."); + } + + List resultDtos = new ArrayList<>(); + try { + MessageCorrelationBuilder correlation = createMessageCorrelationBuilder(messageDto); + if (!variablesInResultEnabled) { + resultDtos.addAll(correlate(messageDto, correlation)); + } else { + resultDtos.addAll(correlateWithVariablesEnabled(messageDto, correlation)); + } + } catch (RestException e) { + String errorMessage = String.format("Cannot deliver message: %s", e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } catch (MismatchingMessageCorrelationException e) { + throw new RestException(Status.BAD_REQUEST, e); + } + return createResponse(resultDtos, messageDto); + } + + protected List correlate(CorrelationMessageDto messageDto, MessageCorrelationBuilder correlation) { + List resultDtos = new ArrayList<>(); + if (!messageDto.isAll()) { + MessageCorrelationResult result = correlation.correlateWithResult(); + resultDtos.add(MessageCorrelationResultDto.fromMessageCorrelationResult(result)); + } else { + List results = correlation.correlateAllWithResult(); + for (MessageCorrelationResult result : results) { + resultDtos.add(MessageCorrelationResultDto.fromMessageCorrelationResult(result)); + } + } + return resultDtos; + } + + protected List correlateWithVariablesEnabled(CorrelationMessageDto messageDto, MessageCorrelationBuilder correlation) { + List resultDtos = new ArrayList<>(); + if (!messageDto.isAll()) { + MessageCorrelationResultWithVariables result = correlation.correlateWithResultAndVariables(false); + resultDtos.add(MessageCorrelationResultWithVariableDto.fromMessageCorrelationResultWithVariables(result)); + } else { + List results = correlation.correlateAllWithResultAndVariables(false); + for (MessageCorrelationResultWithVariables result : results) { + resultDtos.add(MessageCorrelationResultWithVariableDto.fromMessageCorrelationResultWithVariables(result)); + } + } + return resultDtos; + } + + + protected Response createResponse(List resultDtos, CorrelationMessageDto messageDto) { + Response.ResponseBuilder response = Response.noContent(); + if (messageDto.isResultEnabled()) { + response = Response.ok(resultDtos, MediaType.APPLICATION_JSON); + } + return response.build(); + } + + protected MessageCorrelationBuilder createMessageCorrelationBuilder(CorrelationMessageDto messageDto) { + ProcessEngine processEngine = getProcessEngine(); + RuntimeService runtimeService = processEngine.getRuntimeService(); + + ObjectMapper objectMapper = getObjectMapper(); + Map correlationKeys = VariableValueDto.toMap(messageDto.getCorrelationKeys(), processEngine, objectMapper); + Map localCorrelationKeys = VariableValueDto.toMap(messageDto.getLocalCorrelationKeys(), processEngine, objectMapper); + Map processVariables = VariableValueDto.toMap(messageDto.getProcessVariables(), processEngine, objectMapper); + Map processVariablesLocal = VariableValueDto.toMap(messageDto.getProcessVariablesLocal(), processEngine, objectMapper); + Map processVariablesToTriggeredScope = VariableValueDto.toMap(messageDto.getProcessVariablesToTriggeredScope(), processEngine, objectMapper); + + MessageCorrelationBuilder builder = runtimeService + .createMessageCorrelation(messageDto.getMessageName()); + + if (processVariables != null) { + builder.setVariables(processVariables); + } + if (processVariablesLocal != null) { + builder.setVariablesLocal(processVariablesLocal); + } + if (processVariablesToTriggeredScope != null) { + builder.setVariablesToTriggeredScope(processVariablesToTriggeredScope); + } + if (messageDto.getBusinessKey() != null) { + builder.processInstanceBusinessKey(messageDto.getBusinessKey()); + } + + if (correlationKeys != null && !correlationKeys.isEmpty()) { + for (Entry correlationKey : correlationKeys.entrySet()) { + String name = correlationKey.getKey(); + Object value = correlationKey.getValue(); + builder.processInstanceVariableEquals(name, value); + } + } + + if (localCorrelationKeys != null && !localCorrelationKeys.isEmpty()) { + for (Entry correlationKey : localCorrelationKeys.entrySet()) { + String name = correlationKey.getKey(); + Object value = correlationKey.getValue(); + builder.localVariableEquals(name, value); + } + } + + if (messageDto.getTenantId() != null) { + builder.tenantId(messageDto.getTenantId()); + + } else if (messageDto.isWithoutTenantId()) { + builder.withoutTenantId(); + } + + String processInstanceId = messageDto.getProcessInstanceId(); + if (processInstanceId != null) { + builder.processInstanceId(processInstanceId); + } + + return builder; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MetricsRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MetricsRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..53cd04647e90160fd045d2839b89359999ab0254 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MetricsRestServiceImpl.java @@ -0,0 +1,139 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import org.camunda.bpm.engine.rest.MetricsRestService; +import org.camunda.bpm.engine.rest.sub.metrics.MetricsResource; +import org.camunda.bpm.engine.rest.sub.metrics.MetricsResourceImpl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.management.MetricsQuery; +import org.camunda.bpm.engine.rest.dto.metrics.MetricsIntervalResultDto; +import org.camunda.bpm.engine.management.MetricIntervalValue; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; +import org.camunda.bpm.engine.rest.dto.converter.LongConverter; + +/** + * @author Daniel Meyer + * + */ +public class MetricsRestServiceImpl extends AbstractRestProcessEngineAware implements MetricsRestService { + + public static final String QUERY_PARAM_NAME = "name"; + public static final String QUERY_PARAM_REPORTER = "reporter"; + public static final String QUERY_PARAM_START_DATE = "startDate"; + public static final String QUERY_PARAM_END_DATE = "endDate"; + public static final String QUERY_PARAM_FIRST_RESULT = "firstResult"; + public static final String QUERY_PARAM_MAX_RESULTS = "maxResults"; + public static final String QUERY_PARAM_INTERVAL = "interval"; + public static final String QUERY_PARAM_DATE = "date"; + public static final String QUERY_PARAM_AGG_BY_REPORTER = "aggregateByReporter"; + + protected final DateConverter dateConverter; + + public MetricsRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + dateConverter = new DateConverter(); + dateConverter.setObjectMapper(objectMapper); + } + + @Override + public MetricsResource getMetrics(String name) { + return new MetricsResourceImpl(name, getProcessEngine(), objectMapper); + } + + @Override + public List interval(UriInfo uriInfo) { + MultivaluedMap queryParameters = uriInfo.getQueryParameters(); + final String name = queryParameters.getFirst(QUERY_PARAM_NAME); + MetricsQuery query = getProcessEngine().getManagementService() + .createMetricsQuery() + .name(name) + .reporter(queryParameters.getFirst(QUERY_PARAM_REPORTER)); + + applyQueryParams(query, queryParameters); + + List metrics; + LongConverter longConverter = new LongConverter(); + longConverter.setObjectMapper(objectMapper); + if (queryParameters.getFirst(QUERY_PARAM_INTERVAL) != null) { + long interval = longConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_INTERVAL)); + metrics = query.interval(interval); + } else { + metrics = query.interval(); + } + + final List dtoList = convertToDtos(metrics); + if (name != null) { + dtoList.forEach(dto -> dto.setName(name)); + } + return dtoList; + } + + @Override + public Response deleteTaskMetrics(String dateString) { + Date date = dateConverter.convertQueryParameterToType(dateString); + getProcessEngine().getManagementService().deleteTaskMetrics(date); + + // return no content (204) since resource is deleted + return Response.noContent().build(); + } + + protected void applyQueryParams(MetricsQuery query, MultivaluedMap queryParameters) { + if(queryParameters.getFirst(QUERY_PARAM_START_DATE) != null) { + Date startDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_START_DATE)); + query.startDate(startDate); + } + + if(queryParameters.getFirst(QUERY_PARAM_END_DATE) != null) { + Date endDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_END_DATE)); + query.endDate(endDate); + } + + IntegerConverter intConverter = new IntegerConverter(); + intConverter.setObjectMapper(objectMapper); + + if (queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT) != null) { + int firstResult = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT)); + query.offset(firstResult); + } + + if (queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS) != null) { + int maxResults = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS)); + query.limit(maxResults); + } + + if(queryParameters.getFirst(QUERY_PARAM_AGG_BY_REPORTER) != null) { + query.aggregateByReporter(); + } + } + + protected List convertToDtos(List metrics) { + List intervalMetrics = new ArrayList<>(); + for (MetricIntervalValue m : metrics) { + intervalMetrics.add(new MetricsIntervalResultDto(m)); + } + return intervalMetrics; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MigrationRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MigrationRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..4324e7f0dd8c9c9ab03e8223749b384277871448 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/MigrationRestServiceImpl.java @@ -0,0 +1,136 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.migration.MigrationInstructionsBuilder; +import org.camunda.bpm.engine.migration.MigrationPlan; +import org.camunda.bpm.engine.migration.MigrationPlanExecutionBuilder; +import org.camunda.bpm.engine.migration.MigrationPlanValidationException; +import org.camunda.bpm.engine.rest.MigrationRestService; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationExecutionDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationPlanDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationPlanGenerationDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationPlanReportDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import static org.camunda.bpm.engine.rest.dto.VariableValueDto.toMap; + +public class MigrationRestServiceImpl extends AbstractRestProcessEngineAware implements MigrationRestService { + + public MigrationRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + public MigrationPlanDto generateMigrationPlan(MigrationPlanGenerationDto generationDto) { + RuntimeService runtimeService = getProcessEngine().getRuntimeService(); + + String sourceProcessDefinitionId = generationDto.getSourceProcessDefinitionId(); + String targetProcessDefinitionId = generationDto.getTargetProcessDefinitionId(); + + try { + MigrationInstructionsBuilder instructionsBuilder = runtimeService.createMigrationPlan(sourceProcessDefinitionId, targetProcessDefinitionId) + .mapEqualActivities(); + + if (generationDto.isUpdateEventTriggers()) { + instructionsBuilder = instructionsBuilder.updateEventTriggers(); + } + + Map variableDtos = generationDto.getVariables(); + if (variableDtos != null) { + instructionsBuilder.setVariables(toMap(variableDtos, getProcessEngine(), objectMapper)); + } + + MigrationPlan migrationPlan = instructionsBuilder.build(); + + return MigrationPlanDto.from(migrationPlan); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + public MigrationPlanReportDto validateMigrationPlan(MigrationPlanDto migrationPlanDto) { + try { + createMigrationPlan(migrationPlanDto); + // return an empty report if not errors are found + return MigrationPlanReportDto.emptyReport(); + } + catch (MigrationPlanValidationException e) { + return MigrationPlanReportDto.form(e.getValidationReport()); + } + } + + public void executeMigrationPlan(MigrationExecutionDto migrationExecution) { + createMigrationPlanExecutionBuilder(migrationExecution).execute(); + } + + public BatchDto executeMigrationPlanAsync(MigrationExecutionDto migrationExecution) { + Batch batch = createMigrationPlanExecutionBuilder(migrationExecution).executeAsync(); + return BatchDto.fromBatch(batch); + } + + protected MigrationPlanExecutionBuilder createMigrationPlanExecutionBuilder(MigrationExecutionDto migrationExecution) { + MigrationPlan migrationPlan = createMigrationPlan(migrationExecution.getMigrationPlan()); + List processInstanceIds = migrationExecution.getProcessInstanceIds(); + + MigrationPlanExecutionBuilder executionBuilder = getProcessEngine().getRuntimeService() + .newMigration(migrationPlan).processInstanceIds(processInstanceIds); + + ProcessInstanceQueryDto processInstanceQueryDto = migrationExecution.getProcessInstanceQuery(); + if (processInstanceQueryDto != null) { + ProcessInstanceQuery processInstanceQuery = processInstanceQueryDto.toQuery(getProcessEngine()); + executionBuilder.processInstanceQuery(processInstanceQuery); + } + + if (migrationExecution.isSkipCustomListeners()) { + executionBuilder.skipCustomListeners(); + } + + if (migrationExecution.isSkipIoMappings()) { + executionBuilder.skipIoMappings(); + } + + return executionBuilder; + } + + protected MigrationPlan createMigrationPlan(MigrationPlanDto migrationPlanDto) { + try { + return MigrationPlanDto.toMigrationPlan(getProcessEngine(), objectMapper, migrationPlanDto); + } + catch (MigrationPlanValidationException e) { + throw e; + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ModificationRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ModificationRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e7cca71ea06aee6d0c6db2af99341f9dd3ca9c76 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ModificationRestServiceImpl.java @@ -0,0 +1,100 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.rest.ModificationRestService; +import org.camunda.bpm.engine.rest.dto.ModificationDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.runtime.ModificationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ModificationRestServiceImpl extends AbstractRestProcessEngineAware implements ModificationRestService { + + public ModificationRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public void executeModification(ModificationDto modificationExecutionDto) { + try { + createModificationBuilder(modificationExecutionDto).execute(); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto executeModificationAsync(ModificationDto modificationExecutionDto) { + Batch batch = null; + try { + batch = createModificationBuilder(modificationExecutionDto).executeAsync(); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + return BatchDto.fromBatch(batch); + } + + private ModificationBuilder createModificationBuilder(ModificationDto dto) { + ModificationBuilder builder = getProcessEngine().getRuntimeService().createModification(dto.getProcessDefinitionId()); + + if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) { + dto.applyTo(builder, getProcessEngine(), objectMapper); + } + + List processInstanceIds = dto.getProcessInstanceIds(); + builder.processInstanceIds(processInstanceIds); + + ProcessInstanceQueryDto processInstanceQueryDto = dto.getProcessInstanceQuery(); + if (processInstanceQueryDto != null) { + ProcessInstanceQuery processInstanceQuery = processInstanceQueryDto.toQuery(getProcessEngine()); + builder.processInstanceQuery(processInstanceQuery); + } + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = dto.getHistoricProcessInstanceQuery(); + if(historicProcessInstanceQueryDto != null) { + HistoricProcessInstanceQuery historicProcessInstanceQuery = historicProcessInstanceQueryDto.toQuery(getProcessEngine()); + builder.historicProcessInstanceQuery(historicProcessInstanceQuery); + } + + if (dto.isSkipCustomListeners()) { + builder.skipCustomListeners(); + } + + if (dto.isSkipIoMappings()) { + builder.skipIoMappings(); + } + + if (dto.getAnnotation() != null) { + builder.setAnnotation(dto.getAnnotation()); + } + + return builder; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/NamedProcessEngineRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/NamedProcessEngineRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1e96d4ebde2f0f21ec1176d1ee3224a4046c0792 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/NamedProcessEngineRestServiceImpl.java @@ -0,0 +1,297 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import static org.camunda.bpm.engine.rest.util.EngineUtil.getProcessEngineProvider; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriBuilder; + +import org.camunda.bpm.engine.rest.AuthorizationRestService; +import org.camunda.bpm.engine.rest.BatchRestService; +import org.camunda.bpm.engine.rest.CaseDefinitionRestService; +import org.camunda.bpm.engine.rest.CaseExecutionRestService; +import org.camunda.bpm.engine.rest.CaseInstanceRestService; +import org.camunda.bpm.engine.rest.ConditionRestService; +import org.camunda.bpm.engine.rest.DecisionDefinitionRestService; +import org.camunda.bpm.engine.rest.DecisionRequirementsDefinitionRestService; +import org.camunda.bpm.engine.rest.DeploymentRestService; +import org.camunda.bpm.engine.rest.EventSubscriptionRestService; +import org.camunda.bpm.engine.rest.ExecutionRestService; +import org.camunda.bpm.engine.rest.ExternalTaskRestService; +import org.camunda.bpm.engine.rest.FilterRestService; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.IdentityRestService; +import org.camunda.bpm.engine.rest.IncidentRestService; +import org.camunda.bpm.engine.rest.JobDefinitionRestService; +import org.camunda.bpm.engine.rest.JobRestService; +import org.camunda.bpm.engine.rest.MessageRestService; +import org.camunda.bpm.engine.rest.MetricsRestService; +import org.camunda.bpm.engine.rest.MigrationRestService; +import org.camunda.bpm.engine.rest.ModificationRestService; +import org.camunda.bpm.engine.rest.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.ProcessInstanceRestService; +import org.camunda.bpm.engine.rest.SchemaLogRestService; +import org.camunda.bpm.engine.rest.SignalRestService; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.TelemetryRestService; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.VariableInstanceRestService; +import org.camunda.bpm.engine.rest.dto.ProcessEngineDto; +import org.camunda.bpm.engine.rest.history.HistoryRestService; +import org.camunda.bpm.engine.rest.impl.optimize.OptimizeRestService; +import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider; + + +@Path(NamedProcessEngineRestServiceImpl.PATH) +public class NamedProcessEngineRestServiceImpl extends AbstractProcessEngineRestServiceImpl { + + public static final String PATH = "/engine"; + + @Override + @Path("/{name}" + ProcessDefinitionRestService.PATH) + public ProcessDefinitionRestService getProcessDefinitionService(@PathParam("name") String engineName) { + return super.getProcessDefinitionService(engineName); + } + + @Override + @Path("/{name}" + ProcessInstanceRestService.PATH) + public ProcessInstanceRestService getProcessInstanceService(@PathParam("name") String engineName) { + return super.getProcessInstanceService(engineName); + } + + @Override + @Path("/{name}" + ExecutionRestService.PATH) + public ExecutionRestService getExecutionService(@PathParam("name") String engineName) { + return super.getExecutionService(engineName); + } + + @Override + @Path("/{name}" + TaskRestService.PATH) + public TaskRestService getTaskRestService(@PathParam("name") String engineName) { + return super.getTaskRestService(engineName); + } + + @Override + @Path("/{name}" + IdentityRestService.PATH) + public IdentityRestService getIdentityRestService(@PathParam("name") String engineName) { + return super.getIdentityRestService(engineName); + } + + @Override + @Path("/{name}" + MessageRestService.PATH) + public MessageRestService getMessageRestService(@PathParam("name") String engineName) { + return super.getMessageRestService(engineName); + } + + @Override + @Path("/{name}" + VariableInstanceRestService.PATH) + public VariableInstanceRestService getVariableInstanceService(@PathParam("name") String engineName) { + return super.getVariableInstanceService(engineName); + } + + @Override + @Path("/{name}" + JobDefinitionRestService.PATH) + public JobDefinitionRestService getJobDefinitionRestService(@PathParam("name") String engineName) { + return super.getJobDefinitionRestService(engineName); + } + + @Override + @Path("/{name}" + JobRestService.PATH) + public JobRestService getJobRestService(@PathParam("name") String engineName) { + return super.getJobRestService(engineName); + } + + @Override + @Path("/{name}" + GroupRestService.PATH) + public GroupRestService getGroupRestService(@PathParam("name") String engineName) { + return super.getGroupRestService(engineName); + } + + @Override + @Path("/{name}" + UserRestService.PATH) + public UserRestService getUserRestService(@PathParam("name") String engineName) { + return super.getUserRestService(engineName); + } + + @Override + @Path("/{name}" + AuthorizationRestService.PATH) + public AuthorizationRestService getAuthorizationRestService(@PathParam("name") String engineName) { + return super.getAuthorizationRestService(engineName); + } + + @Override + @Path("/{name}" + IncidentRestService.PATH) + public IncidentRestService getIncidentService(@PathParam("name") String engineName) { + return super.getIncidentService(engineName); + } + + @Override + @Path("/{name}" + HistoryRestService.PATH) + public HistoryRestService getHistoryRestService(@PathParam("name") String engineName) { + return super.getHistoryRestService(engineName); + } + + @Override + @Path("/{name}" + DeploymentRestService.PATH) + public DeploymentRestService getDeploymentRestService(@PathParam("name") String engineName) { + return super.getDeploymentRestService(engineName); + } + + @Override + @Path("/{name}" + CaseDefinitionRestService.PATH) + public CaseDefinitionRestService getCaseDefinitionRestService(@PathParam("name") String engineName) { + return super.getCaseDefinitionRestService(engineName); + } + + @Override + @Path("/{name}" + CaseInstanceRestService.PATH) + public CaseInstanceRestService getCaseInstanceRestService(@PathParam("name") String engineName) { + return super.getCaseInstanceRestService(engineName); + } + + @Override + @Path("/{name}" + CaseExecutionRestService.PATH) + public CaseExecutionRestService getCaseExecutionRestService(@PathParam("name") String engineName) { + return super.getCaseExecutionRestService(engineName); + } + + @Override + @Path("/{name}" + FilterRestService.PATH) + public FilterRestService getFilterRestService(@PathParam("name") String engineName) { + return super.getFilterRestService(engineName); + } + + @Override + @Path("/{name}" + MetricsRestService.PATH) + public MetricsRestService getMetricsRestService(@PathParam("name") String engineName) { + return super.getMetricsRestService(engineName); + } + + @Override + @Path("/{name}" + DecisionDefinitionRestService.PATH) + public DecisionDefinitionRestService getDecisionDefinitionRestService(@PathParam("name") String engineName) { + return super.getDecisionDefinitionRestService(engineName); + } + + @Override + @Path("/{name}" + DecisionRequirementsDefinitionRestService.PATH) + public DecisionRequirementsDefinitionRestService getDecisionRequirementsDefinitionRestService(@PathParam("name") String engineName) { + return super.getDecisionRequirementsDefinitionRestService(engineName); + } + + @Override + @Path("/{name}" + ExternalTaskRestService.PATH) + public ExternalTaskRestService getExternalTaskRestService(@PathParam("name") String engineName) { + return super.getExternalTaskRestService(engineName); + } + + @Override + @Path("/{name}" + MigrationRestService.PATH) + public MigrationRestService getMigrationRestService(@PathParam("name") String engineName) { + return super.getMigrationRestService(engineName); + } + + @Override + @Path("/{name}" + ModificationRestService.PATH) + public ModificationRestService getModificationRestService(@PathParam("name") String engineName) { + return super.getModificationRestService(engineName); + } + + @Override + @Path("/{name}" + BatchRestService.PATH) + public BatchRestService getBatchRestService(@PathParam("name") String engineName) { + return super.getBatchRestService(engineName); + } + + @Override + @Path("/{name}" + TenantRestService.PATH) + public TenantRestService getTenantRestService(@PathParam("name") String engineName) { + return super.getTenantRestService(engineName); + } + + @Override + @Path("/{name}" + SignalRestService.PATH) + public SignalRestService getSignalRestService(@PathParam("name") String engineName) { + return super.getSignalRestService(engineName); + } + + @Override + @Path("/{name}" + ConditionRestService.PATH) + public ConditionRestService getConditionRestService(@PathParam("name") String engineName) { + return super.getConditionRestService(engineName); + } + + @Path("/{name}" + OptimizeRestService.PATH) + public OptimizeRestService getOptimizeRestService(@PathParam("name") String engineName) { + return super.getOptimizeRestService(engineName); + } + + @Path("/{name}" + VersionRestService.PATH) + public VersionRestService getVersionRestService(@PathParam("name") String engineName) { + return super.getVersionRestService(engineName); + } + + @Path("/{name}" + SchemaLogRestService.PATH) + public SchemaLogRestService getSchemaLogRestService(@PathParam("name") String engineName) { + return super.getSchemaLogRestService(engineName); + } + + @Override + @Path("/{name}" + EventSubscriptionRestService.PATH) + public EventSubscriptionRestService getEventSubscriptionRestService(@PathParam("name") String engineName) { + return super.getEventSubscriptionRestService(engineName); + } + + @Override + @Path("/{name}" + TelemetryRestService.PATH) + public TelemetryRestService getTelemetryRestService(@PathParam("name") String engineName) { + return super.getTelemetryRestService(engineName); + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + public List getProcessEngineNames() { + ProcessEngineProvider provider = getProcessEngineProvider(); + Set engineNames = provider.getProcessEngineNames(); + + List results = new ArrayList(); + for (String engineName : engineNames) { + ProcessEngineDto dto = new ProcessEngineDto(); + dto.setName(engineName); + results.add(dto); + } + + return results; + } + + @Override + protected URI getRelativeEngineUri(String engineName) { + return UriBuilder.fromResource(NamedProcessEngineRestServiceImpl.class).path("{name}").build(engineName); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ProcessDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ProcessDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..b85739d993172beef7c00533c5557d9c7c66fe63 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ProcessDefinitionRestServiceImpl.java @@ -0,0 +1,227 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.management.ProcessDefinitionStatistics; +import org.camunda.bpm.engine.management.ProcessDefinitionStatisticsQuery; +import org.camunda.bpm.engine.repository.DeleteProcessDefinitionsBuilder; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.ProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.StatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionQueryDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionStatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.ProcessDefinitionResource; +import org.camunda.bpm.engine.rest.sub.repository.impl.ProcessDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class ProcessDefinitionRestServiceImpl extends AbstractRestProcessEngineAware implements ProcessDefinitionRestService { + + public ProcessDefinitionRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public ProcessDefinitionResource getProcessDefinitionByKey(String processDefinitionKey) { + + ProcessDefinition processDefinition = getProcessEngine() + .getRepositoryService() + .createProcessDefinitionQuery() + .processDefinitionKey(processDefinitionKey) + .withoutTenantId() + .latestVersion() + .singleResult(); + + if(processDefinition == null){ + String errorMessage = String.format("No matching process definition with key: %s and no tenant-id", processDefinitionKey); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getProcessDefinitionById(processDefinition.getId()); + } + } + + @Override + public ProcessDefinitionResource getProcessDefinitionByKeyAndTenantId(String processDefinitionKey, String tenantId) { + + ProcessDefinition processDefinition = getProcessEngine() + .getRepositoryService() + .createProcessDefinitionQuery() + .processDefinitionKey(processDefinitionKey) + .tenantIdIn(tenantId) + .latestVersion() + .singleResult(); + + if (processDefinition == null) { + String errorMessage = String.format("No matching process definition with key: %s and tenant-id: %s", processDefinitionKey, tenantId); + throw new RestException(Status.NOT_FOUND, errorMessage); + + } else { + return getProcessDefinitionById(processDefinition.getId()); + } + } + + @Override + public ProcessDefinitionResource getProcessDefinitionById( + String processDefinitionId) { + return new ProcessDefinitionResourceImpl(getProcessEngine(), processDefinitionId, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List getProcessDefinitions(UriInfo uriInfo, + Integer firstResult, Integer maxResults) { + ProcessDefinitionQueryDto queryDto = new ProcessDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + List definitions = new ArrayList<>(); + + ProcessEngine engine = getProcessEngine(); + ProcessDefinitionQuery query = queryDto.toQuery(engine); + + List matchingDefinitions = QueryUtil.list(query, firstResult, maxResults); + + for (ProcessDefinition definition : matchingDefinitions) { + ProcessDefinitionDto def = ProcessDefinitionDto.fromProcessDefinition(definition); + definitions.add(def); + } + return definitions; + } + + @Override + public CountResultDto getProcessDefinitionsCount(UriInfo uriInfo) { + ProcessDefinitionQueryDto queryDto = new ProcessDefinitionQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + ProcessEngine engine = getProcessEngine(); + ProcessDefinitionQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + return result; + } + + + @Override + public List getStatistics(Boolean includeFailedJobs, Boolean includeRootIncidents, Boolean includeIncidents, String includeIncidentsForType) { + if (includeIncidents != null && includeIncidentsForType != null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Only one of the query parameter includeIncidents or includeIncidentsForType can be set."); + } + + if (includeIncidents != null && includeRootIncidents != null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Only one of the query parameter includeIncidents or includeRootIncidents can be set."); + } + + if (includeRootIncidents != null && includeIncidentsForType != null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Only one of the query parameter includeRootIncidents or includeIncidentsForType can be set."); + } + + ManagementService mgmtService = getProcessEngine().getManagementService(); + ProcessDefinitionStatisticsQuery query = mgmtService.createProcessDefinitionStatisticsQuery(); + + if (includeFailedJobs != null && includeFailedJobs) { + query.includeFailedJobs(); + } + + if (includeIncidents != null && includeIncidents) { + query.includeIncidents(); + } else if (includeIncidentsForType != null) { + query.includeIncidentsForType(includeIncidentsForType); + } else if (includeRootIncidents != null && includeRootIncidents) { + query.includeRootIncidents(); + } + + List queryResults = query.unlimitedList(); + + List results = new ArrayList<>(); + for (ProcessDefinitionStatistics queryResult : queryResults) { + StatisticsResultDto dto = ProcessDefinitionStatisticsResultDto.fromProcessDefinitionStatistics(queryResult); + results.add(dto); + } + + return results; + } + + @Override + public void updateSuspensionState(ProcessDefinitionSuspensionStateDto dto) { + if (dto.getProcessDefinitionId() != null) { + String message = "Only processDefinitionKey can be set to update the suspension state."; + throw new InvalidRequestException(Status.BAD_REQUEST, message); + } + + try { + dto.updateSuspensionState(getProcessEngine()); + + } catch (IllegalArgumentException e) { + String message = String.format("Could not update the suspension state of Process Definitions due to: %s", e.getMessage()) ; + throw new InvalidRequestException(Status.BAD_REQUEST, e, message); + } + } + + @Override + public void deleteProcessDefinitionsByKey(String processDefinitionKey, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings) { + RepositoryService repositoryService = getProcessEngine().getRepositoryService(); + + DeleteProcessDefinitionsBuilder builder = repositoryService.deleteProcessDefinitions() + .byKey(processDefinitionKey); + + deleteProcessDefinitions(builder, cascade, skipCustomListeners, skipIoMappings); + } + + @Override + public void deleteProcessDefinitionsByKeyAndTenantId(String processDefinitionKey, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings, String tenantId) { + RepositoryService repositoryService = getProcessEngine().getRepositoryService(); + + DeleteProcessDefinitionsBuilder builder = repositoryService.deleteProcessDefinitions() + .byKey(processDefinitionKey) + .withTenantId(tenantId); + + deleteProcessDefinitions(builder, cascade, skipCustomListeners, skipIoMappings); + } + + protected void deleteProcessDefinitions(DeleteProcessDefinitionsBuilder builder, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings) { + if (skipCustomListeners) { + builder = builder.skipCustomListeners(); + } + + if (cascade) { + builder = builder.cascade(); + } + + if (skipIoMappings) { + builder = builder.skipIoMappings(); + } + + try { + builder.delete(); + } catch (NotFoundException e) { // rewrite status code from bad request (400) to not found (404) + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ProcessInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ProcessInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..5ae428c5dd2a743ede0c625aab7bcd4a9da7a124 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/ProcessInstanceRestServiceImpl.java @@ -0,0 +1,327 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.impl.util.EnsureUtil; +import org.camunda.bpm.engine.management.SetJobRetriesByProcessAsyncBuilder; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.ProcessInstanceRestService; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceSuspensionStateAsyncDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.SetJobRetriesByProcessDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.CorrelationMessageAsyncDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.DeleteProcessInstancesDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.SetVariablesAsyncDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.runtime.ProcessInstanceResource; +import org.camunda.bpm.engine.rest.sub.runtime.impl.ProcessInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.MessageCorrelationAsyncBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; +import org.camunda.bpm.engine.variable.VariableMap; + +public class ProcessInstanceRestServiceImpl extends AbstractRestProcessEngineAware implements + ProcessInstanceRestService { + + public ProcessInstanceRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + + @Override + public List getProcessInstances( + UriInfo uriInfo, Integer firstResult, Integer maxResults) { + ProcessInstanceQueryDto queryDto = new ProcessInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryProcessInstances(queryDto, firstResult, maxResults); + } + + @Override + public List queryProcessInstances( + ProcessInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + ProcessInstanceQuery query = queryDto.toQuery(engine); + + List matchingInstances = QueryUtil.list(query, firstResult, maxResults); + + List instanceResults = new ArrayList<>(); + for (ProcessInstance instance : matchingInstances) { + ProcessInstanceDto resultInstance = ProcessInstanceDto.fromProcessInstance(instance); + instanceResults.add(resultInstance); + } + return instanceResults; + } + + @Override + public CountResultDto getProcessInstancesCount(UriInfo uriInfo) { + ProcessInstanceQueryDto queryDto = new ProcessInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryProcessInstancesCount(queryDto); + } + + @Override + public CountResultDto queryProcessInstancesCount(ProcessInstanceQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + ProcessInstanceQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public ProcessInstanceResource getProcessInstance(String processInstanceId) { + return new ProcessInstanceResourceImpl(getProcessEngine(), processInstanceId, getObjectMapper()); + } + + @Override + public void updateSuspensionState(ProcessInstanceSuspensionStateDto dto) { + dto.updateSuspensionState(getProcessEngine()); + } + + @Override + public BatchDto updateSuspensionStateAsync(ProcessInstanceSuspensionStateAsyncDto dto){ + Batch batch = null; + try { + batch = dto.updateSuspensionStateAsync(getProcessEngine()); + return BatchDto.fromBatch(batch); + + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto deleteAsync(DeleteProcessInstancesDto dto) { + RuntimeService runtimeService = getProcessEngine().getRuntimeService(); + + ProcessInstanceQuery processInstanceQuery = null; + + if (dto.getProcessInstanceQuery() != null) { + processInstanceQuery = dto.getProcessInstanceQuery().toQuery(getProcessEngine()); + } + + try { + Batch batch = runtimeService.deleteProcessInstancesAsync( + dto.getProcessInstanceIds(), + processInstanceQuery, + null, + dto.getDeleteReason(), + dto.isSkipCustomListeners(), + dto.isSkipSubprocesses(), + dto.isSkipIoMappings() + ); + + return BatchDto.fromBatch(batch); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto deleteAsyncHistoricQueryBased(DeleteProcessInstancesDto deleteProcessInstancesDto) { + HistoricProcessInstanceQuery historicProcessInstanceQuery = null; + if (deleteProcessInstancesDto.getHistoricProcessInstanceQuery() != null) { + historicProcessInstanceQuery = deleteProcessInstancesDto.getHistoricProcessInstanceQuery() + .toQuery(getProcessEngine()); + } + + RuntimeService runtimeService = getProcessEngine().getRuntimeService(); + + try { + Batch batch = runtimeService.deleteProcessInstancesAsync( + deleteProcessInstancesDto.getProcessInstanceIds(), + null, + historicProcessInstanceQuery, + deleteProcessInstancesDto.getDeleteReason(), + deleteProcessInstancesDto.isSkipCustomListeners(), + deleteProcessInstancesDto.isSkipSubprocesses(), + deleteProcessInstancesDto.isSkipIoMappings() + ); + + return BatchDto.fromBatch(batch); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto setRetriesByProcess(SetJobRetriesByProcessDto setJobRetriesDto) { + try { + EnsureUtil.ensureNotNull("setJobRetriesDto", setJobRetriesDto); + EnsureUtil.ensureNotNull("retries", setJobRetriesDto.getRetries()); + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + ProcessInstanceQuery processInstanceQuery = null; + if (setJobRetriesDto.getProcessInstanceQuery() != null) { + processInstanceQuery = setJobRetriesDto.getProcessInstanceQuery().toQuery(getProcessEngine()); + } + + try { + SetJobRetriesByProcessAsyncBuilder builder = getProcessEngine().getManagementService() + .setJobRetriesByProcessAsync(setJobRetriesDto.getRetries().intValue()) + .processInstanceIds(setJobRetriesDto.getProcessInstances()) + .processInstanceQuery(processInstanceQuery); + if(setJobRetriesDto.isDueDateSet()) { + builder.dueDate(setJobRetriesDto.getDueDate()); + } + Batch batch = builder.executeAsync(); + return BatchDto.fromBatch(batch); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto setRetriesByProcessHistoricQueryBased(SetJobRetriesByProcessDto setJobRetriesDto) { + HistoricProcessInstanceQueryDto queryDto = setJobRetriesDto.getHistoricProcessInstanceQuery(); + HistoricProcessInstanceQuery query = null; + if (queryDto != null) { + query = queryDto.toQuery(getProcessEngine()); + } + + try { + ManagementService managementService = getProcessEngine().getManagementService(); + SetJobRetriesByProcessAsyncBuilder builder = managementService + .setJobRetriesByProcessAsync(setJobRetriesDto.getRetries()) + .processInstanceIds(setJobRetriesDto.getProcessInstances()) + .historicProcessInstanceQuery(query); + if(setJobRetriesDto.isDueDateSet()) { + builder.dueDate(setJobRetriesDto.getDueDate()); + } + Batch batch = builder.executeAsync(); + return BatchDto.fromBatch(batch); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto setVariablesAsync(SetVariablesAsyncDto setVariablesAsyncDto) { + Map variables = setVariablesAsyncDto.getVariables(); + + VariableMap variableMap = null; + try { + variableMap = VariableValueDto.toMap(variables, getProcessEngine(), objectMapper); + + } catch (RestException e) { + String errorMessage = String.format("Cannot set variables: %s", e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } + + List ids = setVariablesAsyncDto.getProcessInstanceIds(); + ProcessInstanceQuery runtimeQuery = toQuery(setVariablesAsyncDto.getProcessInstanceQuery()); + HistoricProcessInstanceQuery historyQuery = toQuery(setVariablesAsyncDto.getHistoricProcessInstanceQuery()); + + RuntimeService runtimeService = getProcessEngine().getRuntimeService(); + + Batch batch = null; + try { + batch = runtimeService.setVariablesAsync(ids, runtimeQuery, historyQuery, variableMap); + + } catch (BadUserRequestException | AuthorizationException e) { + throw e; + + } catch (ProcessEngineException e) { + // 1) the java serialization format is prohibited + // 2) null value is given + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + + } + + return BatchDto.fromBatch(batch); + } + + @Override + public BatchDto correlateMessageAsync(CorrelationMessageAsyncDto correlationMessageAsyncDto) { + Map variables = correlationMessageAsyncDto.getVariables(); + + VariableMap variableMap = null; + try { + variableMap = VariableValueDto.toMap(variables, getProcessEngine(), objectMapper); + } catch (RestException e) { + String errorMessage = String.format("Cannot set variables: %s", e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + } + + String messageName = correlationMessageAsyncDto.getMessageName(); + List ids = correlationMessageAsyncDto.getProcessInstanceIds(); + ProcessInstanceQuery runtimeQuery = toQuery(correlationMessageAsyncDto.getProcessInstanceQuery()); + HistoricProcessInstanceQuery historyQuery = toQuery(correlationMessageAsyncDto.getHistoricProcessInstanceQuery()); + + RuntimeService runtimeService = getProcessEngine().getRuntimeService(); + + Batch batch = null; + try { + MessageCorrelationAsyncBuilder messageCorrelationBuilder = runtimeService + .createMessageCorrelationAsync(messageName) + .setVariables(variableMap); + if (ids != null) { + messageCorrelationBuilder.processInstanceIds(ids); + } + if (runtimeQuery != null) { + messageCorrelationBuilder.processInstanceQuery(runtimeQuery); + } + if (historyQuery != null) { + messageCorrelationBuilder.historicProcessInstanceQuery(historyQuery); + } + batch = messageCorrelationBuilder.correlateAllAsync(); + } catch (NullValueException e) { + // null values are given + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + + return BatchDto.fromBatch(batch); + } + + protected , R extends AbstractQueryDto> T toQuery(R query) { + if (query == null) { + return null; + } + + return query.toQuery(getProcessEngine()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/SchemaLogRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/SchemaLogRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..bc39c1d6d9a4edd4a569ad00a74348bf07253a8c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/SchemaLogRestServiceImpl.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.management.SchemaLogEntry; +import org.camunda.bpm.engine.management.SchemaLogQuery; +import org.camunda.bpm.engine.rest.SchemaLogRestService; +import org.camunda.bpm.engine.rest.dto.SchemaLogEntryDto; +import org.camunda.bpm.engine.rest.dto.SchemaLogQueryDto; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Miklas Boskamp + * + */ +public class SchemaLogRestServiceImpl extends AbstractRestProcessEngineAware implements SchemaLogRestService { + + public SchemaLogRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public List getSchemaLog(Request request, UriInfo uriInfo, Integer firstResult, Integer maxResults) { + return querySchemaLog(new SchemaLogQueryDto(getObjectMapper(), uriInfo.getQueryParameters()), firstResult, maxResults); + } + + @Override + public List querySchemaLog(SchemaLogQueryDto dto, Integer firstResult, Integer maxResults) { + SchemaLogQuery query = dto.toQuery(getProcessEngine()); + List schemaLogEntries = QueryUtil.list(query, firstResult, maxResults); + return SchemaLogEntryDto.fromSchemaLogEntries(schemaLogEntries); + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/SignalRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/SignalRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e2632d7542c789ca63f524e5d1c440a118fab644 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/SignalRestServiceImpl.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.rest.SignalRestService; +import org.camunda.bpm.engine.rest.dto.SignalDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.runtime.SignalEventReceivedBuilder; + +import javax.ws.rs.core.Response.Status; +import java.util.Map; + +/** + * @author Tassilo Weidner + */ +public class SignalRestServiceImpl extends AbstractRestProcessEngineAware implements SignalRestService { + + public SignalRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public void throwSignal(SignalDto dto) { + String name = dto.getName(); + if (name == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "No signal name given"); + } + + SignalEventReceivedBuilder signalEvent = createSignalEventReceivedBuilder(dto); + try { + signalEvent.send(); + } catch (NotFoundException e) { + // keeping compatibility with older versions where ProcessEngineException (=> 500) was + // thrown; NotFoundException translates to 400 by default + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, e.getMessage()); + } + } + + protected SignalEventReceivedBuilder createSignalEventReceivedBuilder(SignalDto dto) { + RuntimeService runtimeService = getProcessEngine().getRuntimeService(); + String name = dto.getName(); + SignalEventReceivedBuilder signalEvent = runtimeService.createSignalEvent(name); + + String executionId = dto.getExecutionId(); + if (executionId != null) { + signalEvent.executionId(executionId); + } + + Map variablesDto = dto.getVariables(); + if (variablesDto != null) { + Map variables = VariableValueDto.toMap(variablesDto, getProcessEngine(), objectMapper); + signalEvent.setVariables(variables); + } + + String tenantId = dto.getTenantId(); + if (tenantId != null) { + signalEvent.tenantId(tenantId); + } + + boolean isWithoutTenantId = dto.isWithoutTenantId(); + if (isWithoutTenantId) { + signalEvent.withoutTenantId(); + } + + return signalEvent; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TaskRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TaskRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f062a70661d96050776f9bbfa4f07b4bc77d477d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TaskRestServiceImpl.java @@ -0,0 +1,200 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.core.Variant; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.task.TaskDto; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.rest.dto.task.TaskWithAttachmentAndCommentDto; +import org.camunda.bpm.engine.rest.dto.task.TaskWithVariablesDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.hal.task.HalTaskList; +import org.camunda.bpm.engine.rest.sub.task.TaskReportResource; +import org.camunda.bpm.engine.rest.sub.task.TaskResource; +import org.camunda.bpm.engine.rest.sub.task.impl.TaskReportResourceImpl; +import org.camunda.bpm.engine.rest.sub.task.impl.TaskResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.task.TaskQuery; +import org.camunda.bpm.engine.variable.VariableMap; + +public class TaskRestServiceImpl extends AbstractRestProcessEngineAware implements TaskRestService { + + public static final List VARIANTS = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, Hal.APPLICATION_HAL_JSON_TYPE).add().build(); + + public TaskRestServiceImpl(String engineName, final ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public Object getTasks(Request request, UriInfo uriInfo, Integer firstResult, Integer maxResults) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { + return getJsonTasks(uriInfo, firstResult, maxResults); + } + else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { + return getHalTasks(uriInfo, firstResult, maxResults); + } + } + throw new InvalidRequestException(Response.Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + public List getJsonTasks(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + // get list of tasks + TaskQueryDto queryDto = new TaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryTasks(queryDto, firstResult, maxResults); + } + + public HalTaskList getHalTasks(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + TaskQueryDto queryDto = new TaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + ProcessEngine engine = getProcessEngine(); + TaskQuery query = queryDto.toQuery(engine); + + // get list of tasks + List matchingTasks = executeTaskQuery(firstResult, maxResults, query); + + // get total count + long count = query.count(); + + return HalTaskList.generate(matchingTasks, count, engine); + } + + @Override + public List queryTasks(TaskQueryDto queryDto, Integer firstResult, + Integer maxResults) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + TaskQuery query = queryDto.toQuery(engine); + + List matchingTasks = executeTaskQuery(firstResult, maxResults, query); + List tasks = new ArrayList(); + + boolean withTaskVariables = Boolean.TRUE.equals(queryDto.getWithTaskVariablesInReturn()); + boolean withTaskLocalVariables = Boolean.TRUE.equals(queryDto.getWithTaskLocalVariablesInReturn()); + boolean withCommentInfo = Boolean.TRUE.equals(queryDto.getWithCommentAttachmentInfo()); + + if (withTaskVariables || withTaskLocalVariables) { + return getVariablesForTasks(engine, matchingTasks, withTaskVariables, withCommentInfo); + } + if (withCommentInfo) { + tasks = matchingTasks.stream().map(TaskWithAttachmentAndCommentDto::fromEntity).collect(Collectors.toList()); + } + else { + tasks = matchingTasks.stream().map(TaskDto::fromEntity).collect(Collectors.toList()); + } + return tasks; + } + + protected List executeTaskQuery(Integer firstResult, Integer maxResults, TaskQuery query) { + + // enable initialization of form key: + query.initializeFormKeys(); + return QueryUtil.list(query, firstResult, maxResults); + } + + @Override + public CountResultDto getTasksCount(UriInfo uriInfo) { + TaskQueryDto queryDto = new TaskQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryTasksCount(queryDto); + } + + @Override + public CountResultDto queryTasksCount(TaskQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + TaskQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public TaskResource getTask(String id, + boolean withCommentAttachmentInfo, + boolean withTaskVariablesInReturn, + boolean withTaskLocalVariablesInReturn) { + return new TaskResourceImpl(getProcessEngine(), id, relativeRootResourcePath, getObjectMapper(), + withCommentAttachmentInfo, withTaskVariablesInReturn, withTaskLocalVariablesInReturn); + } + + @Override + public void createTask(TaskDto taskDto) { + ProcessEngine engine = getProcessEngine(); + TaskService taskService = engine.getTaskService(); + + Task newTask = taskService.newTask(taskDto.getId()); + taskDto.updateTask(newTask); + + try { + taskService.saveTask(newTask); + + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Could not save task: " + e.getMessage()); + } + + } + + @Override + public TaskReportResource getTaskReportResource() { + return new TaskReportResourceImpl(getProcessEngine()); + } + + private List getVariablesForTasks(ProcessEngine engine, + List matchingTasks, + boolean withTaskVariablesInReturn, + boolean withCommentAndAttachments) { + TaskService taskService = engine.getTaskService(); + List tasks = new ArrayList(); + for (Task task : matchingTasks) { + VariableMap taskVariables; + if (withTaskVariablesInReturn) { + taskVariables = taskService.getVariablesTyped(task.getId(), true); + } else { + taskVariables = taskService.getVariablesLocalTyped(task.getId(), true); + } + Map taskVariablesDto = VariableValueDto.fromMap(taskVariables); + if (withCommentAndAttachments) { + tasks.add(TaskWithAttachmentAndCommentDto.fromEntity(task, taskVariablesDto)); + } else { + tasks.add(TaskWithVariablesDto.fromEntity(task, taskVariablesDto)); + } + } + return tasks; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TelemetryRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TelemetryRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..c62589bcc6d23cdb2737c6beebdcd38d58fb4fe6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TelemetryRestServiceImpl.java @@ -0,0 +1,57 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.rest.TelemetryRestService; +import org.camunda.bpm.engine.rest.dto.TelemetryConfigurationDto; +import org.camunda.bpm.engine.rest.dto.telemetry.TelemetryDataDto; +import org.camunda.bpm.engine.telemetry.TelemetryData; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TelemetryRestServiceImpl extends AbstractRestProcessEngineAware implements TelemetryRestService { + + public TelemetryRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public void configureTelemetry(TelemetryConfigurationDto dto) { + boolean enableTelemetry = dto.isEnableTelemetry(); + + ManagementService managementService = getProcessEngine().getManagementService(); + + managementService.toggleTelemetry(enableTelemetry); + } + + @Override + public TelemetryConfigurationDto getTelemetryConfiguration() { + ManagementService managementService = getProcessEngine().getManagementService(); + + Boolean telemetryEnabled = managementService.isTelemetryEnabled(); + return new TelemetryConfigurationDto(telemetryEnabled); + } + + @Override + public TelemetryDataDto getTelemetryData() { + ManagementService managementService = getProcessEngine().getManagementService(); + TelemetryData data = managementService.getTelemetryData(); + + return TelemetryDataDto.fromEngineDto(data); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TenantRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TenantRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..b8e418eb10cfc6429c09827092782a3a2b45e25e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/TenantRestServiceImpl.java @@ -0,0 +1,120 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Resources.TENANT; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.util.List; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.identity.TenantQuery; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.TenantDto; +import org.camunda.bpm.engine.rest.dto.identity.TenantQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.identity.TenantResource; +import org.camunda.bpm.engine.rest.sub.identity.impl.TenantResourceImpl; +import org.camunda.bpm.engine.rest.util.PathUtil; +import org.camunda.bpm.engine.rest.util.QueryUtil;; + +public class TenantRestServiceImpl extends AbstractAuthorizedRestResource implements TenantRestService { + + public TenantRestServiceImpl(String engineName, final ObjectMapper objectMapper) { + super(engineName, TENANT, ANY, objectMapper); + } + + @Override + public TenantResource getTenant(String id) { + id = PathUtil.decodePathParam(id); + return new TenantResourceImpl(getProcessEngine().getName(), id, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List queryTenants(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + TenantQueryDto queryDto = new TenantQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + TenantQuery query = queryDto.toQuery(getProcessEngine()); + + List tenants = QueryUtil.list(query, firstResult, maxResults); + + return TenantDto.fromTenantList(tenants ); + } + + @Override + public CountResultDto getTenantCount(UriInfo uriInfo) { + TenantQueryDto queryDto = new TenantQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + + TenantQuery query = queryDto.toQuery(getProcessEngine()); + long count = query.count(); + + return new CountResultDto(count); + } + + @Override + public void createTenant(TenantDto dto) { + + if (getIdentityService().isReadOnly()) { + throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only."); + } + + Tenant newTenant = getIdentityService().newTenant(dto.getId()); + dto.update(newTenant); + + getIdentityService().saveTenant(newTenant); + } + + @Override + public ResourceOptionsDto availableOperations(UriInfo context) { + + UriBuilder baseUriBuilder = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(TenantRestService.PATH); + + ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); + + // GET / + URI baseUri = baseUriBuilder.build(); + resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); + + // GET /count + URI countUri = baseUriBuilder.clone().path("/count").build(); + resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); + + // POST /create + if (!getIdentityService().isReadOnly() && isAuthorized(CREATE)) { + URI createUri = baseUriBuilder.clone().path("/create").build(); + resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); + } + + return resourceOptionsDto; + } + + protected IdentityService getIdentityService() { + return getProcessEngine().getIdentityService(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/UserRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/UserRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a4ea4a8aec9338df5606a9b65736065e257a7cb1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/UserRestServiceImpl.java @@ -0,0 +1,148 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Resources.USER; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.net.URI; +import java.util.List; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.UserDto; +import org.camunda.bpm.engine.rest.dto.identity.UserProfileDto; +import org.camunda.bpm.engine.rest.dto.identity.UserQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.identity.UserResource; +import org.camunda.bpm.engine.rest.sub.identity.impl.UserResourceImpl; +import org.camunda.bpm.engine.rest.util.PathUtil; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Daniel Meyer + * + */ +public class UserRestServiceImpl extends AbstractAuthorizedRestResource implements UserRestService { + + public UserRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, USER, ANY, objectMapper); + } + + @Override + public UserResource getUser(String id) { + id = PathUtil.decodePathParam(id); + return new UserResourceImpl(getProcessEngine().getName(), id, relativeRootResourcePath, getObjectMapper()); + } + + @Override + public List queryUsers(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + UserQueryDto queryDto = new UserQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryUsers(queryDto, firstResult, maxResults); + } + + public List queryUsers(UserQueryDto queryDto, Integer firstResult, Integer maxResults) { + + queryDto.setObjectMapper(getObjectMapper()); + UserQuery query = queryDto.toQuery(getProcessEngine()); + + List resultList = QueryUtil.list(query, firstResult, maxResults); + + return UserProfileDto.fromUserList(resultList); + } + + + @Override + public CountResultDto getUserCount(UriInfo uriInfo) { + UserQueryDto queryDto = new UserQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return getUserCount(queryDto); + } + + protected CountResultDto getUserCount(UserQueryDto queryDto) { + UserQuery query = queryDto.toQuery(getProcessEngine()); + long count = query.count(); + return new CountResultDto(count); + } + + @Override + public void createUser(UserDto userDto) { + final IdentityService identityService = getIdentityService(); + + if(identityService.isReadOnly()) { + throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only."); + } + + UserProfileDto profile = userDto.getProfile(); + if(profile == null || profile.getId() == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "request object must provide profile information with valid id."); + } + + User newUser = identityService.newUser(profile.getId()); + profile.update(newUser); + + if(userDto.getCredentials() != null) { + newUser.setPassword(userDto.getCredentials().getPassword()); + } + + identityService.saveUser(newUser); + + } + + @Override + public ResourceOptionsDto availableOperations(UriInfo context) { + + final IdentityService identityService = getIdentityService(); + + UriBuilder baseUriBuilder = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(UserRestService.PATH); + + ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto(); + + // GET / + URI baseUri = baseUriBuilder.build(); + resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list"); + + // GET /count + URI countUri = baseUriBuilder.clone().path("/count").build(); + resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count"); + + // POST /create + if(!identityService.isReadOnly() && isAuthorized(CREATE)) { + URI createUri = baseUriBuilder.clone().path("/create").build(); + resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create"); + } + + return resourceOptionsDto; + } + + // utility methods ////////////////////////////////////// + + protected IdentityService getIdentityService() { + return getProcessEngine().getIdentityService(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/VariableInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/VariableInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..301f4c0e33bb9cc9917e2b46eabcaf0bf3892c7c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/VariableInstanceRestServiceImpl.java @@ -0,0 +1,94 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.VariableInstanceRestService; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.runtime.VariableInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.VariableInstanceQueryDto; +import org.camunda.bpm.engine.rest.sub.runtime.VariableInstanceResource; +import org.camunda.bpm.engine.rest.sub.runtime.impl.VariableInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.runtime.VariableInstanceQuery; + +public class VariableInstanceRestServiceImpl extends AbstractRestProcessEngineAware implements VariableInstanceRestService { + + public VariableInstanceRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @Override + public VariableInstanceResource getVariableInstance(String id) { + return new VariableInstanceResourceImpl(id, getProcessEngine()); + } + + @Override + public List getVariableInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { + VariableInstanceQueryDto queryDto = new VariableInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryVariableInstances(queryDto, firstResult, maxResults, deserializeObjectValues); + } + + @Override + public List queryVariableInstances(VariableInstanceQueryDto queryDto, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + VariableInstanceQuery query = queryDto.toQuery(engine); + + // disable binary fetching by default. + query.disableBinaryFetching(); + + // disable custom object fetching by default. Cannot be done to not break existing API + if (!deserializeObjectValues) { + query.disableCustomObjectDeserialization(); + } + + List matchingInstances = QueryUtil.list(query, firstResult, maxResults); + + List instanceResults = new ArrayList<>(); + for (VariableInstance instance : matchingInstances) { + VariableInstanceDto resultInstance = VariableInstanceDto.fromVariableInstance(instance); + instanceResults.add(resultInstance); + } + return instanceResults; + } + + @Override + public CountResultDto getVariableInstancesCount(UriInfo uriInfo) { + VariableInstanceQueryDto queryDto = new VariableInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters()); + return queryVariableInstancesCount(queryDto); + } + + @Override + public CountResultDto queryVariableInstancesCount(VariableInstanceQueryDto queryDto) { + ProcessEngine engine = getProcessEngine(); + queryDto.setObjectMapper(getObjectMapper()); + VariableInstanceQuery query = queryDto.toQuery(engine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/VersionRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/VersionRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..862c77838c5bd0ce7f70fcef8bef6a83b9df0094 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/VersionRestService.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.VersionDto; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@Produces(MediaType.APPLICATION_JSON) +public class VersionRestService extends AbstractRestProcessEngineAware { + + public static final String PATH = "/version"; + + public VersionRestService(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + public VersionDto getVersion() { + return new VersionDto(VersionRestService.class.getPackage().getImplementationVersion()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/application/ContainerManagedProcessEngineProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/application/ContainerManagedProcessEngineProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..571ab74511c632d8fee786c0387f0272e2a3c543 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/application/ContainerManagedProcessEngineProvider.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.application; + +import org.camunda.bpm.BpmPlatform; +import org.camunda.bpm.ProcessEngineService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngines; +import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider; + +import java.util.Set; + +/** + *

Uses the {@link ProcessEngineService} and exposes the default process engine

+ * + * @author Daniel Meyer + */ +public class ContainerManagedProcessEngineProvider implements ProcessEngineProvider { + + @Override + public ProcessEngine getDefaultProcessEngine() { + ProcessEngine defaultProcessEngine = BpmPlatform.getDefaultProcessEngine(); + if(defaultProcessEngine != null) { + return defaultProcessEngine; + } else { + return ProcessEngines.getDefaultProcessEngine(false); + } + } + + @Override + public ProcessEngine getProcessEngine(String name) { + return ProcessEngines.getProcessEngine(name); + } + + @Override + public Set getProcessEngineNames() { + return ProcessEngines.getProcessEngines().keySet(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricActivityInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricActivityInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e687a19843838980f821f0fa10121d3ac0d4da92 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricActivityInstanceRestServiceImpl.java @@ -0,0 +1,88 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityInstanceQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricActivityInstanceRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricActivityInstanceResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricActivityInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricActivityInstanceRestServiceImpl implements HistoricActivityInstanceRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricActivityInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricActivityInstanceResource getHistoricCaseInstance(String activityInstanceId) { + return new HistoricActivityInstanceResourceImpl(processEngine, activityInstanceId); + } + + @Override + public List getHistoricActivityInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricActivityInstanceQueryDto queryHistoricActivityInstanceDto = new HistoricActivityInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricActivityInstances(queryHistoricActivityInstanceDto, firstResult, maxResults); + } + + @Override + public List queryHistoricActivityInstances(HistoricActivityInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + queryDto.setObjectMapper(objectMapper); + HistoricActivityInstanceQuery query = queryDto.toQuery(processEngine); + + List matchingHistoricActivityInstances = QueryUtil.list(query, firstResult, maxResults); + + List historicActivityInstanceResults = new ArrayList(); + for (HistoricActivityInstance historicActivityInstance : matchingHistoricActivityInstances) { + HistoricActivityInstanceDto resultHistoricActivityInstance = new HistoricActivityInstanceDto(); + HistoricActivityInstanceDto.fromHistoricActivityInstance(resultHistoricActivityInstance, historicActivityInstance); + historicActivityInstanceResults.add(resultHistoricActivityInstance); + } + return historicActivityInstanceResults; + } + + @Override + public CountResultDto getHistoricActivityInstancesCount(UriInfo uriInfo) { + HistoricActivityInstanceQueryDto queryDto = new HistoricActivityInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricActivityInstancesCount(queryDto); + } + + @Override + public CountResultDto queryHistoricActivityInstancesCount(HistoricActivityInstanceQueryDto queryDto) { + queryDto.setObjectMapper(objectMapper); + HistoricActivityInstanceQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricActivityStatisticsQueryDto.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricActivityStatisticsQueryDto.java new file mode 100644 index 0000000000000000000000000000000000000000..9420d9313a28ac6b7196a960c45d77e4fd78554f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricActivityStatisticsQueryDto.java @@ -0,0 +1,164 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import java.util.Date; +import java.util.Map; + +import javax.ws.rs.core.MultivaluedMap; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricActivityStatisticsQuery; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; +import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoricActivityStatisticsQueryDto extends AbstractQueryDto { + + protected static final String SORT_ORDER_ACTIVITY_ID = "activityId"; + + protected String processDefinitionId; + + protected Boolean includeCanceled; + protected Boolean includeFinished; + protected Boolean includeCompleteScope; + protected Boolean includeIncidents; + + protected Date startedAfter; + protected Date startedBefore; + protected Date finishedAfter; + protected Date finishedBefore; + + protected String[] processInstanceIdIn; + + public HistoricActivityStatisticsQueryDto(ObjectMapper objectMapper, String processDefinitionId, MultivaluedMap queryParameters) { + super(objectMapper, queryParameters); + this.processDefinitionId = processDefinitionId; + } + + /* + * This is a path param and set from within the resource method + */ + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + } + + @CamundaQueryParam(value = "canceled", converter = BooleanConverter.class) + public void setIncludeCanceled(Boolean includeCanceled) { + this.includeCanceled = includeCanceled; + } + + @CamundaQueryParam(value = "finished", converter = BooleanConverter.class) + public void setIncludeFinished(Boolean includeFinished) { + this.includeFinished = includeFinished; + } + + @CamundaQueryParam(value = "completeScope", converter = BooleanConverter.class) + public void setIncludeCompleteScope(Boolean includeCompleteScope) { + this.includeCompleteScope = includeCompleteScope; + } + + @CamundaQueryParam(value = "incidents", converter = BooleanConverter.class) + public void setIncludeIncidents(Boolean includeClosedIncidents) { + this.includeIncidents = includeClosedIncidents; + } + + @CamundaQueryParam(value = "startedAfter", converter = DateConverter.class) + public void setStartedAfter(Date startedAfter) { + this.startedAfter = startedAfter; + } + + @CamundaQueryParam(value = "startedBefore", converter = DateConverter.class) + public void setStartedBefore(Date startedBefore) { + this.startedBefore = startedBefore; + } + + @CamundaQueryParam(value = "finishedAfter", converter = DateConverter.class) + public void setFinishedAfter(Date finishedAfter) { + this.finishedAfter = finishedAfter; + } + + @CamundaQueryParam(value = "finishedBefore", converter = DateConverter.class) + public void setFinishedBefore(Date finishedBefore) { + this.finishedBefore = finishedBefore; + } + + @CamundaQueryParam(value = "processInstanceIdIn", converter = StringArrayConverter.class) + public void setProcessInstanceIdIn(String[] processInstanceIdIn) { + this.processInstanceIdIn = processInstanceIdIn; + } + + @Override + protected boolean isValidSortByValue(String value) { + return SORT_ORDER_ACTIVITY_ID.equals(value); + } + + @Override + protected HistoricActivityStatisticsQuery createNewQuery(ProcessEngine engine) { + return engine.getHistoryService().createHistoricActivityStatisticsQuery(processDefinitionId); + } + + @Override + protected void applyFilters(HistoricActivityStatisticsQuery query) { + + if (includeCanceled != null && includeCanceled) { + query.includeCanceled(); + } + + if (includeFinished != null && includeFinished) { + query.includeFinished(); + } + + if (includeCompleteScope != null && includeCompleteScope) { + query.includeCompleteScope(); + } + + if (includeIncidents !=null && includeIncidents) { + query.includeIncidents(); + } + + if (startedAfter != null) { + query.startedAfter(startedAfter); + } + + if (startedBefore != null) { + query.startedBefore(startedBefore); + } + + if (finishedAfter != null) { + query.finishedAfter(finishedAfter); + } + + if (finishedBefore != null) { + query.finishedBefore(finishedBefore); + } + + if (processInstanceIdIn != null) { + query.processInstanceIdIn(processInstanceIdIn); + } + } + + @Override + protected void applySortBy(HistoricActivityStatisticsQuery query, String sortBy, Map parameters, ProcessEngine engine) { + if (SORT_ORDER_ACTIVITY_ID.equals(sortBy)) { + query.orderByActivityId(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricBatchRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricBatchRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..b415752a526ddb0db2bbe1393c2cb3542d64bf56 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricBatchRestServiceImpl.java @@ -0,0 +1,142 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.batch.history.HistoricBatch; +import org.camunda.bpm.engine.batch.history.HistoricBatchQuery; +import org.camunda.bpm.engine.history.CleanableHistoricBatchReport; +import org.camunda.bpm.engine.history.CleanableHistoricBatchReportResult; +import org.camunda.bpm.engine.history.SetRemovalTimeSelectModeForHistoricBatchesBuilder; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.batch.CleanableHistoricBatchReportDto; +import org.camunda.bpm.engine.rest.dto.history.batch.CleanableHistoricBatchReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchDto; +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchQueryDto; +import org.camunda.bpm.engine.rest.dto.history.batch.removaltime.SetRemovalTimeToHistoricBatchesDto; +import org.camunda.bpm.engine.rest.history.HistoricBatchRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricBatchResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricBatchResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricBatchRestServiceImpl implements HistoricBatchRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricBatchRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricBatchResource getHistoricBatch(String batchId) { + return new HistoricBatchResourceImpl(processEngine, batchId); + } + + @Override + public List getHistoricBatches(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricBatchQueryDto queryDto = new HistoricBatchQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricBatchQuery query = queryDto.toQuery(processEngine); + + List matchingBatches = QueryUtil.list(query, firstResult, maxResults); + + List batchResults = new ArrayList(); + for (HistoricBatch matchingBatch : matchingBatches) { + batchResults.add(HistoricBatchDto.fromBatch(matchingBatch)); + } + return batchResults; + } + + @Override + public CountResultDto getHistoricBatchesCount(UriInfo uriInfo) { + HistoricBatchQueryDto queryDto = new HistoricBatchQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricBatchQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + return new CountResultDto(count); + } + + @Override + public List getCleanableHistoricBatchesReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + CleanableHistoricBatchReportDto queryDto = new CleanableHistoricBatchReportDto(objectMapper, uriInfo.getQueryParameters()); + CleanableHistoricBatchReport query = queryDto.toQuery(processEngine); + + List reportResult = QueryUtil.list(query, firstResult, maxResults); + + return CleanableHistoricBatchReportResultDto.convert(reportResult); + } + + @Override + public CountResultDto getCleanableHistoricBatchesReportCount(UriInfo uriInfo) { + CleanableHistoricBatchReportDto queryDto = new CleanableHistoricBatchReportDto(objectMapper, uriInfo.getQueryParameters()); + queryDto.setObjectMapper(objectMapper); + CleanableHistoricBatchReport query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricBatchesDto dto) { + HistoryService historyService = processEngine.getHistoryService(); + + HistoricBatchQuery historicBatchQuery = null; + + if (dto.getHistoricBatchQuery() != null) { + historicBatchQuery = dto.getHistoricBatchQuery().toQuery(processEngine); + + } + + SetRemovalTimeSelectModeForHistoricBatchesBuilder builder = + historyService.setRemovalTimeToHistoricBatches(); + + if (dto.isCalculatedRemovalTime()) { + builder.calculatedRemovalTime(); + + } + + Date removalTime = dto.getAbsoluteRemovalTime(); + if (dto.getAbsoluteRemovalTime() != null) { + builder.absoluteRemovalTime(removalTime); + + } + + if (dto.isClearedRemovalTime()) { + builder.clearedRemovalTime(); + + } + + builder.byIds(dto.getHistoricBatchIds()); + builder.byQuery(historicBatchQuery); + + Batch batch = builder.executeAsync(); + return BatchDto.fromBatch(batch); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseActivityInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseActivityInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e7901de63d12dbbd399631285522089112ae05b5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseActivityInstanceRestServiceImpl.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstance; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseActivityInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseActivityInstanceQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricCaseActivityInstanceRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricCaseActivityInstanceResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricCaseActivityInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricCaseActivityInstanceRestServiceImpl implements HistoricCaseActivityInstanceRestService { + + protected ProcessEngine processEngine; + protected ObjectMapper objectMapper; + + public HistoricCaseActivityInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricCaseActivityInstanceResource getHistoricCaseInstance(String caseActivityInstanceId) { + return new HistoricCaseActivityInstanceResourceImpl(processEngine, caseActivityInstanceId); + } + + @Override + public List getHistoricCaseActivityInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricCaseActivityInstanceQueryDto queryHistoricCaseActivityInstanceDto = new HistoricCaseActivityInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricCaseActivityInstances(queryHistoricCaseActivityInstanceDto, firstResult, maxResults); + } + + public List queryHistoricCaseActivityInstances(HistoricCaseActivityInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + HistoricCaseActivityInstanceQuery query = queryDto.toQuery(processEngine); + + List matchingHistoricCaseActivityInstances = QueryUtil.list(query, firstResult, maxResults); + + List historicCaseActivityInstanceResults = new ArrayList(); + for (HistoricCaseActivityInstance historicCaseActivityInstance : matchingHistoricCaseActivityInstances) { + HistoricCaseActivityInstanceDto resultHistoricCaseActivityInstance = HistoricCaseActivityInstanceDto.fromHistoricCaseActivityInstance(historicCaseActivityInstance); + historicCaseActivityInstanceResults.add(resultHistoricCaseActivityInstance); + } + return historicCaseActivityInstanceResults; + } + + @Override + public CountResultDto getHistoricCaseActivityInstancesCount(UriInfo uriInfo) { + HistoricCaseActivityInstanceQueryDto queryDto = new HistoricCaseActivityInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricCaseActivityInstancesCount(queryDto); + } + + public CountResultDto queryHistoricCaseActivityInstancesCount(HistoricCaseActivityInstanceQueryDto queryDto) { + HistoricCaseActivityInstanceQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + + return new CountResultDto(count); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f893e8e04aabfc0a989582f5d8cc44fc6efd3abf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseDefinitionRestServiceImpl.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricCaseInstanceReport; +import org.camunda.bpm.engine.history.CleanableHistoricCaseInstanceReportResult; +import org.camunda.bpm.engine.history.HistoricCaseActivityStatistics; +import org.camunda.bpm.engine.history.HistoricCaseActivityStatisticsQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricCaseInstanceReportDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricCaseInstanceReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseActivityStatisticsDto; +import org.camunda.bpm.engine.rest.history.HistoricCaseDefinitionRestService; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Roman Smirnov + * + */ +public class HistoricCaseDefinitionRestServiceImpl implements HistoricCaseDefinitionRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricCaseDefinitionRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public List getHistoricCaseActivityStatistics(String caseDefinitionId) { + HistoryService historyService = processEngine.getHistoryService(); + + HistoricCaseActivityStatisticsQuery historicCaseActivityStatisticsQuery = + historyService.createHistoricCaseActivityStatisticsQuery(caseDefinitionId); + + List statistics = + historicCaseActivityStatisticsQuery.unlimitedList(); + + List result = new ArrayList(); + for (HistoricCaseActivityStatistics currentStatistics : statistics) { + result.add(HistoricCaseActivityStatisticsDto.fromHistoricCaseActivityStatistics(currentStatistics)); + } + + return result; + } + + @Override + public List getCleanableHistoricCaseInstanceReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + CleanableHistoricCaseInstanceReportDto queryDto = new CleanableHistoricCaseInstanceReportDto(objectMapper, uriInfo.getQueryParameters()); + CleanableHistoricCaseInstanceReport query = queryDto.toQuery(processEngine); + + List reportResult = QueryUtil.list(query, firstResult, maxResults); + + return CleanableHistoricCaseInstanceReportResultDto.convert(reportResult); + } + + @Override + public CountResultDto getCleanableHistoricCaseInstanceReportCount(UriInfo uriInfo) { + CleanableHistoricCaseInstanceReportDto queryDto = new CleanableHistoricCaseInstanceReportDto(objectMapper, uriInfo.getQueryParameters()); + queryDto.setObjectMapper(objectMapper); + CleanableHistoricCaseInstanceReport query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..5c4d45d633e76f731b16db13f52f452c723f47e0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricCaseInstanceRestServiceImpl.java @@ -0,0 +1,84 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricCaseInstance; +import org.camunda.bpm.engine.history.HistoricCaseInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseInstanceQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricCaseInstanceRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricCaseInstanceResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricCaseInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricCaseInstanceRestServiceImpl implements HistoricCaseInstanceRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricCaseInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricCaseInstanceResource getHistoricCaseInstance(String caseInstanceId) { + return new HistoricCaseInstanceResourceImpl(processEngine, caseInstanceId); + } + + @Override + public List getHistoricCaseInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricCaseInstanceQueryDto queryHistoricCaseInstanceDto = new HistoricCaseInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricCaseInstances(queryHistoricCaseInstanceDto, firstResult, maxResults); + } + + @Override + public List queryHistoricCaseInstances(HistoricCaseInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + HistoricCaseInstanceQuery query = queryDto.toQuery(processEngine); + + List matchingHistoricCaseInstances = QueryUtil.list(query, firstResult, maxResults); + + List historicCaseInstanceDtoResults = new ArrayList(); + for (HistoricCaseInstance historicCaseInstance : matchingHistoricCaseInstances) { + HistoricCaseInstanceDto resultHistoricCaseInstanceDto = HistoricCaseInstanceDto.fromHistoricCaseInstance(historicCaseInstance); + historicCaseInstanceDtoResults.add(resultHistoricCaseInstanceDto); + } + return historicCaseInstanceDtoResults; + } + + @Override + public CountResultDto getHistoricCaseInstancesCount(UriInfo uriInfo) { + HistoricCaseInstanceQueryDto queryDto = new HistoricCaseInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricCaseInstancesCount(queryDto); + } + + @Override + public CountResultDto queryHistoricCaseInstancesCount(HistoricCaseInstanceQueryDto queryDto) { + HistoricCaseInstanceQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + + return new CountResultDto(count); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a89930aa913b8d13a0902a14c64a261b6e043d6a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionDefinitionRestServiceImpl.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricDecisionInstanceReport; +import org.camunda.bpm.engine.history.CleanableHistoricDecisionInstanceReportResult; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricDecisionInstanceReportDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricDecisionInstanceReportResultDto; +import org.camunda.bpm.engine.rest.history.HistoricDecisionDefinitionRestService; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricDecisionDefinitionRestServiceImpl implements HistoricDecisionDefinitionRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricDecisionDefinitionRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public List getCleanableHistoricDecisionInstanceReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + CleanableHistoricDecisionInstanceReportDto queryDto = new CleanableHistoricDecisionInstanceReportDto(objectMapper, uriInfo.getQueryParameters()); + CleanableHistoricDecisionInstanceReport query = queryDto.toQuery(processEngine); + + List reportResult = QueryUtil.list(query, firstResult, maxResults); + + return CleanableHistoricDecisionInstanceReportResultDto.convert(reportResult); + } + + @Override + public CountResultDto getCleanableHistoricDecisionInstanceReportCount(UriInfo uriInfo) { + CleanableHistoricDecisionInstanceReportDto queryDto = new CleanableHistoricDecisionInstanceReportDto(objectMapper, uriInfo.getQueryParameters()); + queryDto.setObjectMapper(objectMapper); + CleanableHistoricDecisionInstanceReport query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..804c002a2ea8508fb67398298cbb97beb3d93b95 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionInstanceRestServiceImpl.java @@ -0,0 +1,152 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceQuery; +import org.camunda.bpm.engine.history.SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.history.batch.DeleteHistoricDecisionInstancesDto; +import org.camunda.bpm.engine.rest.dto.history.batch.removaltime.SetRemovalTimeToHistoricDecisionInstancesDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.history.HistoricDecisionInstanceRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricDecisionInstanceResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricDecisionInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricDecisionInstanceRestServiceImpl implements HistoricDecisionInstanceRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricDecisionInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricDecisionInstanceResource getHistoricDecisionInstance(String decisionInstanceId) { + return new HistoricDecisionInstanceResourceImpl(processEngine, decisionInstanceId); + } + + @Override + public List getHistoricDecisionInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricDecisionInstanceQueryDto queryHistoricDecisionInstanceDto = new HistoricDecisionInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricDecisionInstances(queryHistoricDecisionInstanceDto, firstResult, maxResults); + } + + public List queryHistoricDecisionInstances(HistoricDecisionInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + HistoricDecisionInstanceQuery query = queryDto.toQuery(processEngine); + + List matchingHistoricDecisionInstances = QueryUtil.list(query, firstResult, maxResults); + + List historicDecisionInstanceDtoResults = new ArrayList(); + for (HistoricDecisionInstance historicDecisionInstance : matchingHistoricDecisionInstances) { + HistoricDecisionInstanceDto resultHistoricDecisionInstanceDto = HistoricDecisionInstanceDto.fromHistoricDecisionInstance(historicDecisionInstance); + historicDecisionInstanceDtoResults.add(resultHistoricDecisionInstanceDto); + } + return historicDecisionInstanceDtoResults; + } + + @Override + public CountResultDto getHistoricDecisionInstancesCount(UriInfo uriInfo) { + HistoricDecisionInstanceQueryDto queryDto = new HistoricDecisionInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricDecisionInstancesCount(queryDto); + } + + public CountResultDto queryHistoricDecisionInstancesCount(HistoricDecisionInstanceQueryDto queryDto) { + HistoricDecisionInstanceQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + + return new CountResultDto(count); + } + + @Override + public BatchDto deleteAsync(DeleteHistoricDecisionInstancesDto dto) { + HistoricDecisionInstanceQuery decisionInstanceQuery = null; + if (dto.getHistoricDecisionInstanceQuery() != null) { + decisionInstanceQuery = dto.getHistoricDecisionInstanceQuery().toQuery(processEngine); + } + + try { + List historicDecisionInstanceIds = dto.getHistoricDecisionInstanceIds(); + String deleteReason = dto.getDeleteReason(); + Batch batch = processEngine.getHistoryService().deleteHistoricDecisionInstancesAsync(historicDecisionInstanceIds, decisionInstanceQuery, deleteReason); + return BatchDto.fromBatch(batch); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricDecisionInstancesDto dto) { + HistoryService historyService = processEngine.getHistoryService(); + + HistoricDecisionInstanceQuery historicDecisionInstanceQuery = null; + + if (dto.getHistoricDecisionInstanceQuery() != null) { + historicDecisionInstanceQuery = dto.getHistoricDecisionInstanceQuery().toQuery(processEngine); + + } + + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder = + historyService.setRemovalTimeToHistoricDecisionInstances(); + + if (dto.isCalculatedRemovalTime()) { + builder.calculatedRemovalTime(); + + } + + Date removalTime = dto.getAbsoluteRemovalTime(); + if (dto.getAbsoluteRemovalTime() != null) { + builder.absoluteRemovalTime(removalTime); + + } + + if (dto.isClearedRemovalTime()) { + builder.clearedRemovalTime(); + + } + + builder.byIds(dto.getHistoricDecisionInstanceIds()); + builder.byQuery(historicDecisionInstanceQuery); + + if (dto.isHierarchical()) { + builder.hierarchical(); + + } + + Batch batch = builder.executeAsync(); + return BatchDto.fromBatch(batch); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionStatisticsRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionStatisticsRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..2bb3e9f50df46a70c90d821ad5d3797ccf3625c0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDecisionStatisticsRestServiceImpl.java @@ -0,0 +1,57 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceStatistics; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceStatisticsQuery; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceStatisticsDto; +import org.camunda.bpm.engine.rest.history.HistoricDecisionStatisticsRestService; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Askar Akhmerov + */ +public class HistoricDecisionStatisticsRestServiceImpl implements HistoricDecisionStatisticsRestService { + + protected ProcessEngine processEngine; + + public HistoricDecisionStatisticsRestServiceImpl(ProcessEngine processEngine) { + this.processEngine = processEngine; + } + + @Override + public List getDecisionStatistics(String decisionRequirementsDefinitionId, String decisionInstanceId) { + List result = new ArrayList(); + HistoricDecisionInstanceStatisticsQuery statisticsQuery = processEngine.getHistoryService() + .createHistoricDecisionInstanceStatisticsQuery(decisionRequirementsDefinitionId); + if (decisionInstanceId != null) { + statisticsQuery.decisionInstanceId(decisionInstanceId); + } + + List statistics = statisticsQuery.unlimitedList(); + + for (HistoricDecisionInstanceStatistics stats : statistics) { + result.add(HistoricDecisionInstanceStatisticsDto.fromDecisionDefinitionStatistics(stats)); + } + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDetailRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDetailRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..39dbebbb2dadfeb8e7d90e20448dc382aa3a8851 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricDetailRestServiceImpl.java @@ -0,0 +1,101 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricDetail; +import org.camunda.bpm.engine.history.HistoricDetailQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDetailDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDetailQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricDetailRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricDetailResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricDetailResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Roman Smirnov + * + */ +public class HistoricDetailRestServiceImpl implements HistoricDetailRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricDetailRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricDetailResource historicDetail(String detailId) { + return new HistoricDetailResourceImpl(detailId, processEngine); + } + + @Override + public List getHistoricDetails(UriInfo uriInfo, Integer firstResult, + Integer maxResults, boolean deserializeObjectValues) { + HistoricDetailQueryDto queryDto = new HistoricDetailQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricDetailQuery query = queryDto.toQuery(processEngine); + + return executeHistoricDetailQuery(query, firstResult, maxResults, deserializeObjectValues); + } + + @Override + public List queryHistoricDetails(HistoricDetailQueryDto queryDto, Integer firstResult, + Integer maxResults, boolean deserializeObjectValues) { + HistoricDetailQuery query = queryDto.toQuery(processEngine); + + return executeHistoricDetailQuery(query, firstResult, maxResults, deserializeObjectValues); + } + + @Override + public CountResultDto getHistoricDetailsCount(UriInfo uriInfo) { + HistoricDetailQueryDto queryDto = new HistoricDetailQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricDetailQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + private List executeHistoricDetailQuery(HistoricDetailQuery query, Integer firstResult, + Integer maxResults, boolean deserializeObjectValues) { + + query.disableBinaryFetching(); + if (!deserializeObjectValues) { + query.disableCustomObjectDeserialization(); + } + + List queryResult = QueryUtil.list(query, firstResult, maxResults); + + List result = new ArrayList(); + for (HistoricDetail historicDetail : queryResult) { + HistoricDetailDto dto = HistoricDetailDto.fromHistoricDetail(historicDetail); + result.add(dto); + } + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricExternalTaskLogRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricExternalTaskLogRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..8f618ab337d9b23b761fee73ece7901a79ada48c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricExternalTaskLogRestServiceImpl.java @@ -0,0 +1,89 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricExternalTaskLog; +import org.camunda.bpm.engine.history.HistoricExternalTaskLogQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricExternalTaskLogDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricExternalTaskLogQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricExternalTaskLogRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricExternalTaskLogResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricExternalTaskLogResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricExternalTaskLogRestServiceImpl implements HistoricExternalTaskLogRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricExternalTaskLogRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricExternalTaskLogResource getHistoricExternalTaskLog(String historicExternalTaskLogId) { + return new HistoricExternalTaskLogResourceImpl(historicExternalTaskLogId, processEngine); + } + + @Override + public List getHistoricExternalTaskLogs(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricExternalTaskLogQueryDto queryDto = new HistoricExternalTaskLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricExternalTaskLogs(queryDto, firstResult, maxResults); + } + + @Override + public List queryHistoricExternalTaskLogs(HistoricExternalTaskLogQueryDto queryDto, Integer firstResult, Integer maxResults) { + queryDto.setObjectMapper(objectMapper); + HistoricExternalTaskLogQuery query = queryDto.toQuery(processEngine); + + List matchingHistoricExternalTaskLogs = QueryUtil.list(query, firstResult, maxResults); + + List results = new ArrayList(); + for (HistoricExternalTaskLog historicExternalTaskLog : matchingHistoricExternalTaskLogs) { + HistoricExternalTaskLogDto result = HistoricExternalTaskLogDto.fromHistoricExternalTaskLog(historicExternalTaskLog); + results.add(result); + } + + return results; + } + + @Override + public CountResultDto getHistoricExternalTaskLogsCount(UriInfo uriInfo) { + HistoricExternalTaskLogQueryDto queryDto = new HistoricExternalTaskLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricExternalTaskLogsCount(queryDto); + } + + @Override + public CountResultDto queryHistoricExternalTaskLogsCount(HistoricExternalTaskLogQueryDto queryDto) { + queryDto.setObjectMapper(objectMapper); + HistoricExternalTaskLogQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricIdentityLinkLogRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricIdentityLinkLogRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1e831385b63317777e72f5859801265dd4bff46e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricIdentityLinkLogRestServiceImpl.java @@ -0,0 +1,73 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricIdentityLinkLog; +import org.camunda.bpm.engine.history.HistoricIdentityLinkLogQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricIdentityLinkLogDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricIdentityLinkLogQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricIdentityLinkLogRestService; +import org.camunda.bpm.engine.rest.util.QueryUtil; +/** + * + * @author Deivarayan Azhagappan + * + */ +public class HistoricIdentityLinkLogRestServiceImpl implements HistoricIdentityLinkLogRestService{ + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricIdentityLinkLogRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public List getHistoricIdentityLinks(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricIdentityLinkLogQueryDto queryDto = new HistoricIdentityLinkLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricIdentityLinkLogQuery query = queryDto.toQuery(processEngine); + + List queryResult = QueryUtil.list(query, firstResult, maxResults); + List result = new ArrayList(); + for (HistoricIdentityLinkLog historicIdentityLink : queryResult) { + HistoricIdentityLinkLogDto dto = HistoricIdentityLinkLogDto.fromHistoricIdentityLink(historicIdentityLink); + result.add(dto); + } + return result; + } + + @Override + public CountResultDto getHistoricIdentityLinksCount(UriInfo uriInfo) { + HistoricIdentityLinkLogQueryDto queryDto = new HistoricIdentityLinkLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricIdentityLinkLogQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricIncidentRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricIncidentRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..d2d4ac3de2c1e772fb7977d70b7411adf103e3f8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricIncidentRestServiceImpl.java @@ -0,0 +1,74 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricIncident; +import org.camunda.bpm.engine.history.HistoricIncidentQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricIncidentDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricIncidentQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricIncidentRestService; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Roman Smirnov + * + */ +public class HistoricIncidentRestServiceImpl implements HistoricIncidentRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricIncidentRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public List getHistoricIncidents(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricIncidentQueryDto queryDto = new HistoricIncidentQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricIncidentQuery query = queryDto.toQuery(processEngine); + + List queryResult = QueryUtil.list(query, firstResult, maxResults); + + List result = new ArrayList(); + for (HistoricIncident historicIncident : queryResult) { + HistoricIncidentDto dto = HistoricIncidentDto.fromHistoricIncident(historicIncident); + result.add(dto); + } + + return result; + } + + @Override + public CountResultDto getHistoricIncidentsCount(UriInfo uriInfo) { + HistoricIncidentQueryDto queryDto = new HistoricIncidentQueryDto(objectMapper, uriInfo.getQueryParameters()); + HistoricIncidentQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricJobLogRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricJobLogRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..9b2b9e259b1178673bd06226ec90b7a99a310269 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricJobLogRestServiceImpl.java @@ -0,0 +1,93 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricJobLog; +import org.camunda.bpm.engine.history.HistoricJobLogQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricJobLogDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricJobLogQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricJobLogRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricJobLogResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricJobLogResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Roman Smirnov + * + */ +public class HistoricJobLogRestServiceImpl implements HistoricJobLogRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricJobLogRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricJobLogResource getHistoricJobLog(String historicJobLogId) { + return new HistoricJobLogResourceImpl(historicJobLogId, processEngine); + } + + @Override + public List getHistoricJobLogs(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricJobLogQueryDto queryDto = new HistoricJobLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricJobLogs(queryDto, firstResult, maxResults); + } + + @Override + public List queryHistoricJobLogs(HistoricJobLogQueryDto queryDto, Integer firstResult, Integer maxResults) { + queryDto.setObjectMapper(objectMapper); + HistoricJobLogQuery query = queryDto.toQuery(processEngine); + + List matchingHistoricJobLogs = QueryUtil.list(query, firstResult, maxResults); + + List results = new ArrayList(); + for (HistoricJobLog historicJobLog : matchingHistoricJobLogs) { + HistoricJobLogDto result = HistoricJobLogDto.fromHistoricJobLog(historicJobLog); + results.add(result); + } + + return results; + } + + @Override + public CountResultDto getHistoricJobLogsCount(UriInfo uriInfo) { + HistoricJobLogQueryDto queryDto = new HistoricJobLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricJobLogsCount(queryDto); + } + + @Override + public CountResultDto queryHistoricJobLogsCount(HistoricJobLogQueryDto queryDto) { + queryDto.setObjectMapper(objectMapper); + HistoricJobLogQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricProcessDefinitionRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricProcessDefinitionRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..447dca3b8013c1357a2d68c4b8af31bc9fe7862c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricProcessDefinitionRestServiceImpl.java @@ -0,0 +1,82 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReport; +import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReportResult; +import org.camunda.bpm.engine.history.HistoricActivityStatistics; +import org.camunda.bpm.engine.history.HistoricActivityStatisticsQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricProcessInstanceReportDto; +import org.camunda.bpm.engine.rest.dto.history.CleanableHistoricProcessInstanceReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityStatisticsDto; +import org.camunda.bpm.engine.rest.history.HistoricProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.impl.AbstractRestProcessEngineAware; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricProcessDefinitionRestServiceImpl extends AbstractRestProcessEngineAware implements HistoricProcessDefinitionRestService { + + public HistoricProcessDefinitionRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + super(processEngine.getName(), objectMapper); + } + + @Override + public List getHistoricActivityStatistics(UriInfo uriInfo, String processDefinitionId) { + HistoricActivityStatisticsQueryDto queryDto = new HistoricActivityStatisticsQueryDto(getObjectMapper(), processDefinitionId, uriInfo.getQueryParameters()); + + HistoricActivityStatisticsQuery query = queryDto.toQuery(getProcessEngine()); + + List result = new ArrayList<>(); + + List statistics = query.unlimitedList(); + + for (HistoricActivityStatistics currentStatistics : statistics) { + result.add(HistoricActivityStatisticsDto.fromHistoricActivityStatistics(currentStatistics)); + } + + return result; + } + + @Override + public List getCleanableHistoricProcessInstanceReport(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + CleanableHistoricProcessInstanceReportDto queryDto = new CleanableHistoricProcessInstanceReportDto(objectMapper, uriInfo.getQueryParameters()); + CleanableHistoricProcessInstanceReport query = queryDto.toQuery(getProcessEngine()); + + List reportResult = QueryUtil.list(query, firstResult, maxResults); + + return CleanableHistoricProcessInstanceReportResultDto.convert(reportResult); + } + + @Override + public CountResultDto getCleanableHistoricProcessInstanceReportCount(UriInfo uriInfo) { + CleanableHistoricProcessInstanceReportDto queryDto = new CleanableHistoricProcessInstanceReportDto(objectMapper, uriInfo.getQueryParameters()); + queryDto.setObjectMapper(objectMapper); + CleanableHistoricProcessInstanceReport query = queryDto.toQuery(getProcessEngine()); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricProcessInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricProcessInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..7beda5c8211e53fd7a961b0488d0d0f7f6638663 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricProcessInstanceRestServiceImpl.java @@ -0,0 +1,236 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.core.Variant; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.history.ReportResult; +import org.camunda.bpm.engine.history.SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.converter.ReportResultToCsvConverter; +import org.camunda.bpm.engine.rest.dto.history.DeleteHistoricProcessInstancesDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceReportDto; +import org.camunda.bpm.engine.rest.dto.history.ReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.batch.removaltime.SetRemovalTimeToHistoricProcessInstancesDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.history.HistoricProcessInstanceRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricProcessInstanceResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricProcessInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; + + public class HistoricProcessInstanceRestServiceImpl implements HistoricProcessInstanceRestService { + + public static final MediaType APPLICATION_CSV_TYPE = new MediaType("application", "csv"); + public static final MediaType TEXT_CSV_TYPE = new MediaType("text", "csv"); + public static final List VARIANTS = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, APPLICATION_CSV_TYPE, TEXT_CSV_TYPE).add().build(); + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricProcessInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricProcessInstanceResource getHistoricProcessInstance(String processInstanceId) { + return new HistoricProcessInstanceResourceImpl(processEngine, processInstanceId); + } + + @Override + public List getHistoricProcessInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricProcessInstanceQueryDto queryHistoriProcessInstanceDto = new HistoricProcessInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricProcessInstances(queryHistoriProcessInstanceDto, firstResult, maxResults); + } + + @Override + public List queryHistoricProcessInstances(HistoricProcessInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + queryDto.setObjectMapper(objectMapper); + HistoricProcessInstanceQuery query = queryDto.toQuery(processEngine); + + List matchingHistoricProcessInstances = QueryUtil.list(query, firstResult, maxResults); + + List historicProcessInstanceDtoResults = new ArrayList(); + for (HistoricProcessInstance historicProcessInstance : matchingHistoricProcessInstances) { + HistoricProcessInstanceDto resultHistoricProcessInstanceDto = HistoricProcessInstanceDto.fromHistoricProcessInstance(historicProcessInstance); + historicProcessInstanceDtoResults.add(resultHistoricProcessInstanceDto); + } + return historicProcessInstanceDtoResults; + } + + @Override + public CountResultDto getHistoricProcessInstancesCount(UriInfo uriInfo) { + HistoricProcessInstanceQueryDto queryDto = new HistoricProcessInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricProcessInstancesCount(queryDto); + } + + @Override + public CountResultDto queryHistoricProcessInstancesCount(HistoricProcessInstanceQueryDto queryDto) { + queryDto.setObjectMapper(objectMapper); + HistoricProcessInstanceQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @SuppressWarnings("unchecked") + protected List queryHistoricProcessInstanceReport(UriInfo uriInfo) { + HistoricProcessInstanceReportDto reportDto = new HistoricProcessInstanceReportDto(objectMapper, uriInfo.getQueryParameters()); + return (List) reportDto.executeReport(processEngine); + } + + @Override + public Response getHistoricProcessInstancesReport(UriInfo uriInfo, Request request) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + MediaType mediaType = variant.getMediaType(); + + if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { + List result = getReportResultAsJson(uriInfo); + return Response.ok(result, mediaType).build(); + } + else if (APPLICATION_CSV_TYPE.equals(mediaType) || TEXT_CSV_TYPE.equals(mediaType)) { + String csv = getReportResultAsCsv(uriInfo); + return Response + .ok(csv, mediaType) + .header("Content-Disposition", URLEncodingUtil.buildAttachmentValue("process-instance-report.csv")) + .build(); + } + } + throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + @Override + public BatchDto deleteAsync(DeleteHistoricProcessInstancesDto dto) { + HistoryService historyService = processEngine.getHistoryService(); + + HistoricProcessInstanceQuery historicProcessInstanceQuery = null; + if (dto.getHistoricProcessInstanceQuery() != null) { + historicProcessInstanceQuery = dto.getHistoricProcessInstanceQuery().toQuery(processEngine); + } + + try { + Batch batch; + batch = historyService.deleteHistoricProcessInstancesAsync(dto.getHistoricProcessInstanceIds(), historicProcessInstanceQuery, dto.getDeleteReason()); + return BatchDto.fromBatch(batch); + + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricProcessInstancesDto dto) { + HistoryService historyService = processEngine.getHistoryService(); + + HistoricProcessInstanceQuery historicProcessInstanceQuery = null; + + if (dto.getHistoricProcessInstanceQuery() != null) { + historicProcessInstanceQuery = dto.getHistoricProcessInstanceQuery().toQuery(processEngine); + + } + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builder = + historyService.setRemovalTimeToHistoricProcessInstances(); + + if (dto.isCalculatedRemovalTime()) { + builder.calculatedRemovalTime(); + + } + + Date removalTime = dto.getAbsoluteRemovalTime(); + if (dto.getAbsoluteRemovalTime() != null) { + builder.absoluteRemovalTime(removalTime); + + } + + if (dto.isClearedRemovalTime()) { + builder.clearedRemovalTime(); + + } + + builder.byIds(dto.getHistoricProcessInstanceIds()); + builder.byQuery(historicProcessInstanceQuery); + + if (dto.isHierarchical()) { + builder.hierarchical(); + + } + + if (dto.isUpdateInChunks()) { + builder.updateInChunks(); + } + + Integer chunkSize = dto.getUpdateChunkSize(); + if (chunkSize != null) { + builder.chunkSize(chunkSize); + } + + Batch batch = builder.executeAsync(); + return BatchDto.fromBatch(batch); + } + + protected List getReportResultAsJson(UriInfo uriInfo) { + List reports = queryHistoricProcessInstanceReport(uriInfo); + List result = new ArrayList(); + for (ReportResult report : reports) { + result.add(ReportResultDto.fromReportResult(report)); + } + return result; + } + + protected String getReportResultAsCsv(UriInfo uriInfo) { + List reports = queryHistoricProcessInstanceReport(uriInfo); + MultivaluedMap queryParameters = uriInfo.getQueryParameters(); + String reportType = queryParameters.getFirst("reportType"); + return ReportResultToCsvConverter.convertReportResult(reports, reportType); + } + + @Override + public Response deleteHistoricVariableInstancesByProcessInstanceId(String processInstanceId) { + try { + processEngine.getHistoryService().deleteHistoricVariableInstancesByProcessInstanceId(processInstanceId); + } catch (NotFoundException nfe) { // rewrite status code from bad request (400) to not found (404) + throw new InvalidRequestException(Status.NOT_FOUND, nfe.getMessage()); + } + // return no content (204) since resource is deleted + return Response.noContent().build(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricTaskInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricTaskInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..af10eb63871b460ee30778d521c82e380b837966 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricTaskInstanceRestServiceImpl.java @@ -0,0 +1,131 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; +import org.camunda.bpm.engine.history.HistoricTaskInstanceReportResult; +import org.camunda.bpm.engine.history.ReportResult; +import org.camunda.bpm.engine.rest.dto.AbstractReportDto; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceReportQueryDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceReportResultDto; +import org.camunda.bpm.engine.rest.dto.history.ReportResultDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.history.HistoricTaskInstanceRestService; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Roman Smirnov + * + */ +public class HistoricTaskInstanceRestServiceImpl implements HistoricTaskInstanceRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricTaskInstanceRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public List getHistoricTaskInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + HistoricTaskInstanceQueryDto queryDto = new HistoricTaskInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricTaskInstances(queryDto, firstResult, maxResults); + } + + @Override + public List queryHistoricTaskInstances(HistoricTaskInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) { + queryDto.setObjectMapper(objectMapper); + HistoricTaskInstanceQuery query = queryDto.toQuery(processEngine); + + List match = QueryUtil.list(query, firstResult, maxResults); + + List result = new ArrayList(); + for (HistoricTaskInstance taskInstance : match) { + HistoricTaskInstanceDto taskInstanceDto = HistoricTaskInstanceDto.fromHistoricTaskInstance(taskInstance); + result.add(taskInstanceDto); + } + return result; + } + + @Override + public CountResultDto getHistoricTaskInstancesCount(UriInfo uriInfo) { + HistoricTaskInstanceQueryDto queryDto = new HistoricTaskInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricTaskInstancesCount(queryDto); + } + + @Override + public CountResultDto queryHistoricTaskInstancesCount(HistoricTaskInstanceQueryDto queryDto) { + queryDto.setObjectMapper(objectMapper); + HistoricTaskInstanceQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } + + @Override + public Response getHistoricTaskInstanceReport(UriInfo uriInfo) { + HistoricTaskInstanceReportQueryDto queryDto = new HistoricTaskInstanceReportQueryDto(objectMapper, uriInfo.getQueryParameters()); + Response response; + + if (AbstractReportDto.REPORT_TYPE_DURATION.equals(queryDto.getReportType())) { + List reportResults = queryDto.executeReport(processEngine); + response = Response.ok(generateDurationDto(reportResults)).build(); + } else if (AbstractReportDto.REPORT_TYPE_COUNT.equals(queryDto.getReportType())) { + List reportResults = queryDto.executeCompletedReport(processEngine); + response = Response.ok(generateCountDto(reportResults)).build(); + } else { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Parameter reportType is not set."); + } + + return response; + } + + protected List generateCountDto(List results) { + List dtoList = new ArrayList(); + + for( HistoricTaskInstanceReportResult result : results ) { + dtoList.add(HistoricTaskInstanceReportResultDto.fromHistoricTaskInstanceReportResult(result)); + } + + return dtoList; + } + + protected List generateDurationDto(List results) { + List dtoList = new ArrayList(); + + for( ReportResult result : results ) { + dtoList.add(ReportResultDto.fromReportResult(result)); + } + + return dtoList; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricVariableInstanceRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricVariableInstanceRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f22f437e8f72286499549957db043f6c353a1929 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoricVariableInstanceRestServiceImpl.java @@ -0,0 +1,94 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.List; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricVariableInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricVariableInstanceQueryDto; +import org.camunda.bpm.engine.rest.history.HistoricVariableInstanceRestService; +import org.camunda.bpm.engine.rest.sub.history.HistoricVariableInstanceResource; +import org.camunda.bpm.engine.rest.sub.history.impl.HistoricVariableInstanceResourceImpl; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +public class HistoricVariableInstanceRestServiceImpl implements HistoricVariableInstanceRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoricVariableInstanceRestServiceImpl(ObjectMapper objectMapper,ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public HistoricVariableInstanceResource variableInstanceResource(String variableId) { + return new HistoricVariableInstanceResourceImpl(variableId, processEngine); + } + + @Override + public List getHistoricVariableInstances(UriInfo uriInfo, Integer firstResult, + Integer maxResults, boolean deserializeObjectValues) { + HistoricVariableInstanceQueryDto queryDto = new HistoricVariableInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricVariableInstances(queryDto, firstResult, maxResults, deserializeObjectValues); + } + + @Override + public List queryHistoricVariableInstances(HistoricVariableInstanceQueryDto queryDto, + Integer firstResult, Integer maxResults, boolean deserializeObjectValues) { + queryDto.setObjectMapper(objectMapper); + HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine); + query.disableBinaryFetching(); + + if (!deserializeObjectValues) { + query.disableCustomObjectDeserialization(); + } + + List matchingHistoricVariableInstances = QueryUtil.list(query, firstResult, maxResults); + + List historicVariableInstanceDtoResults = new ArrayList(); + for (HistoricVariableInstance historicVariableInstance : matchingHistoricVariableInstances) { + HistoricVariableInstanceDto resultHistoricVariableInstance = HistoricVariableInstanceDto.fromHistoricVariableInstance(historicVariableInstance); + historicVariableInstanceDtoResults.add(resultHistoricVariableInstance); + } + return historicVariableInstanceDtoResults; + } + + @Override + public CountResultDto getHistoricVariableInstancesCount(UriInfo uriInfo) { + HistoricVariableInstanceQueryDto queryDto = new HistoricVariableInstanceQueryDto(objectMapper, uriInfo.getQueryParameters()); + return queryHistoricVariableInstancesCount(queryDto); + } + + @Override + public CountResultDto queryHistoricVariableInstancesCount(HistoricVariableInstanceQueryDto queryDto) { + queryDto.setObjectMapper(objectMapper); + HistoricVariableInstanceQuery query = queryDto.toQuery(processEngine); + + long count = query.count(); + CountResultDto result = new CountResultDto(); + result.setCount(count); + + return result; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoryCleanupRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoryCleanupRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..02413d95717c206bd52523af923a6c00bcc82468 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoryCleanupRestServiceImpl.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.jobexecutor.historycleanup.BatchWindow; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.rest.dto.history.HistoryCleanupConfigurationDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDto; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.history.HistoryCleanupRestService; +import org.camunda.bpm.engine.runtime.Job; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoryCleanupRestServiceImpl implements HistoryCleanupRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public HistoryCleanupRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + public JobDto cleanupAsync(boolean immediatelyDue) { + Job job = processEngine.getHistoryService().cleanUpHistoryAsync(immediatelyDue); + return JobDto.fromJob(job); + } + + public JobDto findCleanupJob() { + Job job = processEngine.getHistoryService().findHistoryCleanupJob(); + if (job == null) { + throw new RestException(Status.NOT_FOUND, "History cleanup job does not exist"); + } + return JobDto.fromJob(job); + } + + public List findCleanupJobs() { + List jobs = processEngine.getHistoryService().findHistoryCleanupJobs(); + if (jobs == null || jobs.isEmpty()) { + throw new RestException(Status.NOT_FOUND, "History cleanup jobs are empty"); + } + List dtos = new ArrayList(); + for (Job job : jobs) { + JobDto dto = JobDto.fromJob(job); + dtos.add(dto); + } + return dtos; + } + + public HistoryCleanupConfigurationDto getHistoryCleanupConfiguration() { + ProcessEngineConfigurationImpl engineConfiguration = + (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration(); + + HistoryCleanupConfigurationDto configurationDto = new HistoryCleanupConfigurationDto(); + configurationDto.setEnabled(engineConfiguration.isHistoryCleanupEnabled()); + + BatchWindow batchWindow = engineConfiguration.getBatchWindowManager() + .getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), engineConfiguration); + + if (batchWindow != null) { + configurationDto.setBatchWindowStartTime(batchWindow.getStart()); + configurationDto.setBatchWindowEndTime(batchWindow.getEnd()); + } + + return configurationDto; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoryRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoryRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..b19842f0b8f000485adebb0b21db8a4bfde99fdd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/HistoryRestServiceImpl.java @@ -0,0 +1,127 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import org.camunda.bpm.engine.rest.history.HistoricActivityInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoricProcessDefinitionRestService; +import org.camunda.bpm.engine.rest.history.HistoricBatchRestService; +import org.camunda.bpm.engine.rest.history.HistoricCaseActivityInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoricCaseDefinitionRestService; +import org.camunda.bpm.engine.rest.history.HistoricCaseInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoricDecisionDefinitionRestService; +import org.camunda.bpm.engine.rest.history.HistoricDecisionInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoricDecisionStatisticsRestService; +import org.camunda.bpm.engine.rest.history.HistoricDetailRestService; +import org.camunda.bpm.engine.rest.history.HistoricExternalTaskLogRestService; +import org.camunda.bpm.engine.rest.history.HistoricIdentityLinkLogRestService; +import org.camunda.bpm.engine.rest.history.HistoricIncidentRestService; +import org.camunda.bpm.engine.rest.history.HistoricJobLogRestService; +import org.camunda.bpm.engine.rest.history.HistoricProcessInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoricTaskInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoricVariableInstanceRestService; +import org.camunda.bpm.engine.rest.history.HistoryCleanupRestService; +import org.camunda.bpm.engine.rest.history.HistoryRestService; +import org.camunda.bpm.engine.rest.history.UserOperationLogRestService; + +import org.camunda.bpm.engine.rest.impl.AbstractRestProcessEngineAware; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class HistoryRestServiceImpl extends AbstractRestProcessEngineAware implements HistoryRestService { + + public HistoryRestServiceImpl(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + } + + public HistoricProcessInstanceRestService getProcessInstanceService() { + return new HistoricProcessInstanceRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricCaseInstanceRestService getCaseInstanceService() { + return new HistoricCaseInstanceRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricActivityInstanceRestService getActivityInstanceService() { + return new HistoricActivityInstanceRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricCaseActivityInstanceRestService getCaseActivityInstanceService() { + return new HistoricCaseActivityInstanceRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricVariableInstanceRestService getVariableInstanceService() { + return new HistoricVariableInstanceRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricProcessDefinitionRestService getProcessDefinitionService() { + return new HistoricProcessDefinitionRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricDecisionDefinitionRestService getDecisionDefinitionService() { + return new HistoricDecisionDefinitionRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricDecisionStatisticsRestService getDecisionStatisticsService() { + return new HistoricDecisionStatisticsRestServiceImpl(getProcessEngine()); + } + + public HistoricCaseDefinitionRestService getCaseDefinitionService() { + return new HistoricCaseDefinitionRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public UserOperationLogRestService getUserOperationLogRestService() { + return new UserOperationLogRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricDetailRestService getDetailService() { + return new HistoricDetailRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricTaskInstanceRestService getTaskInstanceService() { + return new HistoricTaskInstanceRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricIncidentRestService getIncidentService() { + return new HistoricIncidentRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricIdentityLinkLogRestService getIdentityLinkService() { + return new HistoricIdentityLinkLogRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricJobLogRestService getJobLogService() { + return new HistoricJobLogRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricDecisionInstanceRestService getDecisionInstanceService() { + return new HistoricDecisionInstanceRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + public HistoricBatchRestService getBatchService() { + return new HistoricBatchRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + @Override + public HistoricExternalTaskLogRestService getExternalTaskLogService() { + return new HistoricExternalTaskLogRestServiceImpl(getObjectMapper(), getProcessEngine()); + } + + @Override + public HistoryCleanupRestService getHistoryCleanupRestService() { + return new HistoryCleanupRestServiceImpl(getObjectMapper(), getProcessEngine()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/UserOperationLogRestServiceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/UserOperationLogRestServiceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a0c226282ecc08ba345f86846e3bd6fdadffdc61 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/history/UserOperationLogRestServiceImpl.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.history; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.UserOperationLogQuery; +import org.camunda.bpm.engine.rest.dto.AnnotationDto; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.history.UserOperationLogEntryDto; +import org.camunda.bpm.engine.rest.dto.history.UserOperationLogQueryDto; +import org.camunda.bpm.engine.rest.history.UserOperationLogRestService; +import org.camunda.bpm.engine.rest.util.QueryUtil; + +/** + * @author Danny Gräf + */ +public class UserOperationLogRestServiceImpl implements UserOperationLogRestService { + + protected ObjectMapper objectMapper; + protected ProcessEngine processEngine; + + public UserOperationLogRestServiceImpl(ObjectMapper objectMapper, ProcessEngine processEngine) { + this.objectMapper = objectMapper; + this.processEngine = processEngine; + } + + @Override + public CountResultDto queryUserOperationCount(UriInfo uriInfo) { + UserOperationLogQueryDto queryDto = new UserOperationLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + UserOperationLogQuery query = queryDto.toQuery(processEngine); + return new CountResultDto(query.count()); + } + + @Override + public List queryUserOperationEntries(UriInfo uriInfo, Integer firstResult, Integer maxResults) { + UserOperationLogQueryDto queryDto = new UserOperationLogQueryDto(objectMapper, uriInfo.getQueryParameters()); + UserOperationLogQuery query = queryDto.toQuery(processEngine); + return UserOperationLogEntryDto.map(QueryUtil.list(query, firstResult, maxResults)); + } + + @Override + public Response setAnnotation(String operationId, AnnotationDto annotationDto) { + String annotation = annotationDto.getAnnotation(); + + processEngine.getHistoryService() + .setAnnotationForOperationLogById(operationId, annotation); + + return Response.noContent().build(); + } + + @Override + public Response clearAnnotation(String operationId) { + processEngine.getHistoryService() + .clearAnnotationForOperationLogById(operationId); + + return Response.noContent().build(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/optimize/OptimizeRestService.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/optimize/OptimizeRestService.java new file mode 100644 index 0000000000000000000000000000000000000000..290817ad2394dd5afcad7ef2472abb032784bee6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/optimize/OptimizeRestService.java @@ -0,0 +1,346 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.optimize; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricIncident; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.history.UserOperationLogEntry; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricIncidentEntity; +import org.camunda.bpm.engine.impl.persistence.entity.optimize.OptimizeHistoricIdentityLinkLogEntity; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricIncidentDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricTaskInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.UserOperationLogEntryDto; +import org.camunda.bpm.engine.rest.dto.history.optimize.OptimizeHistoricActivityInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.optimize.OptimizeHistoricIdentityLinkLogDto; +import org.camunda.bpm.engine.rest.dto.history.optimize.OptimizeHistoricVariableUpdateDto; +import org.camunda.bpm.engine.rest.impl.AbstractRestProcessEngineAware; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Produces(MediaType.APPLICATION_JSON) +public class OptimizeRestService extends AbstractRestProcessEngineAware { + + public static final String PATH = "/optimize"; + + private final DateConverter dateConverter; + + public OptimizeRestService(String engineName, ObjectMapper objectMapper) { + super(engineName, objectMapper); + dateConverter = new DateConverter(); + dateConverter.setObjectMapper(objectMapper); + } + + @GET + @Path("/activity-instance/completed") + public List getCompletedHistoricActivityInstances(@QueryParam("finishedAfter") String finishedAfterAsString, + @QueryParam("finishedAt") String finishedAtAsString, + @QueryParam("maxResults") int maxResults) { + + Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); + Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + + List historicActivityInstances = + config.getOptimizeService().getCompletedHistoricActivityInstances(finishedAfter, finishedAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricActivityInstance instance : historicActivityInstances) { + OptimizeHistoricActivityInstanceDto dto = OptimizeHistoricActivityInstanceDto.fromHistoricActivityInstance(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/activity-instance/running") + public List getRunningHistoricActivityInstances(@QueryParam("startedAfter") String startedAfterAsString, + @QueryParam("startedAt") String startedAtAsString, + @QueryParam("maxResults") int maxResults) { + + Date startedAfter = dateConverter.convertQueryParameterToType(startedAfterAsString); + Date startedAt = dateConverter.convertQueryParameterToType(startedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + + List historicActivityInstances = + config.getOptimizeService().getRunningHistoricActivityInstances(startedAfter, startedAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricActivityInstance instance : historicActivityInstances) { + OptimizeHistoricActivityInstanceDto dto = OptimizeHistoricActivityInstanceDto.fromHistoricActivityInstance(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/task-instance/completed") + public List getCompletedHistoricTaskInstances(@QueryParam("finishedAfter") String finishedAfterAsString, + @QueryParam("finishedAt") String finishedAtAsString, + @QueryParam("maxResults") int maxResults) { + + Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); + Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + + List historicTaskInstances = + config.getOptimizeService().getCompletedHistoricTaskInstances(finishedAfter, finishedAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricTaskInstance instance : historicTaskInstances) { + HistoricTaskInstanceDto dto = HistoricTaskInstanceDto.fromHistoricTaskInstance(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/task-instance/running") + public List getRunningHistoricTaskInstances(@QueryParam("startedAfter") String startedAfterAsString, + @QueryParam("startedAt") String startedAtAsString, + @QueryParam("maxResults") int maxResults) { + + Date startedAfter = dateConverter.convertQueryParameterToType(startedAfterAsString); + Date startedAt = dateConverter.convertQueryParameterToType(startedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + + List historicTaskInstances = + config.getOptimizeService().getRunningHistoricTaskInstances(startedAfter, startedAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricTaskInstance instance : historicTaskInstances) { + HistoricTaskInstanceDto dto = HistoricTaskInstanceDto.fromHistoricTaskInstance(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/user-operation") + public List getHistoricUserOperationLogs(@QueryParam("occurredAfter") String occurredAfterAsString, + @QueryParam("occurredAt") String occurredAtAsString, + @QueryParam("maxResults") int maxResults) { + + Date occurredAfter = dateConverter.convertQueryParameterToType(occurredAfterAsString); + Date occurredAt = dateConverter.convertQueryParameterToType(occurredAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + + List operationLogEntries = + config.getOptimizeService().getHistoricUserOperationLogs(occurredAfter, occurredAt, maxResults); + + List result = new ArrayList<>(); + for (UserOperationLogEntry logEntry : operationLogEntries) { + UserOperationLogEntryDto dto = UserOperationLogEntryDto.map(logEntry); + result.add(dto); + } + return result; + } + + @GET + @Path("/identity-link-log") + public List getHistoricIdentityLinkLogs(@QueryParam("occurredAfter") String occurredAfterAsString, + @QueryParam("occurredAt") String occurredAtAsString, + @QueryParam("maxResults") int maxResults) { + + Date occurredAfter = dateConverter.convertQueryParameterToType(occurredAfterAsString); + Date occurredAt = dateConverter.convertQueryParameterToType(occurredAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + + List operationLogEntries = + config.getOptimizeService().getHistoricIdentityLinkLogs(occurredAfter, occurredAt, maxResults); + + List result = new ArrayList<>(); + for (OptimizeHistoricIdentityLinkLogEntity logEntry : operationLogEntries) { + OptimizeHistoricIdentityLinkLogDto dto = OptimizeHistoricIdentityLinkLogDto.fromHistoricIdentityLink(logEntry); + result.add(dto); + } + return result; + } + + @GET + @Path("/process-instance/completed") + public List getCompletedHistoricProcessInstances(@QueryParam("finishedAfter") String finishedAfterAsString, + @QueryParam("finishedAt") String finishedAtAsString, + @QueryParam("maxResults") int maxResults) { + Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); + Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + List historicProcessInstances = + config.getOptimizeService().getCompletedHistoricProcessInstances(finishedAfter, finishedAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricProcessInstance instance : historicProcessInstances) { + HistoricProcessInstanceDto dto = HistoricProcessInstanceDto.fromHistoricProcessInstance(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/process-instance/running") + public List getRunningHistoricProcessInstances(@QueryParam("startedAfter") String startedAfterAsString, + @QueryParam("startedAt") String startedAtAsString, + @QueryParam("maxResults") int maxResults) { + Date startedAfter = dateConverter.convertQueryParameterToType(startedAfterAsString); + Date startedAt = dateConverter.convertQueryParameterToType(startedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + List historicProcessInstances = + config.getOptimizeService().getRunningHistoricProcessInstances(startedAfter, startedAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricProcessInstance instance : historicProcessInstances) { + HistoricProcessInstanceDto dto = HistoricProcessInstanceDto.fromHistoricProcessInstance(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/variable-update") + public List getHistoricVariableUpdates(@QueryParam("occurredAfter") String occurredAfterAsString, + @QueryParam("occurredAt") String occurredAtAsString, + @QueryParam("excludeObjectValues") boolean excludeObjectValues, + @QueryParam("maxResults") int maxResults) { + Date occurredAfter = dateConverter.convertQueryParameterToType(occurredAfterAsString); + Date occurredAt = dateConverter.convertQueryParameterToType(occurredAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + List historicVariableUpdates = + config.getOptimizeService().getHistoricVariableUpdates(occurredAfter, occurredAt, excludeObjectValues, maxResults); + + List result = new ArrayList<>(); + for (HistoricVariableUpdate instance : historicVariableUpdates) { + OptimizeHistoricVariableUpdateDto dto = + OptimizeHistoricVariableUpdateDto.fromHistoricVariableUpdate(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/incident/completed") + public List getCompletedHistoricIncidents(@QueryParam("finishedAfter") String finishedAfterAsString, + @QueryParam("finishedAt") String finishedAtAsString, + @QueryParam("maxResults") int maxResults) { + Date finishedAfter = dateConverter.convertQueryParameterToType(finishedAfterAsString); + Date finishedAt = dateConverter.convertQueryParameterToType(finishedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + List historicIncidents = + config.getOptimizeService().getCompletedHistoricIncidents(finishedAfter, finishedAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricIncident instance : historicIncidents) { + HistoricIncidentDto dto = HistoricIncidentDto.fromHistoricIncident(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/incident/open") + public List getOpenHistoricIncidents(@QueryParam("createdAfter") String createdAfterAsString, + @QueryParam("createdAt") String createdAtAsString, + @QueryParam("maxResults") int maxResults) { + Date createdAfter = dateConverter.convertQueryParameterToType(createdAfterAsString); + Date createdAt = dateConverter.convertQueryParameterToType(createdAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + List historicIncidents = + config.getOptimizeService().getOpenHistoricIncidents(createdAfter, createdAt, maxResults); + + List result = new ArrayList<>(); + for (HistoricIncident instance : historicIncidents) { + HistoricIncidentDto dto = HistoricIncidentDto.fromHistoricIncident(instance); + result.add(dto); + } + return result; + } + + @GET + @Path("/decision-instance") + public List getHistoricDecisionInstances(@QueryParam("evaluatedAfter") String evaluatedAfterAsString, + @QueryParam("evaluatedAt") String evaluatedAtAsString, + @QueryParam("maxResults") int maxResults) { + Date evaluatedAfter = dateConverter.convertQueryParameterToType(evaluatedAfterAsString); + Date evaluatedAt = dateConverter.convertQueryParameterToType(evaluatedAtAsString); + maxResults = ensureValidMaxResults(maxResults); + + ProcessEngineConfigurationImpl config = + (ProcessEngineConfigurationImpl) getProcessEngine().getProcessEngineConfiguration(); + List historicDecisionInstances = + config.getOptimizeService().getHistoricDecisionInstances(evaluatedAfter, evaluatedAt, maxResults); + + List resultList = new ArrayList<>(); + for (HistoricDecisionInstance historicDecisionInstance : historicDecisionInstances) { + HistoricDecisionInstanceDto dto = + HistoricDecisionInstanceDto.fromHistoricDecisionInstance(historicDecisionInstance); + resultList.add(dto); + } + + return resultList; + } + + protected int ensureValidMaxResults(int givenMaxResults) { + return givenMaxResults > 0 ? givenMaxResults : Integer.MAX_VALUE; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/web/bootstrap/RestContainerBootstrap.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/web/bootstrap/RestContainerBootstrap.java new file mode 100644 index 0000000000000000000000000000000000000000..39f9e0ff0e838dcd28ee8343a75914a6883abee6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/impl/web/bootstrap/RestContainerBootstrap.java @@ -0,0 +1,36 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl.web.bootstrap; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; + +import org.camunda.bpm.engine.rest.util.WebApplicationUtil; + +public class RestContainerBootstrap implements ServletContextListener { + + @Override + public void contextInitialized(ServletContextEvent sce) { + WebApplicationUtil.setApplicationServer(sce.getServletContext().getServerInfo()); + } + + @Override + public void contextDestroyed(ServletContextEvent sce) { + // do nothing + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/JacksonConfigurator.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/JacksonConfigurator.java new file mode 100644 index 0000000000000000000000000000000000000000..98311e43d61f580356140fedbb7020b6b57f419c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/JacksonConfigurator.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.mapper; + +import java.text.SimpleDateFormat; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; + +import org.camunda.bpm.engine.rest.hal.Hal; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +@Provider +@Produces({MediaType.APPLICATION_JSON, Hal.APPLICATION_HAL_JSON}) +public class JacksonConfigurator implements ContextResolver { + + public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + public static String dateFormatString = DEFAULT_DATE_FORMAT; + + public static ObjectMapper configureObjectMapper(ObjectMapper mapper) { + SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString); + mapper.setDateFormat(dateFormat); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); + + mapper.registerModule(new JavaTimeModule()); + + return mapper; + } + + @Override + public ObjectMapper getContext(Class clazz) { + return configureObjectMapper(new ObjectMapper()); + } + + public static void setDateFormatString(String dateFormatString) { + JacksonConfigurator.dateFormatString = dateFormatString; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/MultipartFormData.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/MultipartFormData.java new file mode 100644 index 0000000000000000000000000000000000000000..82f4fd46042871dd4bb04aba98290d16c3a2deb0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/MultipartFormData.java @@ -0,0 +1,117 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.mapper; + +import org.apache.commons.fileupload.FileItemStream; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.rest.exception.RestException; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Custom implementation of Multipart Form Data which can be used for handling requests. + *

+ * Provides access to the form parts via {@link #getNamedPart(String)}. + * + * @author Daniel Meyer + * + */ +public class MultipartFormData { + + protected Map formParts = new HashMap(); + + public void addPart(FormPart formPart) { + formParts.put(formPart.getFieldName(), formPart); + } + + public FormPart getNamedPart(String name) { + return formParts.get(name); + } + + public Set getPartNames() { + return formParts.keySet(); + } + + /** + * Dto representing a part in a multipart form. + * + */ + public static class FormPart { + + protected String fieldName; + protected String contentType; + protected String textContent; + protected String fileName; + protected byte[] binaryContent; + + public FormPart(FileItemStream stream) { + fieldName = stream.getFieldName(); + contentType = stream.getContentType(); + binaryContent = readBinaryContent(stream); + fileName = stream.getName(); + + if(contentType == null || contentType.contains(MediaType.TEXT_PLAIN)) { + textContent = new String(binaryContent, StandardCharsets.UTF_8); + } + } + + public FormPart() { + } + + protected byte[] readBinaryContent(FileItemStream stream) { + InputStream inputStream = getInputStream(stream); + return IoUtil.readInputStream(inputStream, stream.getFieldName()); + } + + protected InputStream getInputStream(FileItemStream stream) { + try { + return stream.openStream(); + } catch (IOException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + } + } + + public String getFieldName() { + return fieldName; + } + + public String getContentType() { + return contentType; + } + + public String getTextContent() { + return textContent; + } + + public byte[] getBinaryContent() { + return binaryContent; + } + + public String getFileName() { + return fileName; + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/MultipartPayloadProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/MultipartPayloadProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..3747dc191aef7205a31de3c8b6728a619c10dcd0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/mapper/MultipartPayloadProvider.java @@ -0,0 +1,138 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.mapper; + +import org.apache.commons.fileupload.FileItemIterator; +import org.apache.commons.fileupload.FileItemStream; +import org.apache.commons.fileupload.FileUpload; +import org.apache.commons.fileupload.RequestContext; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData.FormPart; + +import javax.ws.rs.Consumes; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.ext.MessageBodyReader; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.InputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +/** +*

Provides a {@link MessageBodyReader} for {@link MultipartFormData}. This allows writing resources which +* consume {@link MediaType#MULTIPART_FORM_DATA} which is parsed into a {@link MultipartFormData} object:

+* +*
+* {@literal @}POST
+* {@literal @}Consumes(MediaType.MULTIPART_FORM_DATA)
+* void handleMultipartPost(MultipartFormData multipartFormData);
+* 
+* +*

The implementation used apache commons fileupload in order to parse the request and populate an instance of +* {@link MultipartFormData}.

+* +* @author Daniel Meyer +*/ +@Provider +@Consumes(MediaType.MULTIPART_FORM_DATA) +public class MultipartPayloadProvider implements MessageBodyReader { + + public static final String TYPE_NAME = "multipart"; + public static final String SUB_TYPE_NAME = "form-data"; + + public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { + return TYPE_NAME.equals(mediaType.getType().toLowerCase()) + && SUB_TYPE_NAME.equals(mediaType.getSubtype().toLowerCase()); + } + + public MultipartFormData readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { + + final MultipartFormData multipartFormData = createMultipartFormDataInstance(); + final FileUpload fileUpload = createFileUploadInstance(); + + String contentType = httpHeaders.getFirst("content-type"); + RestMultipartRequestContext requestContext = createRequestContext(entityStream, contentType); + + // parse the request (populates the multipartFormData) + parseRequest(multipartFormData, fileUpload, requestContext); + + return multipartFormData; + + } + + protected FileUpload createFileUploadInstance() { + return new FileUpload(); + } + + protected MultipartFormData createMultipartFormDataInstance() { + return new MultipartFormData(); + } + + protected void parseRequest(MultipartFormData multipartFormData, FileUpload fileUpload, RestMultipartRequestContext requestContext) { + try { + FileItemIterator itemIterator = fileUpload.getItemIterator(requestContext); + while (itemIterator.hasNext()) { + FileItemStream stream = itemIterator.next(); + multipartFormData.addPart(new FormPart(stream)); + } + } catch (Exception e) { + throw new RestException(Status.BAD_REQUEST, e, "multipart/form-data cannot be processed"); + + } + } + + protected RestMultipartRequestContext createRequestContext(InputStream entityStream, String contentType) { + return new RestMultipartRequestContext(entityStream, contentType); + } + + /** + * Exposes the REST request to commons fileupload + * + */ + static class RestMultipartRequestContext implements RequestContext { + + protected InputStream inputStream; + protected String contentType; + + public RestMultipartRequestContext(InputStream inputStream, String contentType) { + this.inputStream = inputStream; + this.contentType = contentType; + } + + public String getCharacterEncoding() { + return null; + } + + public String getContentType() { + return contentType; + } + + public int getContentLength() { + return -1; + } + + public InputStream getInputStream() throws IOException { + return inputStream; + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/AuthenticationProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/AuthenticationProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..9a31831dc9acc54183416bea29d00efd4f7804db --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/AuthenticationProvider.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.security.auth; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * A provider to handle the authentication of {@link HttpServletRequest}s. + * May implement a specific authentication scheme. + * + * @author Thorben Lindhauer + */ +public interface AuthenticationProvider { + + /** + * Checks the request for authentication. May not return null, but always an + * {@link AuthenticationResult} that indicates, whether authentication was + * successful, and, if true, always provides the authenticated user. + * + * The result can only be successful if a valid user id was provided in the + * request. It is not required to provide the group or tenant id, as they will + * be resolved via the {@link IdentityService} (e.g. + * {@link ProcessEngineAuthenticationFilter#setAuthenticatedUser}). + * + * @param request + * the request to authenticate + * @param engine + * the process engine the request addresses. May be used to + * authenticate against the engine's identity service. + */ + AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, ProcessEngine engine); + + /** + *

+ * Callback to add an authentication challenge to the response to the client. Called in case of unsuccessful authentication. + *

+ * + *

+ * For example, a Http Basic auth implementation may set the WWW-Authenticate header to Basic realm="engine name". + *

+ * + * @param request the response to augment + * @param engine the process engine the request addressed. May be considered as an authentication realm to create a specific authentication + * challenge + */ + void augmentResponseByAuthenticationChallenge(HttpServletResponse response, ProcessEngine engine); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/AuthenticationResult.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/AuthenticationResult.java new file mode 100644 index 0000000000000000000000000000000000000000..7bb784396e9615afb030861fd31adb631a86746a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/AuthenticationResult.java @@ -0,0 +1,88 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.security.auth; + +import java.util.List; + +import org.camunda.bpm.engine.IdentityService; + +/** + * Serves as DTO to hold the result of an authentication request performed + * through an {@link AuthenticationProvider}. + * + * Note that when implementing a custom {@link AuthenticationProvider}, it is + * not required to set groups or tenants for an AuthenticationResult, as they + * will be resolved later via the {@link IdentityService} (e.g. + * {@link ProcessEngineAuthenticationFilter#setAuthenticatedUser}). + */ +public class AuthenticationResult { + + protected boolean isAuthenticated; + + protected String authenticatedUser; + protected List groups; + protected List tenants; + + public AuthenticationResult(String authenticatedUser, boolean isAuthenticated) { + this.authenticatedUser = authenticatedUser; + this.isAuthenticated = isAuthenticated; + } + + public String getAuthenticatedUser() { + return authenticatedUser; + } + + public void setAuthenticatedUser(String authenticatedUser) { + this.authenticatedUser = authenticatedUser; + } + + public boolean isAuthenticated() { + return isAuthenticated; + } + + public void setAuthenticated(boolean isAuthenticated) { + this.isAuthenticated = isAuthenticated; + } + + public List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } + + public List getTenants() { + return tenants; + } + + public void setTenants(List tenants) { + this.tenants = tenants; + } + + public static AuthenticationResult successful(String userId) { + return new AuthenticationResult(userId, true); + } + + public static AuthenticationResult unsuccessful() { + return new AuthenticationResult(null, false); + } + + public static AuthenticationResult unsuccessful(String userId) { + return new AuthenticationResult(userId, false); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/ProcessEngineAuthenticationFilter.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/ProcessEngineAuthenticationFilter.java new file mode 100644 index 0000000000000000000000000000000000000000..3aab49a1d071acb3715caa975114ed24187490af --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/ProcessEngineAuthenticationFilter.java @@ -0,0 +1,243 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.security.auth; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.rest.dto.ExceptionDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.impl.NamedProcessEngineRestServiceImpl; +import org.camunda.bpm.engine.rest.util.EngineUtil; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + *

+ * Servlet filter to plug in authentication. + *

+ * + *

Valid init-params:

+ * + * + * + * + * + * + * + * + * + * + * + *
ParameterRequiredExpected value
{@value #AUTHENTICATION_PROVIDER_PARAM}yesAn implementation of {@link AuthenticationProvider}
{@value #SERVLET_PATH_PREFIX}noThe expected servlet path. Should only be set, if the underlying JAX-RS application is not deployed as a servlet (e.g. Resteasy allows deployments + * as a servlet filter). Value has to match what would be the {@link HttpServletRequest#getServletPath()} if it was deployed as a servlet.
+ * + * @author Thorben Lindhauer + */ +public class ProcessEngineAuthenticationFilter implements Filter { + + // regexes for urls that may be accessed unauthorized + protected static final Pattern[] WHITE_LISTED_URL_PATTERNS = new Pattern[] { + Pattern.compile("^" + NamedProcessEngineRestServiceImpl.PATH + "/?") + }; + + protected static final Pattern ENGINE_REQUEST_URL_PATTERN = Pattern.compile("^" + NamedProcessEngineRestServiceImpl.PATH + "/(.*?)(/|$)"); + protected static final String DEFAULT_ENGINE_NAME = "default"; + + // init params + public static final String AUTHENTICATION_PROVIDER_PARAM = "authentication-provider"; + public static final String SERVLET_PATH_PREFIX = "rest-url-pattern-prefix"; + + protected AuthenticationProvider authenticationProvider; + protected String servletPathPrefix; + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + String authenticationProviderClassName = filterConfig.getInitParameter(AUTHENTICATION_PROVIDER_PARAM); + + if (authenticationProviderClassName == null) { + throw new ServletException("Cannot instantiate authentication filter: no authentication provider set. init-param " + AUTHENTICATION_PROVIDER_PARAM + " missing"); + } + + try { + Class authenticationProviderClass = Class.forName(authenticationProviderClassName); + authenticationProvider = (AuthenticationProvider) authenticationProviderClass.newInstance(); + } catch (ClassNotFoundException e) { + throw new ServletException("Cannot instantiate authentication filter: authentication provider not found", e); + } catch (InstantiationException e) { + throw new ServletException("Cannot instantiate authentication filter: cannot instantiate authentication provider", e); + } catch (IllegalAccessException e) { + throw new ServletException("Cannot instantiate authentication filter: constructor not accessible", e); + } catch (ClassCastException e) { + throw new ServletException("Cannot instantiate authentication filter: authentication provider does not implement interface " + + AuthenticationProvider.class.getName(), e); + } + + servletPathPrefix = filterConfig.getInitParameter(SERVLET_PATH_PREFIX); + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse resp = (HttpServletResponse) response; + + String servletPath = servletPathPrefix; + if (servletPath == null) { + servletPath = req.getServletPath(); + } + String requestUrl = req.getRequestURI().substring(req.getContextPath().length() + servletPath.length()); + + boolean requiresEngineAuthentication = requiresEngineAuthentication(requestUrl); + + if (!requiresEngineAuthentication) { + chain.doFilter(request, response); + return; + } + + String engineName = extractEngineName(requestUrl); + ProcessEngine engine = getAddressedEngine(engineName); + + if (engine == null) { + resp.setStatus(Status.NOT_FOUND.getStatusCode()); + ExceptionDto exceptionDto = new ExceptionDto(); + exceptionDto.setType(InvalidRequestException.class.getSimpleName()); + exceptionDto.setMessage("Process engine " + engineName + " not available"); + ObjectMapper objectMapper = new ObjectMapper(); + + resp.setContentType(MediaType.APPLICATION_JSON); + objectMapper.writer().writeValue(resp.getWriter(), exceptionDto); + resp.getWriter().flush(); + + return; + } + + AuthenticationResult authenticationResult = authenticationProvider.extractAuthenticatedUser(req, engine); + + if (authenticationResult.isAuthenticated()) { + try { + String authenticatedUser = authenticationResult.getAuthenticatedUser(); + List groups = authenticationResult.getGroups(); + List tenants = authenticationResult.getTenants(); + setAuthenticatedUser(engine, authenticatedUser, groups, tenants); + chain.doFilter(request, response); + } finally { + clearAuthentication(engine); + } + } else { + resp.setStatus(Status.UNAUTHORIZED.getStatusCode()); + authenticationProvider.augmentResponseByAuthenticationChallenge(resp, engine); + } + + } + + @Override + public void destroy() { + + } + + protected void setAuthenticatedUser(ProcessEngine engine, String userId, List groupIds, List tenantIds) { + if (groupIds == null) { + groupIds = getGroupsOfUser(engine, userId); + } + + if (tenantIds == null) { + tenantIds = getTenantsOfUser(engine, userId); + } + + engine.getIdentityService().setAuthentication(userId, groupIds, tenantIds); + } + + protected List getGroupsOfUser(ProcessEngine engine, String userId) { + List groups = engine.getIdentityService().createGroupQuery() + .groupMember(userId) + .list(); + + List groupIds = new ArrayList(); + for (Group group : groups) { + groupIds.add(group.getId()); + } + return groupIds; + } + + protected List getTenantsOfUser(ProcessEngine engine, String userId) { + List tenants = engine.getIdentityService().createTenantQuery() + .userMember(userId) + .includingGroupsOfUser(true) + .list(); + + List tenantIds = new ArrayList(); + for(Tenant tenant : tenants) { + tenantIds.add(tenant.getId()); + } + return tenantIds; + } + + protected void clearAuthentication(ProcessEngine engine) { + engine.getIdentityService().clearAuthentication(); + } + + protected boolean requiresEngineAuthentication(String requestUrl) { + for (Pattern whiteListedUrlPattern : WHITE_LISTED_URL_PATTERNS) { + Matcher matcher = whiteListedUrlPattern.matcher(requestUrl); + if (matcher.matches()) { + return false; + } + } + + return true; + } + + /** + * May not return null + */ + protected String extractEngineName(String requestUrl) { + + Matcher matcher = ENGINE_REQUEST_URL_PATTERN.matcher(requestUrl); + + if (matcher.find()) { + return matcher.group(1); + } else { + // any request that does not match a specific engine and is not an /engine request + // is mapped to the default engine + return DEFAULT_ENGINE_NAME; + } + } + + protected ProcessEngine getAddressedEngine(String engineName) { + return EngineUtil.lookupProcessEngine(engineName); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/impl/ContainerBasedAuthenticationProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/impl/ContainerBasedAuthenticationProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..005fe6f757dbcbe335051e772762df912c056cb4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/impl/ContainerBasedAuthenticationProvider.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.security.auth.impl; + +import java.security.Principal; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.security.auth.AuthenticationProvider; +import org.camunda.bpm.engine.rest.security.auth.AuthenticationResult; + +public class ContainerBasedAuthenticationProvider implements AuthenticationProvider { + + public AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, ProcessEngine engine) { + Principal principal = request.getUserPrincipal(); + + if (principal == null) { + return AuthenticationResult.unsuccessful(); + } + + String name = principal.getName(); + if (name == null || name.isEmpty()) { + return AuthenticationResult.unsuccessful(); + } + + return AuthenticationResult.successful(name); + } + + public void augmentResponseByAuthenticationChallenge(HttpServletResponse response, ProcessEngine engine) { + // noop + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/impl/HttpBasicAuthenticationProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/impl/HttpBasicAuthenticationProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..3eb54be8813bd3820a42e7a309dcd56b83a55203 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/security/auth/impl/HttpBasicAuthenticationProvider.java @@ -0,0 +1,74 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.security.auth.impl; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.rest.security.auth.AuthenticationProvider; +import org.camunda.bpm.engine.rest.security.auth.AuthenticationResult; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.core.HttpHeaders; + +/** + *

+ * Authenticates a request against the provided process engine's identity service by applying http basic authentication. + *

+ * + * @author Thorben Lindhauer + */ +public class HttpBasicAuthenticationProvider implements AuthenticationProvider { + + protected static final String BASIC_AUTH_HEADER_PREFIX = "Basic "; + + @Override + public AuthenticationResult extractAuthenticatedUser(HttpServletRequest request, + ProcessEngine engine) { + String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION); + + if (authorizationHeader != null && authorizationHeader.startsWith(BASIC_AUTH_HEADER_PREFIX)) { + String encodedCredentials = authorizationHeader.substring(BASIC_AUTH_HEADER_PREFIX.length()); + String decodedCredentials = new String(Base64.decodeBase64(encodedCredentials)); + int firstColonIndex = decodedCredentials.indexOf(":"); + + if (firstColonIndex == -1) { + return AuthenticationResult.unsuccessful(); + } else { + String userName = decodedCredentials.substring(0, firstColonIndex); + String password = decodedCredentials.substring(firstColonIndex + 1); + if (isAuthenticated(engine, userName, password)) { + return AuthenticationResult.successful(userName); + } else { + return AuthenticationResult.unsuccessful(userName); + } + } + } else { + return AuthenticationResult.unsuccessful(); + } + } + + protected boolean isAuthenticated(ProcessEngine engine, String userName, String password) { + return engine.getIdentityService().checkPassword(userName, password); + } + + @Override + public void augmentResponseByAuthenticationChallenge( + HttpServletResponse response, ProcessEngine engine) { + response.setHeader(HttpHeaders.WWW_AUTHENTICATE, BASIC_AUTH_HEADER_PREFIX + "realm=\"" + engine.getName() + "\""); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/spi/FetchAndLockHandler.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/spi/FetchAndLockHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..aa6b56af9c4ce5f0582a2b86f98f183412eaebaf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/spi/FetchAndLockHandler.java @@ -0,0 +1,58 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.spi; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto; + +import javax.servlet.ServletContextEvent; +import javax.ws.rs.container.AsyncResponse; + +/** + * SPI supposed to replace the default implementation of the long-polling fetch and lock handler + * + * @author Tassilo Weidner + */ +public interface FetchAndLockHandler { + + /** + * Receives a notification that the engine rest web application initialization has been started + */ + void start(); + + /** + * Receives a notification that the engine rest web application is about to be shut down + */ + void shutdown(); + + /** + * Invoked if a fetch and lock request has been sent by the client + * + * @param dto which is supposed to hold the payload + * @param asyncResponse provides means for asynchronous server side response processing + * @param processEngine provides the process engine context of the respective request + */ + void addPendingRequest(FetchExternalTasksExtendedDto dto, AsyncResponse asyncResponse, ProcessEngine processEngine); + + /** + * Invoked on initialization of the servlet context + * + * @param servletContextEvent provides the servlet context + */ + void contextInitialized(ServletContextEvent servletContextEvent); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/spi/ProcessEngineProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/spi/ProcessEngineProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..75adc55e1a49dc27db68119012183a38cc0c4219 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/spi/ProcessEngineProvider.java @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.spi; + +import org.camunda.bpm.engine.ProcessEngine; + +import java.util.Set; + +/** + * A simple provider SPI used to locate a process engine object. + * + * @author Daniel Meyer + * + */ +public interface ProcessEngineProvider { + + /** + * Provides the default engine. Has to return null if no default engine exists. + */ + ProcessEngine getDefaultProcessEngine(); + + /** + * Provides the engine with the given name. Has to return null if no such engine exists. + */ + ProcessEngine getProcessEngine(String name); + + /** + * Returns the name of all known process engines. Returns an empty set if no engines are accessible. + */ + Set getProcessEngineNames(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/AbstractResourceProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/AbstractResourceProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..8ca3f9337edbff1e13941549a6d9985e2267246c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/AbstractResourceProvider.java @@ -0,0 +1,104 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.impl.VariableResponseProvider; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +/** + * Base class to unify the getResource(boolean deserialized) and + * getResourceBinary() methods for several subclasses. (formerly getVariable() + * and getBinaryVariable()) + * + * @author Ronny Bräunlich + * + */ +public abstract class AbstractResourceProvider, U, DTO> { + + protected String id; + protected ProcessEngine engine; + + public AbstractResourceProvider(String detailId, ProcessEngine engine) { + this.id = detailId; + this.engine = engine; + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + public DTO getResource(@QueryParam(VariableResource.DESERIALIZE_VALUE_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValue) { + U variableInstance = baseQueryForVariable(deserializeObjectValue).singleResult(); + if (variableInstance != null) { + return transformToDto(variableInstance); + } else { + throw new InvalidRequestException(Status.NOT_FOUND, getResourceNameForErrorMessage() + " with Id '" + id + "' does not exist."); + } + } + + + @GET + @Path("/data") + public Response getResourceBinary() { + U queryResult = baseQueryForBinaryVariable().singleResult(); + if (queryResult != null) { + TypedValue variableInstance = transformQueryResultIntoTypedValue(queryResult); + return new VariableResponseProvider().getResponseForTypedVariable(variableInstance, id); + } else { + throw new InvalidRequestException(Status.NOT_FOUND, getResourceNameForErrorMessage() + " with Id '" + id + "' does not exist."); + } + } + + + protected String getId() { + return id; + } + + protected ProcessEngine getEngine() { + return engine; + } + + /** + * Create the query we need for fetching the desired result. Setting + * properties in the query like disableCustomObjectDeserialization() or + * disableBinaryFetching() should be done in this method. + */ + protected abstract Query baseQueryForBinaryVariable(); + + /** + * TODO change comment Create the query we need for fetching the desired + * result. Setting properties in the query like + * disableCustomObjectDeserialization() or disableBinaryFetching() should be + * done in this method. + * + * @param deserializeObjectValue + */ + protected abstract Query baseQueryForVariable(boolean deserializeObjectValue); + + protected abstract TypedValue transformQueryResultIntoTypedValue(U queryResult); + + protected abstract DTO transformToDto(U queryResult); + + protected abstract String getResourceNameForErrorMessage(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/VariableResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/VariableResource.java new file mode 100644 index 0000000000000000000000000000000000000000..39daa3005782b4229bb38d9ff72d5a00e04966f1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/VariableResource.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub; + +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.PatchVariablesDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData; + +public interface VariableResource { + + public final static String DESERIALIZE_VALUE_QUERY_PARAM = "deserializeValue"; + public final static String DESERIALIZE_VALUES_QUERY_PARAM = DESERIALIZE_VALUE_QUERY_PARAM + "s"; + + @GET + @Produces(MediaType.APPLICATION_JSON) + Map getVariables( + @QueryParam(DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeValues); + + @GET + @Path("/{varId}") + @Produces(MediaType.APPLICATION_JSON) + VariableValueDto getVariable( + @PathParam("varId") String variableName, + @QueryParam(DESERIALIZE_VALUE_QUERY_PARAM) @DefaultValue("true") boolean deserializeValue); + + @GET + @Path("/{varId}/data") + public Response getVariableBinary(@PathParam("varId") String variableName); + + @PUT + @Path("/{varId}") + @Consumes(MediaType.APPLICATION_JSON) + void putVariable(@PathParam("varId") String variableName, VariableValueDto variable); + + @POST // using POST since PUT is not as widely supported for file uploads + @Path("/{varId}/data") + @Consumes(MediaType.MULTIPART_FORM_DATA) + void setBinaryVariable(@PathParam("varId") String variableName, MultipartFormData multipartFormData); + + @DELETE + @Path("/{varId}") + void deleteVariable(@PathParam("varId") String variableName); + + @POST + @Consumes(MediaType.APPLICATION_JSON) + void modifyVariables(PatchVariablesDto patch); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/authorization/AuthorizationResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/authorization/AuthorizationResource.java new file mode 100644 index 0000000000000000000000000000000000000000..74f3430c1294940e0dc741d880b2be6e958c89d4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/authorization/AuthorizationResource.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.authorization; + +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationDto; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +/** + * @author Daniel Meyer + * + */ +public interface AuthorizationResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public AuthorizationDto getAuthorization(@Context UriInfo context); + + @DELETE + @Produces(MediaType.APPLICATION_JSON) + public void deleteAuthorization(); + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + public void updateAuthorization(AuthorizationDto Authorization); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/authorization/impl/AuthorizationResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/authorization/impl/AuthorizationResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1fd3163f7dd26b5bbc8fc75ad96ea43706917248 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/authorization/impl/AuthorizationResourceImpl.java @@ -0,0 +1,114 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.authorization.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.rest.AuthorizationRestService; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.impl.AbstractAuthorizedRestResource; +import org.camunda.bpm.engine.rest.sub.authorization.AuthorizationResource; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import java.net.URI; + +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.AUTHORIZATION; + +/** + * + * @author Daniel Meyer + * + */ +public class AuthorizationResourceImpl extends AbstractAuthorizedRestResource implements AuthorizationResource { + + protected final AuthorizationService authorizationService; + protected String relativeRootResourcePath; + + public AuthorizationResourceImpl(String processEngineName, String resourceId, String relativeRootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, AUTHORIZATION, resourceId, objectMapper); + this.relativeRootResourcePath = relativeRootResourcePath; + authorizationService = getProcessEngine().getAuthorizationService(); + } + + public AuthorizationDto getAuthorization(UriInfo context) { + + Authorization dbAuthorization = getDbAuthorization(); + + return AuthorizationDto.fromAuthorization(dbAuthorization, getProcessEngine().getProcessEngineConfiguration()); + + } + + public void deleteAuthorization() { + Authorization dbAuthorization = getDbAuthorization(); + authorizationService.deleteAuthorization(dbAuthorization.getId()); + } + + public void updateAuthorization(AuthorizationDto dto) { + // get db auth + Authorization dbAuthorization = getDbAuthorization(); + // copy values from dto + AuthorizationDto.update(dto, dbAuthorization, getProcessEngine().getProcessEngineConfiguration()); + // save + authorizationService.saveAuthorization(dbAuthorization); + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + + ResourceOptionsDto dto = new ResourceOptionsDto(); + + URI uri = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(AuthorizationRestService.PATH) + .path(resourceId) + .build(); + + dto.addReflexiveLink(uri, HttpMethod.GET, "self"); + + if (isAuthorized(DELETE)) { + dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); + } + if (isAuthorized(UPDATE)) { + dto.addReflexiveLink(uri, HttpMethod.PUT, "update"); + } + + return dto; + } + + // utils ////////////////////////////////////////////////// + + protected Authorization getDbAuthorization() { + Authorization dbAuthorization = authorizationService.createAuthorizationQuery() + .authorizationId(resourceId) + .singleResult(); + + if (dbAuthorization == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Authorization with id " + resourceId + " does not exist."); + + } else { + return dbAuthorization; + + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/batch/BatchResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/batch/BatchResource.java new file mode 100644 index 0000000000000000000000000000000000000000..2f7749462cafd729ee18c91dca6979a57af98004 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/batch/BatchResource.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.batch; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; + +public interface BatchResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + BatchDto getBatch(); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(SuspensionStateDto suspensionState); + + @DELETE + void deleteBatch(@QueryParam("cascade") boolean cascade); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/batch/impl/BatchResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/batch/impl/BatchResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..41de2fdd886a2c7a36a756511701a9ef9e247a89 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/batch/impl/BatchResourceImpl.java @@ -0,0 +1,92 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.batch.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.impl.persistence.entity.SuspensionState; +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.batch.BatchResource; + +public class BatchResourceImpl implements BatchResource { + + protected ProcessEngine processEngine; + protected String batchId; + + public BatchResourceImpl(ProcessEngine processEngine, String batchId) { + this.processEngine = processEngine; + this.batchId = batchId; + } + + public BatchDto getBatch() { + Batch batch = processEngine.getManagementService() + .createBatchQuery() + .batchId(batchId) + .singleResult(); + + if (batch == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Batch with id '" + batchId + "' does not exist"); + } + + return BatchDto.fromBatch(batch); + } + + public void updateSuspensionState(SuspensionStateDto suspensionState) { + if (suspensionState.getSuspended()) { + suspendBatch(); + } + else { + activateBatch(); + } + } + + protected void suspendBatch() { + try { + processEngine.getManagementService().suspendBatchById(batchId); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to suspend batch with id '" + batchId + "'"); + } + } + + protected void activateBatch() { + try { + processEngine.getManagementService().activateBatchById(batchId); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to activate batch with id '" + batchId + "'"); + } + } + + public void deleteBatch(boolean cascade) { + try { + processEngine.getManagementService() + .deleteBatch(batchId, cascade); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to delete batch with id '" + batchId + "'"); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/externaltask/ExternalTaskResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/externaltask/ExternalTaskResource.java new file mode 100644 index 0000000000000000000000000000000000000000..fce7ec21980d111684746ead1508ec4a5ecb680b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/externaltask/ExternalTaskResource.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.externaltask; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.externaltask.CompleteExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExtendLockOnExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskBpmnError; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskFailureDto; +import org.camunda.bpm.engine.rest.dto.externaltask.LockExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.runtime.PriorityDto; +import org.camunda.bpm.engine.rest.dto.runtime.RetriesDto; + +/** + * @author Thorben Lindhauer + * @author Askar Akhmerov + * + */ +public interface ExternalTaskResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + ExternalTaskDto getExternalTask(); + + @GET + @Path("/errorDetails") + @Produces(MediaType.TEXT_PLAIN) + String getErrorDetails(); + + @PUT + @Path("/retries") + @Consumes(MediaType.APPLICATION_JSON) + void setRetries(RetriesDto dto); + + @PUT + @Path("/priority") + @Consumes(MediaType.APPLICATION_JSON) + void setPriority(PriorityDto dto); + + @POST + @Path("/complete") + @Consumes(MediaType.APPLICATION_JSON) + void complete(CompleteExternalTaskDto dto); + + @POST + @Path("/failure") + @Consumes(MediaType.APPLICATION_JSON) + void handleFailure(ExternalTaskFailureDto dto); + + @POST + @Path("/bpmnError") + @Consumes(MediaType.APPLICATION_JSON) + void handleBpmnError(ExternalTaskBpmnError dto); + + @POST + @Path("/lock") + @Consumes(MediaType.APPLICATION_JSON) + void lock(LockExternalTaskDto lockExternalTaskDto); + + @POST + @Path("/extendLock") + @Consumes(MediaType.APPLICATION_JSON) + void extendLock(ExtendLockOnExternalTaskDto extendLockDto); + + @POST + @Path("/unlock") + void unlock(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/externaltask/impl/ExternalTaskResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/externaltask/impl/ExternalTaskResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..633d73f05c5f65f1fc087978236f0bd2869a7b82 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/externaltask/impl/ExternalTaskResourceImpl.java @@ -0,0 +1,198 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.externaltask.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.externaltask.CompleteExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExtendLockOnExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskBpmnError; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskFailureDto; +import org.camunda.bpm.engine.rest.dto.externaltask.LockExternalTaskDto; +import org.camunda.bpm.engine.rest.dto.runtime.PriorityDto; +import org.camunda.bpm.engine.rest.dto.runtime.RetriesDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.externaltask.ExternalTaskResource; +import org.camunda.bpm.engine.variable.VariableMap; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Thorben Lindhauer + * + */ +public class ExternalTaskResourceImpl implements ExternalTaskResource { + + protected ProcessEngine engine; + protected String externalTaskId; + protected ObjectMapper objectMapper; + + public ExternalTaskResourceImpl(ProcessEngine engine, String externalTaskId, ObjectMapper objectMapper) { + this.engine = engine; + this.externalTaskId = externalTaskId; + this.objectMapper = objectMapper; + } + + @Override + public ExternalTaskDto getExternalTask() { + ExternalTask task = engine + .getExternalTaskService() + .createExternalTaskQuery() + .externalTaskId(externalTaskId) + .singleResult(); + + if (task == null) { + throw new RestException(Status.NOT_FOUND, "External task with id " + externalTaskId + " does not exist"); + } + + return ExternalTaskDto.fromExternalTask(task); + } + + @Override + public String getErrorDetails() { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + try { + return externalTaskService.getExternalTaskErrorDetails(externalTaskId); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } + } + + @Override + public void setRetries(RetriesDto dto) { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + Integer retries = dto.getRetries(); + + if (retries == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "The number of retries cannot be null."); + } + + try { + externalTaskService.setRetries(externalTaskId, retries); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } + } + + @Override + public void setPriority(PriorityDto dto) { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + try { + externalTaskService.setPriority(externalTaskId, dto.getPriority()); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } + } + + @Override + public void complete(CompleteExternalTaskDto dto) { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + VariableMap variables = VariableValueDto.toMap(dto.getVariables(), engine, objectMapper); + VariableMap localVariables = VariableValueDto.toMap(dto.getLocalVariables(), engine, objectMapper); + + try { + externalTaskService.complete(externalTaskId, dto.getWorkerId(), variables, localVariables); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, e.getMessage()); + } + + } + + @Override + public void handleFailure(ExternalTaskFailureDto dto) { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + try { + externalTaskService.handleFailure(externalTaskId, + dto.getWorkerId(), + dto.getErrorMessage(), + dto.getErrorDetails(), + dto.getRetries(), + dto.getRetryTimeout(), + VariableValueDto.toMap(dto.getVariables(), engine, objectMapper), + VariableValueDto.toMap(dto.getLocalVariables(), engine, objectMapper)); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + @Override + public void handleBpmnError(ExternalTaskBpmnError dto) { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + try { + externalTaskService.handleBpmnError(externalTaskId, dto.getWorkerId(), dto.getErrorCode(), dto.getErrorMessage(), VariableValueDto.toMap(dto.getVariables(), engine, objectMapper)); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + @Override + public void lock(LockExternalTaskDto lockExternalTaskDto) { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + try { + externalTaskService + .lock(externalTaskId, lockExternalTaskDto.getWorkerId(), lockExternalTaskDto.getLockDuration()); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + @Override + public void extendLock(ExtendLockOnExternalTaskDto extendLockDto) { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + try { + externalTaskService.extendLock(externalTaskId, extendLockDto.getWorkerId(), extendLockDto.getNewDuration()); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + @Override + public void unlock() { + ExternalTaskService externalTaskService = engine.getExternalTaskService(); + + try { + externalTaskService.unlock(externalTaskId); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, "External task with id " + externalTaskId + " does not exist"); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricActivityInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricActivityInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..6a33a290412a825a3238724c551b544b03b2ec0c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricActivityInstanceResource.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityInstanceDto; + +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +public interface HistoricActivityInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricActivityInstanceDto getHistoricActivityInstance(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricBatchResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricBatchResource.java new file mode 100644 index 0000000000000000000000000000000000000000..06e7ba27bf3fb6b1451fa986ec81e800c1444299 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricBatchResource.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchDto; + +public interface HistoricBatchResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricBatchDto getHistoricBatch(); + + @DELETE + void deleteHistoricBatch(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricCaseActivityInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricCaseActivityInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..ae2396d2037184c3fff847eee8007213cadfe418 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricCaseActivityInstanceResource.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseActivityInstanceDto; + +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +public interface HistoricCaseActivityInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricCaseActivityInstanceDto getHistoricCaseActivityInstance(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricCaseInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricCaseInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..a4e811cc148992f76b30062a58a7d0cc705f49ac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricCaseInstanceResource.java @@ -0,0 +1,31 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseInstanceDto; + +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +public interface HistoricCaseInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricCaseInstanceDto getHistoricCaseInstance(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricDecisionInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricDecisionInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..4f0f33bbadf1fac8d1ac808740e320145d3f350e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricDecisionInstanceResource.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceDto; + +public interface HistoricDecisionInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricDecisionInstanceDto getHistoricDecisionInstance(@QueryParam("includeInputs") Boolean includeInputs, + @QueryParam("includeOutputs") Boolean includeOutputs, + @QueryParam("disableBinaryFetching") Boolean disableBinaryFetching, + @QueryParam("disableCustomObjectDeserialization") Boolean disableCustomObjectDeserialization); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricDetailResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricDetailResource.java new file mode 100644 index 0000000000000000000000000000000000000000..842f754ed4d19406b77b7632dc03781b695ca160 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricDetailResource.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.history.HistoricDetailDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +/** + * + * @author Daniel Meyer + * @author Ronny Bräunlich + */ +public interface HistoricDetailResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public HistoricDetailDto getResource( + @QueryParam(VariableResource.DESERIALIZE_VALUE_QUERY_PARAM) @DefaultValue("true") boolean deserializeValue); + + + @GET + @Path("/data") + public Response getResourceBinary(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricExternalTaskLogResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricExternalTaskLogResource.java new file mode 100644 index 0000000000000000000000000000000000000000..adadefa870eb5d8c165e473b30f51eaa2f1530dd --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricExternalTaskLogResource.java @@ -0,0 +1,39 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import org.camunda.bpm.engine.rest.dto.history.HistoricExternalTaskLogDto; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +/** + * @since 7.7 + */ +public interface HistoricExternalTaskLogResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricExternalTaskLogDto getHistoricExternalTaskLog(); + + @GET + @Path("/error-details") + @Produces(MediaType.TEXT_PLAIN) + String getErrorDetails(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricJobLogResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricJobLogResource.java new file mode 100644 index 0000000000000000000000000000000000000000..0925ae925aba3c1c70a2785a3f43c24e9e4c9183 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricJobLogResource.java @@ -0,0 +1,43 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.history.HistoricJobLogDto; + +/** + * @author Roman Smirnov + * + * @since 7.3 + * + */ +public interface HistoricJobLogResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricJobLogDto getHistoricJobLog(); + + @GET + @Path("/stacktrace") + @Produces(MediaType.TEXT_PLAIN) + String getStacktrace(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricProcessInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricProcessInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..72f75f8e4c62bb32dbe4b10ae1d6c4873f5c5909 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricProcessInstanceResource.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto; + +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +public interface HistoricProcessInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + HistoricProcessInstanceDto getHistoricProcessInstance(); + + @DELETE + void deleteHistoricProcessInstance(@QueryParam("failIfNotExists") @DefaultValue("true") Boolean failIfNotExists); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricVariableInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricVariableInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..244d97496c95a116917064923045ad3a01450082 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/HistoricVariableInstanceResource.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history; + +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.history.HistoricVariableInstanceDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +/** + * + * @author Daniel Meyer + * @author Ronny Bräunlich + */ +public interface HistoricVariableInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public HistoricVariableInstanceDto getResource( + @QueryParam(VariableResource.DESERIALIZE_VALUE_QUERY_PARAM) @DefaultValue("true") boolean deserializeValue); + + + @GET + @Path("/data") + public Response getResourceBinary(); + + @DELETE + public Response deleteVariableInstance(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricActivityInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricActivityInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1383dd5fb867805294a9063190b0f9535b2c1da8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricActivityInstanceResourceImpl.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.rest.dto.history.HistoricActivityInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricActivityInstanceResource; + +import javax.ws.rs.core.Response.Status; + +public class HistoricActivityInstanceResourceImpl implements HistoricActivityInstanceResource { + + private ProcessEngine engine; + private String activityInstanceId; + + public HistoricActivityInstanceResourceImpl(ProcessEngine engine, String activityInstanceId) { + this.engine = engine; + this.activityInstanceId = activityInstanceId; + } + + public HistoricActivityInstanceDto getHistoricActivityInstance() { + HistoryService historyService = engine.getHistoryService(); + HistoricActivityInstance instance = historyService.createHistoricActivityInstanceQuery() + .activityInstanceId(activityInstanceId).singleResult(); + + if (instance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic activity instance with id '" + activityInstanceId + "' does not exist"); + } + + final HistoricActivityInstanceDto historicActivityInstanceDto = new HistoricActivityInstanceDto(); + HistoricActivityInstanceDto.fromHistoricActivityInstance(historicActivityInstanceDto, instance); + return historicActivityInstanceDto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricBatchResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricBatchResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..259d3b6352b1a23afd0ffc39069df0ecad8127b4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricBatchResourceImpl.java @@ -0,0 +1,61 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.batch.history.HistoricBatch; +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricBatchResource; + +public class HistoricBatchResourceImpl implements HistoricBatchResource { + + protected ProcessEngine processEngine; + protected String batchId; + + public HistoricBatchResourceImpl(ProcessEngine processEngine, String batchId) { + this.processEngine = processEngine; + this.batchId = batchId; + } + + public HistoricBatchDto getHistoricBatch() { + HistoricBatch batch = processEngine.getHistoryService() + .createHistoricBatchQuery() + .batchId(batchId) + .singleResult(); + + if (batch == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic batch with id '" + batchId + "' does not exist"); + } + + return HistoricBatchDto.fromBatch(batch); + } + + public void deleteHistoricBatch() { + try { + processEngine.getHistoryService() + .deleteHistoricBatch(batchId); + } + catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to delete historic batch with id '" + batchId + "'"); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricCaseActivityInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricCaseActivityInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..094a2674833ac7db41d97bfbfe1360b668d99c14 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricCaseActivityInstanceResourceImpl.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstance; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseActivityInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricCaseActivityInstanceResource; + +import javax.ws.rs.core.Response.Status; + +public class HistoricCaseActivityInstanceResourceImpl implements HistoricCaseActivityInstanceResource { + + private ProcessEngine engine; + private String caseActivityInstanceId; + + public HistoricCaseActivityInstanceResourceImpl(ProcessEngine engine, String caseActivityInstanceId) { + this.engine = engine; + this.caseActivityInstanceId = caseActivityInstanceId; + } + + public HistoricCaseActivityInstanceDto getHistoricCaseActivityInstance() { + HistoryService historyService = engine.getHistoryService(); + HistoricCaseActivityInstance instance = historyService.createHistoricCaseActivityInstanceQuery() + .caseActivityInstanceId(caseActivityInstanceId).singleResult(); + + if (instance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic case activity instance with id '" + caseActivityInstanceId + "' does not exist"); + } + + return HistoricCaseActivityInstanceDto.fromHistoricCaseActivityInstance(instance); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricCaseInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricCaseInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..28aa8e1a802457f6821c80000595226c5343ba02 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricCaseInstanceResourceImpl.java @@ -0,0 +1,49 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricCaseInstance; +import org.camunda.bpm.engine.rest.dto.history.HistoricCaseInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricCaseInstanceResource; + +import javax.ws.rs.core.Response.Status; + +public class HistoricCaseInstanceResourceImpl implements HistoricCaseInstanceResource { + + private ProcessEngine engine; + private String caseInstanceId; + + public HistoricCaseInstanceResourceImpl(ProcessEngine engine, String caseInstanceId) { + this.engine = engine; + this.caseInstanceId = caseInstanceId; + } + + public HistoricCaseInstanceDto getHistoricCaseInstance() { + HistoryService historyService = engine.getHistoryService(); + HistoricCaseInstance instance = historyService.createHistoricCaseInstanceQuery().caseInstanceId(caseInstanceId).singleResult(); + + if (instance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic case instance with id '" + caseInstanceId + "' does not exist"); + } + + return HistoricCaseInstanceDto.fromHistoricCaseInstance(instance); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricDecisionInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricDecisionInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..cdd6ac45006c5d48fef302f3a26673c2d8d09d5e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricDecisionInstanceResourceImpl.java @@ -0,0 +1,64 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceQuery; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricDecisionInstanceResource; + +public class HistoricDecisionInstanceResourceImpl implements HistoricDecisionInstanceResource { + + private ProcessEngine engine; + private String decisionInstanceId; + + public HistoricDecisionInstanceResourceImpl(ProcessEngine engine, String decisionInstanceId) { + this.engine = engine; + this.decisionInstanceId = decisionInstanceId; + } + + public HistoricDecisionInstanceDto getHistoricDecisionInstance(Boolean includeInputs, Boolean includeOutputs, Boolean disableBinaryFetching, Boolean disableCustomObjectDeserialization) { + HistoryService historyService = engine.getHistoryService(); + + HistoricDecisionInstanceQuery query = historyService.createHistoricDecisionInstanceQuery().decisionInstanceId(decisionInstanceId); + if (includeInputs != null && includeInputs) { + query.includeInputs(); + } + if (includeOutputs != null && includeOutputs) { + query.includeOutputs(); + } + if (disableBinaryFetching != null && disableBinaryFetching) { + query.disableBinaryFetching(); + } + if (disableCustomObjectDeserialization != null && disableCustomObjectDeserialization) { + query.disableCustomObjectDeserialization(); + } + + HistoricDecisionInstance instance = query.singleResult(); + + if (instance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic decision instance with id '" + decisionInstanceId + "' does not exist"); + } + + return HistoricDecisionInstanceDto.fromHistoricDecisionInstance(instance); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricDetailResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricDetailResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..91bb8d60905d2ad848acdc6d81d9795e96ed363b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricDetailResourceImpl.java @@ -0,0 +1,82 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.history.HistoricDetail; +import org.camunda.bpm.engine.history.HistoricDetailQuery; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.dto.history.HistoricDetailDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.AbstractResourceProvider; +import org.camunda.bpm.engine.rest.sub.history.HistoricDetailResource; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Daniel Meyer + * @author Ronny Bräunlich + * + */ +public class HistoricDetailResourceImpl extends AbstractResourceProvider implements + HistoricDetailResource { + + public HistoricDetailResourceImpl(String detailId, ProcessEngine engine) { + super(detailId, engine); + } + + protected HistoricDetailQuery baseQuery() { + return engine.getHistoryService().createHistoricDetailQuery().detailId(getId()); + } + + @Override + protected Query baseQueryForBinaryVariable() { + return baseQuery().disableCustomObjectDeserialization(); + } + + @Override + protected Query baseQueryForVariable(boolean deserializeObjectValue) { + HistoricDetailQuery query = baseQuery().disableBinaryFetching(); + + if (!deserializeObjectValue) { + query.disableCustomObjectDeserialization(); + } + return query; + } + + @Override + protected TypedValue transformQueryResultIntoTypedValue(HistoricDetail queryResult) { + if (!(queryResult instanceof HistoricVariableUpdate)) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Historic detail with Id '" + getId() + "' is not a variable update."); + } + HistoricVariableUpdate update = (HistoricVariableUpdate) queryResult; + return update.getTypedValue(); + } + + @Override + protected HistoricDetailDto transformToDto(HistoricDetail queryResult) { + return HistoricDetailDto.fromHistoricDetail(queryResult); + } + + @Override + protected String getResourceNameForErrorMessage() { + return "Historic detail"; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricExternalTaskLogResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricExternalTaskLogResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..3a3e2c1274e6bf0a459e4426cc8b2223917918ce --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricExternalTaskLogResourceImpl.java @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.history.HistoricExternalTaskLog; +import org.camunda.bpm.engine.rest.dto.history.HistoricExternalTaskLogDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricExternalTaskLogResource; + +import javax.ws.rs.core.Response.Status; + +public class HistoricExternalTaskLogResourceImpl implements HistoricExternalTaskLogResource { + + protected String id; + protected ProcessEngine engine; + + public HistoricExternalTaskLogResourceImpl(String id, ProcessEngine engine) { + this.id = id; + this.engine = engine; + } + + @Override + public HistoricExternalTaskLogDto getHistoricExternalTaskLog() { + HistoryService historyService = engine.getHistoryService(); + HistoricExternalTaskLog historicExternalTaskLog = historyService + .createHistoricExternalTaskLogQuery() + .logId(id) + .singleResult(); + + if (historicExternalTaskLog == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic external task log with id " + id + " does not exist"); + } + + return HistoricExternalTaskLogDto.fromHistoricExternalTaskLog(historicExternalTaskLog); + } + + @Override + public String getErrorDetails() { + try { + HistoryService historyService = engine.getHistoryService(); + return historyService.getHistoricExternalTaskLogErrorDetails(id); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricJobLogResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricJobLogResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1e614f5726ea37b11c064dd02df540a48e995154 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricJobLogResourceImpl.java @@ -0,0 +1,70 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.history.HistoricJobLog; +import org.camunda.bpm.engine.rest.dto.history.HistoricJobLogDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricJobLogResource; + +/** + * @author Roman Smirnov + * + */ +public class HistoricJobLogResourceImpl implements HistoricJobLogResource { + + protected String id; + protected ProcessEngine engine; + + public HistoricJobLogResourceImpl(String id, ProcessEngine engine) { + this.id = id; + this.engine = engine; + } + + public HistoricJobLogDto getHistoricJobLog() { + HistoryService historyService = engine.getHistoryService(); + HistoricJobLog historicJobLog = historyService + .createHistoricJobLogQuery() + .logId(id) + .singleResult(); + + if (historicJobLog == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic job log with id " + id + " does not exist"); + } + + return HistoricJobLogDto.fromHistoricJobLog(historicJobLog); + } + + public String getStacktrace() { + try { + HistoryService historyService = engine.getHistoryService(); + String stacktrace = historyService.getHistoricJobLogExceptionStacktrace(id); + return stacktrace; + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricProcessInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricProcessInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..803c9af5a0493f173ff2167216d33e9d75766db3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricProcessInstanceResourceImpl.java @@ -0,0 +1,68 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.history.HistoricProcessInstanceResource; + +public class HistoricProcessInstanceResourceImpl implements HistoricProcessInstanceResource { + + private ProcessEngine engine; + private String processInstanceId; + + public HistoricProcessInstanceResourceImpl(ProcessEngine engine, String processInstanceId) { + this.engine = engine; + this.processInstanceId = processInstanceId; + } + + @Override + public HistoricProcessInstanceDto getHistoricProcessInstance() { + HistoryService historyService = engine.getHistoryService(); + HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult(); + + if (instance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Historic process instance with id " + processInstanceId + " does not exist"); + } + + return HistoricProcessInstanceDto.fromHistoricProcessInstance(instance); + } + + @Override + public void deleteHistoricProcessInstance(Boolean failIfNotExists) { + HistoryService historyService = engine.getHistoryService(); + try { + if(failIfNotExists == null || failIfNotExists) { + historyService.deleteHistoricProcessInstance(processInstanceId); + }else { + historyService.deleteHistoricProcessInstanceIfExists(processInstanceId); + } + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, "Historic process instance with id " + processInstanceId + " does not exist"); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricVariableInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricVariableInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1568d58962e7c557227dcbd8436f70174bb11dd8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/history/impl/HistoricVariableInstanceResourceImpl.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.history.impl; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.dto.history.HistoricVariableInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.AbstractResourceProvider; +import org.camunda.bpm.engine.rest.sub.history.HistoricVariableInstanceResource; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Daniel Meyer + * @author Ronny Bräunlich + * + */ +public class HistoricVariableInstanceResourceImpl extends + AbstractResourceProvider implements HistoricVariableInstanceResource { + + public HistoricVariableInstanceResourceImpl(String variableId, ProcessEngine engine) { + super(variableId, engine); + } + + protected HistoricVariableInstanceQuery baseQuery() { + return getEngine().getHistoryService().createHistoricVariableInstanceQuery().variableId(getId()); + } + + @Override + protected Query baseQueryForBinaryVariable() { + return baseQuery().disableCustomObjectDeserialization(); + } + + @Override + protected Query baseQueryForVariable(boolean deserializeObjectValue) { + HistoricVariableInstanceQuery query = baseQuery().disableBinaryFetching(); + + if (!deserializeObjectValue) { + query.disableCustomObjectDeserialization(); + } + return query; + } + + @Override + protected TypedValue transformQueryResultIntoTypedValue(HistoricVariableInstance queryResult) { + return queryResult.getTypedValue(); + } + + @Override + protected HistoricVariableInstanceDto transformToDto(HistoricVariableInstance queryResult) { + return HistoricVariableInstanceDto.fromHistoricVariableInstance(queryResult); + } + + @Override + protected String getResourceNameForErrorMessage() { + return "Historic variable instance"; + } + + @Override + public Response deleteVariableInstance() { + try { + getEngine().getHistoryService().deleteHistoricVariableInstance(id); + } catch (NotFoundException nfe) { // rewrite status code from bad request (400) to not found (404) + throw new InvalidRequestException(Status.NOT_FOUND, nfe, nfe.getMessage()); + } + // return no content (204) since resource is deleted + return Response.noContent().build(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/GroupMembersResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/GroupMembersResource.java new file mode 100644 index 0000000000000000000000000000000000000000..61c601e634c8f18c21ffc8b8e032fea1ca02befb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/GroupMembersResource.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity; + +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + + +/** + * @author Daniel Meyer + * + */ +public interface GroupMembersResource { + + public static final String PATH = "/members"; + + @PUT + @Path("/{userId}") + public void createGroupMember(@PathParam("userId") String userId); + + @DELETE + @Path("/{userId}") + public void deleteGroupMember(@PathParam("userId") String userId); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/GroupResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/GroupResource.java new file mode 100644 index 0000000000000000000000000000000000000000..fa11d8011c16a24a992f3edcc209b66841174720 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/GroupResource.java @@ -0,0 +1,52 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity; + +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.GroupDto; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +/** + * @author Daniel Meyer + * + */ +public interface GroupResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public GroupDto getGroup(@Context UriInfo context); + + @DELETE + @Produces(MediaType.APPLICATION_JSON) + public void deleteGroup(); + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + public void updateGroup(GroupDto Group); + + @Path(GroupMembersResource.PATH) + GroupMembersResource getGroupMembersResource(); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantGroupMembersResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantGroupMembersResource.java new file mode 100644 index 0000000000000000000000000000000000000000..3f77db683856d9ea8525f529bed7566708173324 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantGroupMembersResource.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity; + +import javax.ws.rs.DELETE; +import javax.ws.rs.OPTIONS; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; + +public interface TenantGroupMembersResource { + + public static final String PATH = "/group-members"; + + @PUT + @Path("/{groupId}") + public void createMembership(@PathParam("groupId") String groupId); + + @DELETE + @Path("/{groupId}") + public void deleteMembership(@PathParam("groupId") String groupId); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantResource.java new file mode 100644 index 0000000000000000000000000000000000000000..4e2431f6c0dff894ac9405cab5cdd8b3fb84fcd2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantResource.java @@ -0,0 +1,57 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.OPTIONS; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.TenantDto; + +public interface TenantResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public TenantDto getTenant(@Context UriInfo context); + + @DELETE + @Produces(MediaType.APPLICATION_JSON) + public void deleteTenant(); + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + public void updateTenant(TenantDto tenant); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + + @Path(TenantUserMembersResource.PATH) + TenantUserMembersResource getTenantUserMembersResource(); + + @Path(TenantGroupMembersResource.PATH) + TenantGroupMembersResource getTenantGroupMembersResource(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantUserMembersResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantUserMembersResource.java new file mode 100644 index 0000000000000000000000000000000000000000..8931c4071889c0e2c5088891b43c49f3b6988ca2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/TenantUserMembersResource.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity; + +import javax.ws.rs.DELETE; +import javax.ws.rs.OPTIONS; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; + +public interface TenantUserMembersResource { + + public static final String PATH = "/user-members"; + + @PUT + @Path("/{userId}") + public void createMembership(@PathParam("userId") String userId); + + @DELETE + @Path("/{userId}") + public void deleteMembership(@PathParam("userId") String userId); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/UserResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/UserResource.java new file mode 100644 index 0000000000000000000000000000000000000000..22af9c549c5ea849512628b1256f420bddffa3a7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/UserResource.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity; + +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.UserCredentialsDto; +import org.camunda.bpm.engine.rest.dto.identity.UserProfileDto; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +/** + * @author Daniel Meyer + * + */ +public interface UserResource { + + @DELETE + @Produces(MediaType.APPLICATION_JSON) + public void deleteUser(); + + @POST + @Path("/unlock") + public void unlockUser(); + + // profile /////////////////// + + @GET + @Path("/profile") + @Produces(MediaType.APPLICATION_JSON) + public UserProfileDto getUserProfile(@Context UriInfo context); + + @PUT + @Path("/profile") + @Consumes(MediaType.APPLICATION_JSON) + public void updateProfile(UserProfileDto profile); + + // credentials ////////////// + + @PUT + @Path("/credentials") + @Consumes(MediaType.APPLICATION_JSON) + public void updateCredentials(UserCredentialsDto account); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/AbstractIdentityResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/AbstractIdentityResource.java new file mode 100644 index 0000000000000000000000000000000000000000..f13cefacf47e5c92f2e17f5268a28ad3e7c46156 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/AbstractIdentityResource.java @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.impl.AbstractAuthorizedRestResource; + +import javax.ws.rs.core.Response.Status; + +/** + * @author Daniel Meyer + * + */ +public abstract class AbstractIdentityResource extends AbstractAuthorizedRestResource { + + protected final IdentityService identityService; + + public AbstractIdentityResource(String processEngineName, Resource resource, String resourceId, ObjectMapper objectMapper) { + super(processEngineName, resource, resourceId, objectMapper); + this.identityService = getProcessEngine().getIdentityService(); + } + + protected void ensureNotReadOnly() { + if(identityService.isReadOnly()) { + throw new InvalidRequestException(Status.FORBIDDEN, "Identity service implementation is read-only."); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/GroupMembersResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/GroupMembersResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..8ca1c4f59fb045d6aea304ba71ff94cd74f3026a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/GroupMembersResourceImpl.java @@ -0,0 +1,80 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.authorization.Resources; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.sub.identity.GroupMembersResource; +import org.camunda.bpm.engine.rest.util.PathUtil; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.UriInfo; +import java.net.URI; + +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; + +/** + * @author Daniel Meyer + * + */ +public class GroupMembersResourceImpl extends AbstractIdentityResource implements GroupMembersResource { + + public GroupMembersResourceImpl(String processEngineName, String resourceId, String rootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, Resources.GROUP_MEMBERSHIP, resourceId, objectMapper); + this.relativeRootResourcePath = rootResourcePath; + } + + public void createGroupMember(String userId) { + ensureNotReadOnly(); + + userId = PathUtil.decodePathParam(userId); + identityService.createMembership(userId, resourceId); + } + + public void deleteGroupMember(String userId) { + ensureNotReadOnly(); + + userId = PathUtil.decodePathParam(userId); + identityService.deleteMembership(userId, resourceId); + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + + ResourceOptionsDto dto = new ResourceOptionsDto(); + + URI uri = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(GroupRestService.PATH) + .path(resourceId) + .path(PATH) + .build(); + + if (!identityService.isReadOnly() && isAuthorized(DELETE)) { + dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); + } + if (!identityService.isReadOnly() && isAuthorized(CREATE)) { + dto.addReflexiveLink(uri, HttpMethod.PUT, "create"); + } + + return dto; + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/GroupResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/GroupResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..88dbddabddb42790f40951fb39fd21760ea0bf38 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/GroupResourceImpl.java @@ -0,0 +1,120 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.rest.GroupRestService; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.GroupDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.identity.GroupMembersResource; +import org.camunda.bpm.engine.rest.sub.identity.GroupResource; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import java.net.URI; + +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.GROUP; + +/** + * @author Daniel Meyer + * + */ +public class GroupResourceImpl extends AbstractIdentityResource implements GroupResource { + + private String rootResourcePath; + + public GroupResourceImpl(String processEngineName, String groupId, String rootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, GROUP, groupId, objectMapper); + this.rootResourcePath = rootResourcePath; + } + + public GroupDto getGroup(UriInfo context) { + + Group dbGroup = findGroupObject(); + if(dbGroup == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Group with id " + resourceId + " does not exist"); + } + + GroupDto group = GroupDto.fromGroup(dbGroup); + + return group; + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + + ResourceOptionsDto dto = new ResourceOptionsDto(); + + // add links if operations are authorized + URI uri = context.getBaseUriBuilder() + .path(rootResourcePath) + .path(GroupRestService.PATH) + .path(resourceId) + .build(); + + dto.addReflexiveLink(uri, HttpMethod.GET, "self"); + if(!identityService.isReadOnly() && isAuthorized(DELETE)) { + dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); + } + if(!identityService.isReadOnly() && isAuthorized(UPDATE)) { + dto.addReflexiveLink(uri, HttpMethod.PUT, "update"); + } + + return dto; + } + + + public void updateGroup(GroupDto group) { + ensureNotReadOnly(); + + Group dbGroup = findGroupObject(); + if(dbGroup == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Group with id " + resourceId + " does not exist"); + } + + group.update(dbGroup); + + identityService.saveGroup(dbGroup); + } + + + public void deleteGroup() { + ensureNotReadOnly(); + identityService.deleteGroup(resourceId); + } + + public GroupMembersResource getGroupMembersResource() { + return new GroupMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper()); + } + + protected Group findGroupObject() { + try { + return identityService.createGroupQuery() + .groupId(resourceId) + .singleResult(); + } catch(ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Exception while performing group query: "+e.getMessage()); + } + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantGroupMembersResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantGroupMembersResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..8aef1757e667ae9b1ca278b3b8a2e0fd22e8a729 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantGroupMembersResourceImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity.impl; + +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; + +import java.net.URI; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.authorization.Resources; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.sub.identity.TenantGroupMembersResource; +import org.camunda.bpm.engine.rest.util.PathUtil; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TenantGroupMembersResourceImpl extends AbstractIdentityResource implements TenantGroupMembersResource { + + public TenantGroupMembersResourceImpl(String processEngineName, String resourceId, String rootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, Resources.TENANT_MEMBERSHIP, resourceId, objectMapper); + this.relativeRootResourcePath = rootResourcePath; + } + + public void createMembership(String groupId) { + ensureNotReadOnly(); + + groupId = PathUtil.decodePathParam(groupId); + identityService.createTenantGroupMembership(resourceId, groupId); + } + + public void deleteMembership(String groupId) { + ensureNotReadOnly(); + + groupId = PathUtil.decodePathParam(groupId); + identityService.deleteTenantGroupMembership(resourceId, groupId); + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + ResourceOptionsDto dto = new ResourceOptionsDto(); + + URI uri = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(TenantRestService.PATH) + .path(resourceId) + .path(TenantGroupMembersResource.PATH) + .build(); + + if (!identityService.isReadOnly() && isAuthorized(DELETE)) { + dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); + } + if (!identityService.isReadOnly() && isAuthorized(CREATE)) { + dto.addReflexiveLink(uri, HttpMethod.PUT, "create"); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..72e0c6f8880b559ea1ffac5de0dd5aec3e551807 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantResourceImpl.java @@ -0,0 +1,121 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity.impl; + +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.TENANT; + +import java.net.URI; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.TenantDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.identity.TenantGroupMembersResource; +import org.camunda.bpm.engine.rest.sub.identity.TenantResource; +import org.camunda.bpm.engine.rest.sub.identity.TenantUserMembersResource; + +import com.fasterxml.jackson.databind.ObjectMapper;; + +public class TenantResourceImpl extends AbstractIdentityResource implements TenantResource { + + private String rootResourcePath; + + public TenantResourceImpl(String processEngineName, String tenantId, String rootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, TENANT, tenantId, objectMapper); + this.rootResourcePath = rootResourcePath; + } + + public TenantDto getTenant(UriInfo context) { + + Tenant tenant = findTenantObject(); + if(tenant == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Tenant with id " + resourceId + " does not exist"); + } + + TenantDto dto = TenantDto.fromTenant(tenant); + return dto; + } + + public void updateTenant(TenantDto tenantDto) { + ensureNotReadOnly(); + + Tenant tenant = findTenantObject(); + if(tenant == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Tenant with id " + resourceId + " does not exist"); + } + + tenantDto.update(tenant); + + identityService.saveTenant(tenant); + } + + public void deleteTenant() { + ensureNotReadOnly(); + + identityService.deleteTenant(resourceId); + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + ResourceOptionsDto dto = new ResourceOptionsDto(); + + // add links if operations are authorized + URI uri = context.getBaseUriBuilder() + .path(rootResourcePath) + .path(TenantRestService.PATH) + .path(resourceId) + .build(); + + dto.addReflexiveLink(uri, HttpMethod.GET, "self"); + + if(!identityService.isReadOnly() && isAuthorized(DELETE)) { + dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); + } + if(!identityService.isReadOnly() && isAuthorized(UPDATE)) { + dto.addReflexiveLink(uri, HttpMethod.PUT, "update"); + } + return dto; + } + + public TenantUserMembersResource getTenantUserMembersResource() { + return new TenantUserMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper()); + } + + public TenantGroupMembersResource getTenantGroupMembersResource() { + return new TenantGroupMembersResourceImpl(getProcessEngine().getName(), resourceId, rootResourcePath, getObjectMapper()); + } + + protected Tenant findTenantObject() { + try { + return identityService.createTenantQuery() + .tenantId(resourceId) + .singleResult(); + + } catch(ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, + "Exception while performing tenant query: " + e.getMessage()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantUserMembersResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantUserMembersResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..771521a5b6109e082d60c2d010bd707c75d51218 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/TenantUserMembersResourceImpl.java @@ -0,0 +1,76 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity.impl; + +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; + +import java.net.URI; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.authorization.Resources; +import org.camunda.bpm.engine.rest.TenantRestService; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.sub.identity.TenantUserMembersResource; +import org.camunda.bpm.engine.rest.util.PathUtil; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TenantUserMembersResourceImpl extends AbstractIdentityResource implements TenantUserMembersResource { + + public TenantUserMembersResourceImpl(String processEngineName, String resourceId, String rootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, Resources.TENANT_MEMBERSHIP, resourceId, objectMapper); + this.relativeRootResourcePath = rootResourcePath; + } + + public void createMembership(String userId) { + ensureNotReadOnly(); + + userId = PathUtil.decodePathParam(userId); + identityService.createTenantUserMembership(resourceId, userId); + } + + public void deleteMembership(String userId) { + ensureNotReadOnly(); + + userId = PathUtil.decodePathParam(userId); + identityService.deleteTenantUserMembership(resourceId, userId); + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + ResourceOptionsDto dto = new ResourceOptionsDto(); + + URI uri = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(TenantRestService.PATH) + .path(resourceId) + .path(TenantUserMembersResource.PATH) + .build(); + + if (!identityService.isReadOnly() && isAuthorized(DELETE)) { + dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); + } + if (!identityService.isReadOnly() && isAuthorized(CREATE)) { + dto.addReflexiveLink(uri, HttpMethod.PUT, "create"); + } + + return dto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/UserResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/UserResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a206418cf2fd8f5382fd08a9fc16d99dc418f653 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/identity/impl/UserResourceImpl.java @@ -0,0 +1,141 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.identity.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.UserRestService; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.identity.UserCredentialsDto; +import org.camunda.bpm.engine.rest.dto.identity.UserProfileDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.identity.UserResource; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import java.net.URI; + +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.USER; + +/** + * @author Daniel Meyer + * + */ +public class UserResourceImpl extends AbstractIdentityResource implements UserResource { + + protected String rootResourcePath; + + public UserResourceImpl(String processEngineName, String userId, String rootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, USER, userId, objectMapper); + this.rootResourcePath = rootResourcePath; + } + + public UserProfileDto getUserProfile(UriInfo context) { + + User dbUser = findUserObject(); + if(dbUser == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "User with id " + resourceId + " does not exist"); + } + + UserProfileDto user = UserProfileDto.fromUser(dbUser); + + return user; + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + ResourceOptionsDto dto = new ResourceOptionsDto(); + + // add links if operations are authorized + UriBuilder baseUriBuilder = context.getBaseUriBuilder() + .path(rootResourcePath) + .path(UserRestService.PATH) + .path(resourceId); + URI baseUri = baseUriBuilder.build(); + URI profileUri = baseUriBuilder.path("/profile").build(); + + dto.addReflexiveLink(profileUri, HttpMethod.GET, "self"); + + if(!identityService.isReadOnly() && isAuthorized(DELETE)) { + dto.addReflexiveLink(baseUri, HttpMethod.DELETE, "delete"); + } + if(!identityService.isReadOnly() && isAuthorized(UPDATE)) { + dto.addReflexiveLink(profileUri, HttpMethod.PUT, "update"); + } + + return dto; + } + + public void deleteUser() { + ensureNotReadOnly(); + identityService.deleteUser(resourceId); + } + + public void unlockUser() { + ensureNotReadOnly(); + identityService.unlockUser(resourceId); + } + + public void updateCredentials(UserCredentialsDto account) { + ensureNotReadOnly(); + + Authentication currentAuthentication = identityService.getCurrentAuthentication(); + if(currentAuthentication != null && currentAuthentication.getUserId() != null) { + if(!identityService.checkPassword(currentAuthentication.getUserId(), account.getAuthenticatedUserPassword())) { + throw new InvalidRequestException(Status.BAD_REQUEST, "The given authenticated user password is not valid."); + } + } + + User dbUser = findUserObject(); + if(dbUser == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "User with id " + resourceId + " does not exist"); + } + + dbUser.setPassword(account.getPassword()); + + identityService.saveUser(dbUser); + } + + public void updateProfile(UserProfileDto profile) { + ensureNotReadOnly(); + + User dbUser = findUserObject(); + if(dbUser == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "User with id " + resourceId + " does not exist"); + } + + profile.update(dbUser); + + identityService.saveUser(dbUser); + } + + protected User findUserObject() { + try { + return identityService.createUserQuery() + .userId(resourceId) + .singleResult(); + } catch(ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Exception while performing user query: "+e.getMessage()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/impl/AbstractVariablesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/impl/AbstractVariablesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..d10538dac544c1c08624ec0366673a3d670c20f6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/impl/AbstractVariablesResource.java @@ -0,0 +1,272 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.impl; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.rest.dto.PatchVariablesDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData.FormPart; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.runtime.DeserializationTypeValidator; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.TypedValue; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; + + +public abstract class AbstractVariablesResource implements VariableResource { + + protected static final String DEFAULT_BINARY_VALUE_TYPE = "Bytes"; + + protected ProcessEngine engine; + protected String resourceId; + protected ObjectMapper objectMapper; + + public AbstractVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) { + this.engine = engine; + this.resourceId = resourceId; + this.objectMapper = objectMapper; + } + + @Override + public Map getVariables(boolean deserializeValues) { + + VariableMap variables = getVariableEntities(deserializeValues); + + return VariableValueDto.fromMap(variables); + } + + @Override + public VariableValueDto getVariable(String variableName, boolean deserializeValue) { + TypedValue value = getTypedValueForVariable(variableName, deserializeValue); + return VariableValueDto.fromTypedValue(value); + + } + + protected TypedValue getTypedValueForVariable(String variableName, boolean deserializeValue) { + TypedValue value = null; + try { + value = getVariableEntity(variableName, deserializeValue); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot get %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + + if (value == null) { + String errorMessage = String.format("%s variable with name %s does not exist", getResourceTypeName(), variableName); + throw new InvalidRequestException(Status.NOT_FOUND, errorMessage); + } + return value; + } + + public Response getVariableBinary(String variableName) { + TypedValue typedValue = getTypedValueForVariable(variableName, false); + return new VariableResponseProvider().getResponseForTypedVariable(typedValue, resourceId); + } + + @Override + public void putVariable(String variableName, VariableValueDto variable) { + + try { + TypedValue typedValue = variable.toTypedValue(engine, objectMapper); + setVariableEntity(variableName, typedValue); + + } catch (RestException e) { + throw new InvalidRequestException(e.getStatus(), e, + String.format("Cannot put %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage())); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, + String.format("Cannot put %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage())); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, + String.format("Cannot put %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage())); + } + } + + public void setBinaryVariable(String variableKey, MultipartFormData payload) { + FormPart dataPart = payload.getNamedPart("data"); + FormPart objectTypePart = payload.getNamedPart("type"); + FormPart valueTypePart = payload.getNamedPart("valueType"); + + if(objectTypePart != null) { + Object object = null; + + if(dataPart.getContentType()!=null + && dataPart.getContentType().toLowerCase().contains(MediaType.APPLICATION_JSON)) { + + object = deserializeJsonObject(objectTypePart.getTextContent(), dataPart.getBinaryContent()); + + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Unrecognized content type for serialized java type: "+dataPart.getContentType()); + } + + if(object != null) { + setVariableEntity(variableKey, Variables.objectValue(object).create()); + } + } else { + + String valueTypeName = DEFAULT_BINARY_VALUE_TYPE; + if (valueTypePart != null) { + if (valueTypePart.getTextContent() == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, + "Form part with name 'valueType' must have a text/plain value"); + } + + valueTypeName = valueTypePart.getTextContent(); + } + + VariableValueDto valueDto = VariableValueDto.fromFormPart(valueTypeName, dataPart); + try { + + TypedValue typedValue = valueDto.toTypedValue(engine, objectMapper); + setVariableEntity(variableKey, typedValue); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot put %s variable %s: %s", getResourceTypeName(), variableKey, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + } + } + + protected Object deserializeJsonObject(String className, byte[] data) { + try { + JavaType type = TypeFactory.defaultInstance().constructFromCanonical(className); + validateType(type); + return objectMapper.readValue(new String(data, Charset.forName("UTF-8")), type); + } catch(Exception e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, "Could not deserialize JSON object: "+e.getMessage()); + } + } + + /** + * Validate the type with the help of the validator in the engine.
+ * Note: when adjusting this method, please also consider adjusting + * the {@code JacksonJsonDataFormatMapper#validateType} in the Engine Spin Plugin + */ + protected void validateType(JavaType type) { + if (getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()) { + DeserializationTypeValidator validator = getProcessEngineConfiguration().getDeserializationTypeValidator(); + if (validator != null) { + List invalidTypes = new ArrayList<>(); + validateType(type, validator, invalidTypes); + if (!invalidTypes.isEmpty()) { + throw new IllegalArgumentException("The following classes are not whitelisted for deserialization: " + invalidTypes); + } + } + } + } + + protected void validateType(JavaType type, DeserializationTypeValidator validator, List invalidTypes) { + if (!type.isPrimitive()) { + if (!type.isArrayType()) { + validateTypeInternal(type, validator, invalidTypes); + } + if (type.isMapLikeType()) { + validateType(type.getKeyType(), validator, invalidTypes); + } + if (type.isContainerType() || type.hasContentType()) { + validateType(type.getContentType(), validator, invalidTypes); + } + } + } + + protected void validateTypeInternal(JavaType type, DeserializationTypeValidator validator, List invalidTypes) { + String className = type.getRawClass().getName(); + if (!validator.validate(className) && !invalidTypes.contains(className)) { + invalidTypes.add(className); + } + } + + protected ProcessEngineConfiguration getProcessEngineConfiguration() { + return engine.getProcessEngineConfiguration(); + } + + @Override + public void deleteVariable(String variableName) { + try { + removeVariableEntity(variableName); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot delete %s variable %s: %s", getResourceTypeName(), variableName, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + + } + + @Override + public void modifyVariables(PatchVariablesDto patch) { + VariableMap variableModifications = null; + try { + variableModifications = VariableValueDto.toMap(patch.getModifications(), engine, objectMapper); + + } catch (RestException e) { + String errorMessage = String.format("Cannot modify variables for %s: %s", getResourceTypeName(), e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } + + List variableDeletions = patch.getDeletions(); + + try { + updateVariableEntities(variableModifications, variableDeletions); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot modify variables for %s %s: %s", getResourceTypeName(), resourceId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + + + } + + protected abstract VariableMap getVariableEntities(boolean deserializeValues); + + protected abstract void updateVariableEntities(VariableMap variables, List deletions); + + protected abstract TypedValue getVariableEntity(String variableKey, boolean deserializeValue); + + protected abstract void setVariableEntity(String variableKey, TypedValue variableValue); + + protected abstract void removeVariableEntity(String variableKey); + + protected abstract String getResourceTypeName(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/impl/VariableResponseProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/impl/VariableResponseProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..9f5bfeede1d8774176cbbd9a17985188a4ec304f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/impl/VariableResponseProvider.java @@ -0,0 +1,68 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.impl; + +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.BytesValue; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; + +/** + * @author Christopher Zell + */ +public class VariableResponseProvider { + + public Response getResponseForTypedVariable(TypedValue typedVariableValue, String id) { + if (typedVariableValue instanceof BytesValue || ValueType.BYTES.equals(typedVariableValue.getType())) { + return responseForByteVariable(typedVariableValue); + } else if (ValueType.FILE.equals(typedVariableValue.getType())) { + return responseForFileVariable((FileValue) typedVariableValue); + } else { + throw new InvalidRequestException(Response.Status.BAD_REQUEST, String.format("Value of variable with id %s is not a binary value.", id)); + } + } + + + /** + * Creates a response for a variable of type {@link ValueType#FILE}. + */ + protected Response responseForFileVariable(FileValue fileValue) { + String type = fileValue.getMimeType() != null ? fileValue.getMimeType() : MediaType.APPLICATION_OCTET_STREAM; + if (fileValue.getEncoding() != null) { + type += "; charset=" + fileValue.getEncoding(); + } + Object value = fileValue.getValue() == null ? "" : fileValue.getValue(); + return Response.ok(value, type).header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(fileValue.getFilename())).build(); + } + + /** + * Creates a response for a variable of type {@link ValueType#BYTES}. + */ + protected Response responseForByteVariable(TypedValue variableInstance) { + byte[] valueBytes = (byte[]) variableInstance.getValue(); + if (valueBytes == null) { + valueBytes = new byte[0]; + } + return Response.ok(new ByteArrayInputStream(valueBytes), MediaType.APPLICATION_OCTET_STREAM).build(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/management/JobDefinitionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/management/JobDefinitionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..872a32c6a06df3a59c79adc295cb776d4728c1d7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/management/JobDefinitionResource.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.management; + +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDefinitionPriorityDto; +import org.camunda.bpm.engine.rest.dto.runtime.RetriesDto; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +/** + * @author roman.smirnov + */ +public interface JobDefinitionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + JobDefinitionDto getJobDefinition(); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(JobDefinitionSuspensionStateDto dto); + + @PUT + @Path("/retries") + @Consumes(MediaType.APPLICATION_JSON) + void setJobRetries(RetriesDto dto); + + @PUT + @Path("/jobPriority") + @Consumes(MediaType.APPLICATION_JSON) + void setJobPriority(JobDefinitionPriorityDto dto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/management/JobDefinitionResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/management/JobDefinitionResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..9d3a9c557bbc6d7a1329d2b106949f126040f942 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/management/JobDefinitionResourceImpl.java @@ -0,0 +1,113 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.management; + +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.management.JobDefinition; +import org.camunda.bpm.engine.management.SetJobRetriesBuilder; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionDto; +import org.camunda.bpm.engine.rest.dto.management.JobDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDefinitionPriorityDto; +import org.camunda.bpm.engine.rest.dto.runtime.RetriesDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; + +/** + * @author roman.smirnov + */ +public class JobDefinitionResourceImpl implements JobDefinitionResource { + + protected ProcessEngine engine; + protected String jobDefinitionId; + + public JobDefinitionResourceImpl(ProcessEngine engine, String jobDefinitionId) { + this.engine = engine; + this.jobDefinitionId = jobDefinitionId; + } + + public JobDefinitionDto getJobDefinition() { + ManagementService managementService = engine.getManagementService(); + JobDefinition jobDefinition = managementService.createJobDefinitionQuery().jobDefinitionId(jobDefinitionId).singleResult(); + + if (jobDefinition == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Job Definition with id " + jobDefinitionId + " does not exist"); + } + + return JobDefinitionDto.fromJobDefinition(jobDefinition); + } + + public void updateSuspensionState(JobDefinitionSuspensionStateDto dto) { + try { + dto.setJobDefinitionId(jobDefinitionId); + dto.updateSuspensionState(engine); + + } catch (IllegalArgumentException e) { + String message = String.format("The suspension state of Job Definition with id %s could not be updated due to: %s", jobDefinitionId, e.getMessage()); + throw new InvalidRequestException(Status.BAD_REQUEST, e, message); + } + + } + + public void setJobRetries(RetriesDto dto) { + try { + SetJobRetriesBuilder builder = engine.getManagementService() + .setJobRetries(dto.getRetries()) + .jobDefinitionId(jobDefinitionId); + if (dto.isDueDateSet()) { + builder.dueDate(dto.getDueDate()); + } + builder.execute(); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + } + + @Override + public void setJobPriority(JobDefinitionPriorityDto dto) { + try { + ManagementService managementService = engine.getManagementService(); + + if (dto.getPriority() != null) { + managementService.setOverridingJobPriorityForJobDefinition(jobDefinitionId, dto.getPriority(), dto.isIncludeJobs()); + } + else { + if (dto.isIncludeJobs()) { + throw new InvalidRequestException(Status.BAD_REQUEST, + "Cannot reset priority for job definition " + jobDefinitionId + " with includeJobs=true"); + } + + managementService.clearOverridingJobPriorityForJobDefinition(jobDefinitionId); + } + + } catch (AuthorizationException e) { + throw e; + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/metrics/MetricsResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/metrics/MetricsResource.java new file mode 100644 index 0000000000000000000000000000000000000000..49bcd33761656bd7d9ca708b31df25baa348de6c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/metrics/MetricsResource.java @@ -0,0 +1,38 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.metrics; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.metrics.MetricsResultDto; + +/** + * @author Daniel Meyer + * + */ +public interface MetricsResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + @Path("/sum") + MetricsResultDto sum(@Context UriInfo uriInfo); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/metrics/MetricsResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/metrics/MetricsResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..3df745df4ca097bdbaeede8383cc80a2f2c4c885 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/metrics/MetricsResourceImpl.java @@ -0,0 +1,96 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.metrics; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.Date; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.management.Metrics; +import org.camunda.bpm.engine.management.MetricsQuery; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.dto.metrics.MetricsResultDto; + + +/** + * @author Daniel Meyer + * + */ +public class MetricsResourceImpl implements MetricsResource { + + protected String metricsName; + protected ProcessEngine processEngine; + protected ObjectMapper objectMapper; + + public MetricsResourceImpl(String metricsName, ProcessEngine processEngine, ObjectMapper objectMapper) { + this.metricsName = metricsName; + this.processEngine = processEngine; + this.objectMapper = objectMapper; + } + + @Override + public MetricsResultDto sum(UriInfo uriInfo) { + MultivaluedMap queryParameters = uriInfo.getQueryParameters(); + + DateConverter dateConverter = new DateConverter(); + dateConverter.setObjectMapper(objectMapper); + + Number result = null; + + if (Metrics.UNIQUE_TASK_WORKERS.equals(metricsName) || Metrics.TASK_USERS.equals(metricsName)) { + result = processEngine.getManagementService().getUniqueTaskWorkerCount( + extractStartDate(queryParameters, dateConverter), + extractEndDate(queryParameters, dateConverter)); + } else { + MetricsQuery query = processEngine.getManagementService() + .createMetricsQuery() + .name(metricsName); + + applyQueryParams(queryParameters, dateConverter, query); + result = query.sum(); + } + return new MetricsResultDto(result); + } + + protected void applyQueryParams(MultivaluedMap queryParameters, DateConverter dateConverter, MetricsQuery query) { + Date startDate = extractStartDate(queryParameters, dateConverter); + Date endDate = extractEndDate(queryParameters, dateConverter); + if (startDate != null) { + query.startDate(startDate); + } + if (endDate != null) { + query.endDate(endDate); + } + } + + protected Date extractEndDate(MultivaluedMap queryParameters, DateConverter dateConverter) { + if(queryParameters.getFirst("endDate") != null) { + return dateConverter.convertQueryParameterToType(queryParameters.getFirst("endDate")); + } + return null; + } + + protected Date extractStartDate(MultivaluedMap queryParameters, DateConverter dateConverter) { + if(queryParameters.getFirst("startDate") != null) { + return dateConverter.convertQueryParameterToType(queryParameters.getFirst("startDate")); + } + return null; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/CaseDefinitionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/CaseDefinitionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..992a3ca88320e3a82752c6771c766a10684ce8a4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/CaseDefinitionResource.java @@ -0,0 +1,60 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository; + +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.dto.repository.CaseDefinitionDiagramDto; +import org.camunda.bpm.engine.rest.dto.repository.CaseDefinitionDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.CreateCaseInstanceDto; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +/** + * @author Roman Smirnov + * + */ +public interface CaseDefinitionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + CaseDefinitionDto getCaseDefinition(); + + @GET + @Path("/xml") + @Produces(MediaType.APPLICATION_JSON) + CaseDefinitionDiagramDto getCaseDefinitionCmmnXml(); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CaseInstanceDto createCaseInstance(@Context UriInfo context, CreateCaseInstanceDto parameters); + + @GET + @Path("/diagram") + Response getCaseDefinitionDiagram(); + + @PUT + @Path("/history-time-to-live") + @Consumes(MediaType.APPLICATION_JSON) + void updateHistoryTimeToLive(HistoryTimeToLiveDto historyTimeToLiveDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DecisionDefinitionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DecisionDefinitionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..3535301c47cfbd8d1b5d8bfba2f62e1f1bc0bcbb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DecisionDefinitionResource.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.dmn.EvaluateDecisionDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionDefinitionDiagramDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionDefinitionDto; + +public interface DecisionDefinitionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + DecisionDefinitionDto getDecisionDefinition(); + + @GET + @Path("/xml") + @Produces(MediaType.APPLICATION_JSON) + DecisionDefinitionDiagramDto getDecisionDefinitionDmnXml(); + + @GET + @Path("/diagram") + Response getDecisionDefinitionDiagram(); + + @POST + @Path("/evaluate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + List> evaluateDecision(@Context UriInfo context, EvaluateDecisionDto parameters); + + @PUT + @Path("/history-time-to-live") + @Consumes(MediaType.APPLICATION_JSON) + void updateHistoryTimeToLive(HistoryTimeToLiveDto historyTimeToLiveDto); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DecisionRequirementsDefinitionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DecisionRequirementsDefinitionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..80f5387c15ae21c962af2f427bd7fa5268a07d58 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DecisionRequirementsDefinitionResource.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.repository.DecisionRequirementsDefinitionXmlDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionRequirementsDefinitionDto; + +public interface DecisionRequirementsDefinitionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + DecisionRequirementsDefinitionDto getDecisionRequirementsDefinition(); + + @GET + @Path("/xml") + @Produces(MediaType.APPLICATION_JSON) + DecisionRequirementsDefinitionXmlDto getDecisionRequirementsDefinitionDmnXml(); + + @GET + @Path("/diagram") + Response getDecisionRequirementsDefinitionDiagram(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DeploymentResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DeploymentResource.java new file mode 100644 index 0000000000000000000000000000000000000000..f575f9e41390b1bb6488f48f3cee04b23774d643 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DeploymentResource.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository; + +import org.camunda.bpm.engine.rest.dto.repository.DeploymentDto; +import org.camunda.bpm.engine.rest.dto.repository.RedeploymentDto; + +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; + +public interface DeploymentResource { + + public static final String CASCADE = "cascade"; + + @GET + @Produces(MediaType.APPLICATION_JSON) + DeploymentDto getDeployment(); + + @Path("/resources") + DeploymentResourcesResource getDeploymentResources(); + + @POST + @Path("/redeploy") + @Produces(MediaType.APPLICATION_JSON) + DeploymentDto redeploy(@Context UriInfo uriInfo, RedeploymentDto redeployment); + + @DELETE + void deleteDeployment(@PathParam("id") String deploymentId, @Context UriInfo uriInfo); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DeploymentResourcesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DeploymentResourcesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..41a7a7a13841f9b8c65257ee619bb911721152f3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/DeploymentResourcesResource.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository; + +import java.util.List; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.repository.DeploymentResourceDto; + +/** + * @author Sebastian Menski + */ +public interface DeploymentResourcesResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getDeploymentResources(); + + @GET + @Path("/{resourceId}") + @Produces(MediaType.APPLICATION_JSON) + DeploymentResourceDto getDeploymentResource(@PathParam("resourceId") String resourceId); + + @GET + @Path("/{resourceId}/data") + Response getDeploymentResourceData(@PathParam("resourceId") String resourceId); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/ProcessDefinitionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/ProcessDefinitionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..011376ed8e97c0797fdf9fdb346e2390af58ce96 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/ProcessDefinitionResource.java @@ -0,0 +1,123 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository; + +import org.camunda.bpm.engine.rest.dto.StatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.repository.CalledProcessDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionDiagramDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.RestartProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.StartProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.task.FormDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.List; +import java.util.Map; + +public interface ProcessDefinitionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + ProcessDefinitionDto getProcessDefinition(); + + @GET + @Path("/xml") + @Produces(MediaType.APPLICATION_JSON) + ProcessDefinitionDiagramDto getProcessDefinitionBpmn20Xml(); + + @GET + @Path("/diagram") + Response getProcessDefinitionDiagram(); + + @DELETE + Response deleteProcessDefinition(@QueryParam("cascade") boolean cascade, + @QueryParam("skipCustomListeners") boolean skipCustomListeners, + @QueryParam("skipIoMappings") boolean skipIoMappings); + + @POST + @Path("/start") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + ProcessInstanceDto startProcessInstance(@Context UriInfo context, StartProcessInstanceDto parameters); + + @POST + @Path("/restart") + @Consumes(MediaType.APPLICATION_JSON) + void restartProcessInstance(RestartProcessInstanceDto restartProcessInstanceDto); + + @POST + @Path("/restart-async") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto restartProcessInstanceAsync(RestartProcessInstanceDto restartProcessInstanceDto); + + @POST + @Path("/submit-form") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + ProcessInstanceDto submitForm(@Context UriInfo context, StartProcessInstanceDto parameters); + + @GET + @Path("/statistics") + @Produces(MediaType.APPLICATION_JSON) + List getActivityStatistics(@QueryParam("failedJobs") Boolean includeFailedJobs, @QueryParam("incidents") Boolean includeIncidents, @QueryParam("incidentsForType") String includeIncidentsForType); + + @GET + @Path("/startForm") + @Produces(MediaType.APPLICATION_JSON) + FormDto getStartForm(); + + @GET + @Path("/deployed-start-form") + Response getDeployedStartForm(); + + @GET + @Path("/rendered-form") + @Produces(MediaType.APPLICATION_XHTML_XML) + Response getRenderedForm(); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(ProcessDefinitionSuspensionStateDto dto); + + @PUT + @Path("/history-time-to-live") + @Consumes(MediaType.APPLICATION_JSON) + void updateHistoryTimeToLive(HistoryTimeToLiveDto historyTimeToLiveDto); + + @GET + @Path("/form-variables") + @Produces(MediaType.APPLICATION_JSON) + Map getFormVariables(@QueryParam("variableNames") String variableNames, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeValues); + + @GET + @Path("/static-called-process-definitions") + @Produces(MediaType.APPLICATION_JSON) + List getStaticCalledProcessDefinitions(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/CaseDefinitionResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/CaseDefinitionResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..aab89f5e1affe6bd2c104fb3adce8a313182d2c6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/CaseDefinitionResourceImpl.java @@ -0,0 +1,187 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.exception.NotAllowedException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.rest.CaseInstanceRestService; +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.repository.CaseDefinitionDiagramDto; +import org.camunda.bpm.engine.rest.dto.repository.CaseDefinitionDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.CreateCaseInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.CaseDefinitionResource; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; +import org.camunda.bpm.engine.runtime.CaseInstance; +import org.camunda.bpm.engine.variable.VariableMap; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseDefinitionResourceImpl implements CaseDefinitionResource { + + protected ProcessEngine engine; + protected String caseDefinitionId; + protected String rootResourcePath; + protected ObjectMapper objectMapper; + + public CaseDefinitionResourceImpl(ProcessEngine engine, String caseDefinitionId, String rootResourcePath, ObjectMapper objectMapper) { + this.engine = engine; + this.caseDefinitionId = caseDefinitionId; + this.rootResourcePath = rootResourcePath; + this.objectMapper = objectMapper; + } + + @Override + public CaseDefinitionDto getCaseDefinition() { + RepositoryService repositoryService = engine.getRepositoryService(); + + CaseDefinition definition = null; + + try { + definition = repositoryService.getCaseDefinition(caseDefinitionId); + + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } + + return CaseDefinitionDto.fromCaseDefinition(definition); + } + + @Override + public CaseDefinitionDiagramDto getCaseDefinitionCmmnXml() { + InputStream caseModelInputStream = null; + try { + caseModelInputStream = engine.getRepositoryService().getCaseModel(caseDefinitionId); + + byte[] caseModel = IoUtil.readInputStream(caseModelInputStream, "caseModelCmmnXml"); + return CaseDefinitionDiagramDto.create(caseDefinitionId, new String(caseModel, "UTF-8")); + + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } catch (UnsupportedEncodingException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } finally { + IoUtil.closeSilently(caseModelInputStream); + } + } + + public CaseInstanceDto createCaseInstance(UriInfo context, CreateCaseInstanceDto parameters) { + CaseService caseService = engine.getCaseService(); + + CaseInstance instance = null; + try { + + String businessKey = parameters.getBusinessKey(); + VariableMap variables = VariableValueDto.toMap(parameters.getVariables(), engine, objectMapper); + + instance = caseService + .withCaseDefinition(caseDefinitionId) + .businessKey(businessKey) + .setVariables(variables) + .create(); + + } catch (RestException e) { + String errorMessage = String.format("Cannot instantiate case definition %s: %s", caseDefinitionId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } catch (NotFoundException e) { + String errorMessage = String.format("Cannot instantiate case definition %s: %s", caseDefinitionId, e.getMessage()); + throw new InvalidRequestException(Status.NOT_FOUND, e, errorMessage); + + } catch (NotValidException e) { + String errorMessage = String.format("Cannot instantiate case definition %s: %s", caseDefinitionId, e.getMessage()); + throw new InvalidRequestException(Status.BAD_REQUEST, e, errorMessage); + + } catch (NotAllowedException e) { + String errorMessage = String.format("Cannot instantiate case definition %s: %s", caseDefinitionId, e.getMessage()); + throw new InvalidRequestException(Status.FORBIDDEN, e, errorMessage); + + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot instantiate case definition %s: %s", caseDefinitionId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + + } + + CaseInstanceDto result = CaseInstanceDto.fromCaseInstance(instance); + + URI uri = context.getBaseUriBuilder() + .path(rootResourcePath) + .path(CaseInstanceRestService.PATH) + .path(instance.getId()) + .build(); + + result.addReflexiveLink(uri, HttpMethod.GET, "self"); + + return result; + } + + @Override + public Response getCaseDefinitionDiagram() { + CaseDefinition definition = engine.getRepositoryService().getCaseDefinition(caseDefinitionId); + InputStream caseDiagram = engine.getRepositoryService().getCaseDiagram(caseDefinitionId); + if (caseDiagram == null) { + return Response.noContent().build(); + } else { + String fileName = definition.getDiagramResourceName(); + return Response.ok(caseDiagram).header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(fileName)) + .type(ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix(fileName)).build(); + } + } + + @Override + public void updateHistoryTimeToLive(HistoryTimeToLiveDto historyTimeToLiveDto) { + engine.getRepositoryService().updateCaseDefinitionHistoryTimeToLive(caseDefinitionId, historyTimeToLiveDto.getHistoryTimeToLive()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DecisionDefinitionResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DecisionDefinitionResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..8e478378cb608fc76c78888dc496cf268c9d1431 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DecisionDefinitionResourceImpl.java @@ -0,0 +1,195 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository.impl; + +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.dmn.engine.DmnDecisionResult; +import org.camunda.bpm.dmn.engine.DmnDecisionResultEntries; +import org.camunda.bpm.dmn.engine.DmnEngineException; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.DecisionService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.repository.DecisionDefinition; +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.dmn.EvaluateDecisionDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionDefinitionDiagramDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionDefinitionDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.DecisionDefinitionResource; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class DecisionDefinitionResourceImpl implements DecisionDefinitionResource { + + protected ProcessEngine engine; + protected String decisionDefinitionId; + protected String rootResourcePath; + protected ObjectMapper objectMapper; + + public DecisionDefinitionResourceImpl(ProcessEngine engine, String decisionDefinitionId, String rootResourcePath, ObjectMapper objectMapper) { + this.engine = engine; + this.decisionDefinitionId = decisionDefinitionId; + this.rootResourcePath = rootResourcePath; + this.objectMapper = objectMapper; + } + + @Override + public DecisionDefinitionDto getDecisionDefinition() { + RepositoryService repositoryService = engine.getRepositoryService(); + + DecisionDefinition definition = null; + + try { + definition = repositoryService.getDecisionDefinition(decisionDefinitionId); + + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } + + return DecisionDefinitionDto.fromDecisionDefinition(definition); + } + + @Override + public DecisionDefinitionDiagramDto getDecisionDefinitionDmnXml() { + InputStream decisionModelInputStream = null; + try { + decisionModelInputStream = engine.getRepositoryService().getDecisionModel(decisionDefinitionId); + + byte[] decisionModel = IoUtil.readInputStream(decisionModelInputStream, "decisionModelDmnXml"); + return DecisionDefinitionDiagramDto.create(decisionDefinitionId, new String(decisionModel, "UTF-8")); + + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } catch (UnsupportedEncodingException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } finally { + IoUtil.closeSilently(decisionModelInputStream); + } + } + + @Override + public Response getDecisionDefinitionDiagram() { + DecisionDefinition definition = engine.getRepositoryService().getDecisionDefinition(decisionDefinitionId); + InputStream decisionDiagram = engine.getRepositoryService().getDecisionDiagram(decisionDefinitionId); + if (decisionDiagram == null) { + return Response.noContent().build(); + } else { + String fileName = definition.getDiagramResourceName(); + return Response.ok(decisionDiagram).header("Content-Disposition",URLEncodingUtil.buildAttachmentValue(fileName)) + .type(ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix(fileName)).build(); + } + } + + @Override + public List> evaluateDecision(UriInfo context, EvaluateDecisionDto parameters) { + DecisionService decisionService = engine.getDecisionService(); + + Map variables = VariableValueDto.toMap(parameters.getVariables(), engine, objectMapper); + + try { + DmnDecisionResult decisionResult = decisionService + .evaluateDecisionById(decisionDefinitionId) + .variables(variables) + .evaluate(); + + return createDecisionResultDto(decisionResult); + + } + catch (AuthorizationException e) { + throw e; + } + catch (NotFoundException e) { + String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); + throw new InvalidRequestException(Status.NOT_FOUND, e, errorMessage); + } + catch (NotValidException e) { + String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); + throw new InvalidRequestException(Status.BAD_REQUEST, e, errorMessage); + } + catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + catch (DmnEngineException e) { + String errorMessage = String.format("Cannot evaluate decision %s: %s", decisionDefinitionId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + } + + @Override + public void updateHistoryTimeToLive(HistoryTimeToLiveDto historyTimeToLiveDto) { + engine.getRepositoryService().updateDecisionDefinitionHistoryTimeToLive(decisionDefinitionId, historyTimeToLiveDto.getHistoryTimeToLive()); + } + + protected List> createDecisionResultDto(DmnDecisionResult decisionResult) { + List> dto = new ArrayList<>(); + + for (DmnDecisionResultEntries entries : decisionResult) { + Map resultEntriesDto = createResultEntriesDto(entries); + dto.add(resultEntriesDto); + } + + return dto; + } + + protected Map createResultEntriesDto(DmnDecisionResultEntries entries) { + VariableMap variableMap = Variables.createVariables(); + + for(String key : entries.keySet()) { + TypedValue typedValue = entries.getEntryTyped(key); + variableMap.putValueTyped(key, typedValue); + } + + return VariableValueDto.fromMap(variableMap); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DecisionRequirementsDefinitionResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DecisionRequirementsDefinitionResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..286ed85daa84f54075171b695f28fcec86c4f0e6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DecisionRequirementsDefinitionResourceImpl.java @@ -0,0 +1,115 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository.impl; + +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinition; +import org.camunda.bpm.engine.rest.dto.repository.DecisionRequirementsDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.DecisionRequirementsDefinitionXmlDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.DecisionRequirementsDefinitionResource; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; + +/** + * + * @author Deivarayan Azhagappan + * + */ +public class DecisionRequirementsDefinitionResourceImpl implements DecisionRequirementsDefinitionResource { + + protected ProcessEngine engine; + protected String decisionRequirementsDefinitionId; + + public DecisionRequirementsDefinitionResourceImpl(ProcessEngine engine, String decisionDefinitionId) { + this.engine = engine; + this.decisionRequirementsDefinitionId = decisionDefinitionId; + } + + @Override + public DecisionRequirementsDefinitionDto getDecisionRequirementsDefinition() { + RepositoryService repositoryService = engine.getRepositoryService(); + + DecisionRequirementsDefinition definition = null; + + try { + definition = repositoryService.getDecisionRequirementsDefinition(decisionRequirementsDefinitionId); + + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } + + return DecisionRequirementsDefinitionDto.fromDecisionRequirementsDefinition(definition); + } + + @Override + public DecisionRequirementsDefinitionXmlDto getDecisionRequirementsDefinitionDmnXml() { + InputStream decisionRequirementsModelInputStream = null; + try { + decisionRequirementsModelInputStream = engine.getRepositoryService().getDecisionRequirementsModel(decisionRequirementsDefinitionId); + + byte[] decisionRequirementsModel = IoUtil.readInputStream(decisionRequirementsModelInputStream, "decisionRequirementsModelDmnXml"); + return DecisionRequirementsDefinitionXmlDto.create(decisionRequirementsDefinitionId, new String(decisionRequirementsModel, "UTF-8")); + + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + + } catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, e.getMessage()); + + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } catch (UnsupportedEncodingException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + + } finally { + IoUtil.closeSilently(decisionRequirementsModelInputStream); + } + } + + @Override + public Response getDecisionRequirementsDefinitionDiagram() { + DecisionRequirementsDefinition definition = engine.getRepositoryService().getDecisionRequirementsDefinition(decisionRequirementsDefinitionId); + InputStream decisionRequirementsDiagram = engine.getRepositoryService().getDecisionRequirementsDiagram(decisionRequirementsDefinitionId); + if (decisionRequirementsDiagram == null) { + return Response.noContent().build(); + } else { + String fileName = definition.getDiagramResourceName(); + return Response.ok(decisionRequirementsDiagram).header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(fileName)) + .type(ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix(fileName)).build(); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DeploymentResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DeploymentResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..e08cc2304a47ba2302a760e71a18b7db1bde29ac --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DeploymentResourceImpl.java @@ -0,0 +1,168 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository.impl; + +import java.net.URI; +import java.util.List; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.repository.DeploymentBuilder; +import org.camunda.bpm.engine.repository.DeploymentWithDefinitions; +import org.camunda.bpm.engine.rest.DeploymentRestService; +import org.camunda.bpm.engine.rest.dto.repository.DeploymentDto; +import org.camunda.bpm.engine.rest.dto.repository.DeploymentWithDefinitionsDto; +import org.camunda.bpm.engine.rest.dto.repository.RedeploymentDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.impl.AbstractRestProcessEngineAware; +import org.camunda.bpm.engine.rest.sub.repository.DeploymentResource; +import org.camunda.bpm.engine.rest.sub.repository.DeploymentResourcesResource; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class DeploymentResourceImpl extends AbstractRestProcessEngineAware implements DeploymentResource { + + protected String deploymentId; + + public DeploymentResourceImpl(String processEngineName, String deploymentId, String rootResourcePath, ObjectMapper objectMapper) { + super(processEngineName, objectMapper); + this.deploymentId = deploymentId; + this.relativeRootResourcePath = rootResourcePath; + } + + public DeploymentDto getDeployment() { + RepositoryService repositoryService = getProcessEngine().getRepositoryService(); + Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); + + if (deployment == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Deployment with id '" + deploymentId + "' does not exist"); + } + + return DeploymentDto.fromDeployment(deployment); + } + + public DeploymentResourcesResource getDeploymentResources() { + return new DeploymentResourcesResourceImpl(getProcessEngine(), deploymentId); + } + + public DeploymentDto redeploy(UriInfo uriInfo, RedeploymentDto redeployment) { + DeploymentWithDefinitions deployment = null; + try { + deployment = tryToRedeploy(redeployment); + + } catch (NotFoundException e) { + throw createInvalidRequestException("redeploy", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("redeploy", Status.BAD_REQUEST, e); + } + + DeploymentWithDefinitionsDto deploymentDto = DeploymentWithDefinitionsDto.fromDeployment(deployment); + + URI uri = uriInfo.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(DeploymentRestService.PATH) + .path(deployment.getId()) + .build(); + + // GET / + deploymentDto.addReflexiveLink(uri, HttpMethod.GET, "self"); + + return deploymentDto; + } + + protected DeploymentWithDefinitions tryToRedeploy(RedeploymentDto redeployment) { + RepositoryService repositoryService = getProcessEngine().getRepositoryService(); + + DeploymentBuilder builder = repositoryService.createDeployment(); + builder.nameFromDeployment(deploymentId); + + String tenantId = getDeployment().getTenantId(); + if (tenantId != null) { + builder.tenantId(tenantId); + } + + if (redeployment != null) { + builder = addRedeploymentResources(builder, redeployment); + } else { + builder.addDeploymentResources(deploymentId); + } + + return builder.deployWithResult(); + } + + protected DeploymentBuilder addRedeploymentResources(DeploymentBuilder builder, RedeploymentDto redeployment) { + builder.source(redeployment.getSource()); + + List resourceIds = redeployment.getResourceIds(); + List resourceNames = redeployment.getResourceNames(); + + boolean isResourceIdListEmpty = resourceIds == null || resourceIds.isEmpty(); + boolean isResourceNameListEmpty = resourceNames == null || resourceNames.isEmpty(); + + if (isResourceIdListEmpty && isResourceNameListEmpty) { + builder.addDeploymentResources(deploymentId); + + } else { + if (!isResourceIdListEmpty) { + builder.addDeploymentResourcesById(deploymentId, resourceIds); + } + if (!isResourceNameListEmpty) { + builder.addDeploymentResourcesByName(deploymentId, resourceNames); + } + } + return builder; + } + + @Override + public void deleteDeployment(String deploymentId, UriInfo uriInfo) { + RepositoryService repositoryService = getProcessEngine().getRepositoryService(); + Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); + + if (deployment == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Deployment with id '" + deploymentId + "' do not exist"); + } + + boolean cascade = isQueryPropertyEnabled(uriInfo, CASCADE); + boolean skipCustomListeners = isQueryPropertyEnabled(uriInfo, "skipCustomListeners"); + boolean skipIoMappings = isQueryPropertyEnabled(uriInfo, "skipIoMappings"); + + repositoryService.deleteDeployment(deploymentId, cascade, skipCustomListeners, skipIoMappings); + } + + protected boolean isQueryPropertyEnabled(UriInfo uriInfo, String property) { + MultivaluedMap queryParams = uriInfo.getQueryParameters(); + + return queryParams.containsKey(property) + && queryParams.get(property).size() > 0 + && "true".equals(queryParams.get(property).get(0)); + } + + protected InvalidRequestException createInvalidRequestException(String action, Status status, ProcessEngineException cause) { + String errorMessage = String.format("Cannot %s deployment '%s': %s", action, deploymentId, cause.getMessage()); + return new InvalidRequestException(status, cause, errorMessage); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DeploymentResourcesResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DeploymentResourcesResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..951f61d814cd9155512784adefa8827738aa5db9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/DeploymentResourcesResourceImpl.java @@ -0,0 +1,157 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository.impl; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.repository.Resource; +import org.camunda.bpm.engine.rest.dto.repository.DeploymentResourceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.repository.DeploymentResourcesResource; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; + +/** + * @author Sebastian Menski + */ +public class DeploymentResourcesResourceImpl implements DeploymentResourcesResource { + + protected static final Map MEDIA_TYPE_MAPPING = new HashMap(); + + static { + MEDIA_TYPE_MAPPING.put("bpmn", MediaType.APPLICATION_XML); + MEDIA_TYPE_MAPPING.put("cmmn", MediaType.APPLICATION_XML); + MEDIA_TYPE_MAPPING.put("dmn", MediaType.APPLICATION_XML); + MEDIA_TYPE_MAPPING.put("json", MediaType.APPLICATION_JSON); + MEDIA_TYPE_MAPPING.put("xml", MediaType.APPLICATION_XML); + + MEDIA_TYPE_MAPPING.put("gif", "image/gif"); + MEDIA_TYPE_MAPPING.put("jpeg", "image/jpeg"); + MEDIA_TYPE_MAPPING.put("jpe", "image/jpeg"); + MEDIA_TYPE_MAPPING.put("jpg", "image/jpeg"); + MEDIA_TYPE_MAPPING.put("png", "image/png"); + MEDIA_TYPE_MAPPING.put("svg", "image/svg+xml"); + MEDIA_TYPE_MAPPING.put("tiff", "image/tiff"); + MEDIA_TYPE_MAPPING.put("tif", "image/tiff"); + + MEDIA_TYPE_MAPPING.put("groovy", "text/plain"); + MEDIA_TYPE_MAPPING.put("java", "text/plain"); + MEDIA_TYPE_MAPPING.put("js", "text/plain"); + MEDIA_TYPE_MAPPING.put("php", "text/plain"); + MEDIA_TYPE_MAPPING.put("py", "text/plain"); + MEDIA_TYPE_MAPPING.put("rb", "text/plain"); + + MEDIA_TYPE_MAPPING.put("html", "text/html"); + MEDIA_TYPE_MAPPING.put("txt", "text/plain"); + } + + protected final ProcessEngine engine; + protected final String deploymentId; + + public DeploymentResourcesResourceImpl(ProcessEngine engine, String deploymentId) { + this.engine = engine; + this.deploymentId = deploymentId; + } + + public List getDeploymentResources() { + List resources = engine.getRepositoryService().getDeploymentResources(deploymentId); + + List deploymentResources = new ArrayList(); + for (Resource resource : resources) { + deploymentResources.add(DeploymentResourceDto.fromResources(resource)); + } + + if (!deploymentResources.isEmpty()) { + return deploymentResources; + } + else { + throw new InvalidRequestException(Status.NOT_FOUND, + "Deployment resources for deployment id '" + deploymentId + "' do not exist."); + } + } + + public DeploymentResourceDto getDeploymentResource(String resourceId) { + List deploymentResources = getDeploymentResources(); + for (DeploymentResourceDto deploymentResource : deploymentResources) { + if (deploymentResource.getId().equals(resourceId)) { + return deploymentResource; + } + } + + throw new InvalidRequestException(Status.NOT_FOUND, + "Deployment resource with resource id '" + resourceId + "' for deployment id '" + deploymentId + "' does not exist."); + } + + public Response getDeploymentResourceData(String resourceId) { + RepositoryService repositoryService = engine.getRepositoryService(); + InputStream resourceAsStream = repositoryService.getResourceAsStreamById(deploymentId, resourceId); + + if (resourceAsStream != null) { + + DeploymentResourceDto resource = getDeploymentResource(resourceId); + + String name = resource.getName(); + + String filename = null; + String mediaType = null; + + if (name != null) { + name = name.replace("\\", "/"); + String[] filenameParts = name.split("/"); + if (filenameParts.length > 0) { + int idx = filenameParts.length-1; + filename = filenameParts[idx]; + } + + String[] extensionParts = name.split("\\."); + if (extensionParts.length > 0) { + int idx = extensionParts.length-1; + String extension = extensionParts[idx]; + if (extension != null) { + mediaType = MEDIA_TYPE_MAPPING.get(extension); + } + } + } + + if (filename == null) { + filename = "data"; + } + + if (mediaType == null) { + mediaType = MediaType.APPLICATION_OCTET_STREAM; + } + + return Response + .ok(resourceAsStream, mediaType) + .header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(filename)) + .build(); + } + else { + throw new InvalidRequestException(Status.NOT_FOUND, + "Deployment resource '" + resourceId + "' for deployment id '" + deploymentId + "' does not exist."); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/IncidentResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/IncidentResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..5f705556ba4620e550fd05882ce3e236bc0b6e47 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/IncidentResourceImpl.java @@ -0,0 +1,74 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository.impl; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.rest.dto.AnnotationDto; +import org.camunda.bpm.engine.rest.dto.runtime.IncidentDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.runtime.IncidentResource; +import org.camunda.bpm.engine.runtime.Incident; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class IncidentResourceImpl implements IncidentResource { + + protected ProcessEngine engine; + protected String incidentId; + protected ObjectMapper objectMapper; + + public IncidentResourceImpl(ProcessEngine engine, String incidentId, ObjectMapper objectMapper) { + this.engine = engine; + this.incidentId = incidentId; + this.objectMapper = objectMapper; + } + + public IncidentDto getIncident() { + Incident incident = engine.getRuntimeService().createIncidentQuery().incidentId(incidentId).singleResult(); + if (incident == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "No matching incident with id " + incidentId); + } + return IncidentDto.fromIncident(incident); + } + + public void resolveIncident() { + try { + engine.getRuntimeService().resolveIncident(incidentId); + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public Response setAnnotation(AnnotationDto annotationDto) { + engine.getRuntimeService().setAnnotationForIncidentById(incidentId, annotationDto.getAnnotation()); + return Response.noContent().build(); + } + + @Override + public Response clearAnnotation() { + engine.getRuntimeService().clearAnnotationForIncidentById(incidentId); + return Response.noContent().build(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/ProcessDefinitionResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/ProcessDefinitionResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..14fe0e1922df8d594118e4666eaa0f59d7d74393 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/repository/impl/ProcessDefinitionResourceImpl.java @@ -0,0 +1,473 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.repository.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.FormService; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.form.CamundaFormRef; +import org.camunda.bpm.engine.form.StartFormData; +import org.camunda.bpm.engine.impl.form.validator.FormFieldValidationException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.management.ActivityStatistics; +import org.camunda.bpm.engine.management.ActivityStatisticsQuery; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.rest.ProcessInstanceRestService; +import org.camunda.bpm.engine.rest.dto.StatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.repository.ActivityStatisticsResultDto; +import org.camunda.bpm.engine.rest.dto.repository.CalledProcessDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionDiagramDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionDto; +import org.camunda.bpm.engine.rest.dto.repository.ProcessDefinitionSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceWithVariablesDto; +import org.camunda.bpm.engine.rest.dto.runtime.RestartProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.StartProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.modification.ProcessInstanceModificationInstructionDto; +import org.camunda.bpm.engine.rest.dto.task.FormDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.repository.ProcessDefinitionResource; +import org.camunda.bpm.engine.rest.util.ApplicationContextPathUtil; +import org.camunda.bpm.engine.rest.util.ContentTypeUtil; +import org.camunda.bpm.engine.rest.util.EncodingUtil; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceWithVariables; +import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder; +import org.camunda.bpm.engine.runtime.RestartProcessInstanceBuilder; +import org.camunda.bpm.engine.variable.VariableMap; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class ProcessDefinitionResourceImpl implements ProcessDefinitionResource { + + protected ProcessEngine engine; + protected String processDefinitionId; + protected String rootResourcePath; + protected ObjectMapper objectMapper; + + public ProcessDefinitionResourceImpl(ProcessEngine engine, String processDefinitionId, String rootResourcePath, ObjectMapper objectMapper) { + this.engine = engine; + this.processDefinitionId = processDefinitionId; + this.rootResourcePath = rootResourcePath; + this.objectMapper = objectMapper; + } + + @Override + public ProcessDefinitionDto getProcessDefinition() { + RepositoryService repoService = engine.getRepositoryService(); + + ProcessDefinition definition; + try { + definition = repoService.getProcessDefinition(processDefinitionId); + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, "No matching definition with id " + processDefinitionId); + } + + ProcessDefinitionDto result = ProcessDefinitionDto.fromProcessDefinition(definition); + + return result; + } + + @Override + public Response deleteProcessDefinition(boolean cascade, boolean skipCustomListeners, boolean skipIoMappings) { + RepositoryService repositoryService = engine.getRepositoryService(); + + try { + repositoryService.deleteProcessDefinition(processDefinitionId, cascade, skipCustomListeners, skipIoMappings); + } catch (NotFoundException nfe) { + throw new InvalidRequestException(Status.NOT_FOUND, nfe, nfe.getMessage()); + } + return Response.ok().build(); + } + + @Override + public ProcessInstanceDto startProcessInstance(UriInfo context, StartProcessInstanceDto parameters) { + ProcessInstanceWithVariables instance = null; + try { + instance = startProcessInstanceAtActivities(parameters); + } catch (AuthorizationException e) { + throw e; + + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot instantiate process definition %s: %s", processDefinitionId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + + } catch (RestException e) { + String errorMessage = String.format("Cannot instantiate process definition %s: %s", processDefinitionId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } + + ProcessInstanceDto result; + if (parameters.isWithVariablesInReturn()) { + result = ProcessInstanceWithVariablesDto.fromProcessInstance(instance); + } + else { + result = ProcessInstanceDto.fromProcessInstance(instance); + } + + URI uri = context.getBaseUriBuilder() + .path(rootResourcePath) + .path(ProcessInstanceRestService.PATH) + .path(instance.getId()) + .build(); + + result.addReflexiveLink(uri, HttpMethod.GET, "self"); + + return result; + } + + protected ProcessInstanceWithVariables startProcessInstanceAtActivities(StartProcessInstanceDto dto) { + Map processInstanceVariables = VariableValueDto.toMap(dto.getVariables(), engine, objectMapper); + String businessKey = dto.getBusinessKey(); + String caseInstanceId = dto.getCaseInstanceId(); + + ProcessInstantiationBuilder instantiationBuilder = engine.getRuntimeService() + .createProcessInstanceById(processDefinitionId) + .businessKey(businessKey) + .caseInstanceId(caseInstanceId) + .setVariables(processInstanceVariables); + + if (dto.getStartInstructions() != null && !dto.getStartInstructions().isEmpty()) { + for (ProcessInstanceModificationInstructionDto instruction : dto.getStartInstructions()) { + instruction.applyTo(instantiationBuilder, engine, objectMapper); + } + } + + return instantiationBuilder.executeWithVariablesInReturn(dto.isSkipCustomListeners(), dto.isSkipIoMappings()); + } + + @Override + public ProcessInstanceDto submitForm(UriInfo context, StartProcessInstanceDto parameters) { + FormService formService = engine.getFormService(); + + ProcessInstance instance = null; + try { + Map variables = VariableValueDto.toMap(parameters.getVariables(), engine, objectMapper); + String businessKey = parameters.getBusinessKey(); + if (businessKey != null) { + instance = formService.submitStartForm(processDefinitionId, businessKey, variables); + } else { + instance = formService.submitStartForm(processDefinitionId, variables); + } + + } catch (AuthorizationException e) { + throw e; + + } catch (FormFieldValidationException e) { + String errorMessage = String.format("Cannot instantiate process definition %s: %s", processDefinitionId, e.getMessage()); + throw new RestException(Status.BAD_REQUEST, e, errorMessage); + + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot instantiate process definition %s: %s", processDefinitionId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + + } catch (RestException e) { + String errorMessage = String.format("Cannot instantiate process definition %s: %s", processDefinitionId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } + + ProcessInstanceDto result = ProcessInstanceDto.fromProcessInstance(instance); + + URI uri = context.getBaseUriBuilder() + .path(rootResourcePath) + .path(ProcessInstanceRestService.PATH) + .path(instance.getId()) + .build(); + + result.addReflexiveLink(uri, HttpMethod.GET, "self"); + + return result; + } + + + @Override + public List getActivityStatistics(Boolean includeFailedJobs, Boolean includeIncidents, String includeIncidentsForType) { + if (includeIncidents != null && includeIncidentsForType != null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "Only one of the query parameter includeIncidents or includeIncidentsForType can be set."); + } + + ManagementService mgmtService = engine.getManagementService(); + ActivityStatisticsQuery query = mgmtService.createActivityStatisticsQuery(processDefinitionId); + + if (includeFailedJobs != null && includeFailedJobs) { + query.includeFailedJobs(); + } + + if (includeIncidents != null && includeIncidents) { + query.includeIncidents(); + } else if (includeIncidentsForType != null) { + query.includeIncidentsForType(includeIncidentsForType); + } + + List queryResults = query.unlimitedList(); + + List results = new ArrayList<>(); + for (ActivityStatistics queryResult : queryResults) { + StatisticsResultDto dto = ActivityStatisticsResultDto.fromActivityStatistics(queryResult); + results.add(dto); + } + + return results; + } + + @Override + public ProcessDefinitionDiagramDto getProcessDefinitionBpmn20Xml() { + InputStream processModelIn = null; + try { + processModelIn = engine.getRepositoryService().getProcessModel(processDefinitionId); + byte[] processModel = IoUtil.readInputStream(processModelIn, "processModelBpmn20Xml"); + return ProcessDefinitionDiagramDto.create(processDefinitionId, new String(processModel, "UTF-8")); + } catch (AuthorizationException e) { + throw e; + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, "No matching definition with id " + processDefinitionId); + } catch (UnsupportedEncodingException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e); + } finally { + IoUtil.closeSilently(processModelIn); + } + } + + @Override + public Response getProcessDefinitionDiagram() { + ProcessDefinition definition = engine.getRepositoryService().getProcessDefinition(processDefinitionId); + InputStream processDiagram = engine.getRepositoryService().getProcessDiagram(processDefinitionId); + if (processDiagram == null) { + return Response.noContent().build(); + } else { + String fileName = definition.getDiagramResourceName(); + return Response.ok(processDiagram) + .header("Content-Disposition", URLEncodingUtil.buildAttachmentValue(fileName)) + .type(getMediaTypeForFileSuffix(fileName)).build(); + } + } + + /** + * Determines an IANA media type based on the file suffix. + * Hint: as of Java 7 the method Files.probeContentType() provides an implementation based on file type detection. + * + * @param fileName + * @return content type, defaults to octet-stream + */ + public static String getMediaTypeForFileSuffix(String fileName) { + String mediaType = "application/octet-stream"; // default + if (fileName != null) { + fileName = fileName.toLowerCase(); + if (fileName.endsWith(".png")) { + mediaType = "image/png"; + } else if (fileName.endsWith(".svg")) { + mediaType = "image/svg+xml"; + } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) { + mediaType = "image/jpeg"; + } else if (fileName.endsWith(".gif")) { + mediaType = "image/gif"; + } else if (fileName.endsWith(".bmp")) { + mediaType = "image/bmp"; + } + } + return mediaType; + } + + @Override + public FormDto getStartForm() { + final FormService formService = engine.getFormService(); + + final StartFormData formData; + try { + formData = formService.getStartFormData(processDefinitionId); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Cannot get start form data for process definition " + processDefinitionId); + } + FormDto dto = FormDto.fromFormData(formData); + if((dto.getKey() == null || dto.getKey().isEmpty()) && dto.getCamundaFormRef() == null) { + if(formData != null && formData.getFormFields() != null && !formData.getFormFields().isEmpty()) { + dto.setKey("embedded:engine://engine/:engine/process-definition/"+processDefinitionId+"/rendered-form"); + } + } + dto.setContextPath(ApplicationContextPathUtil.getApplicationPathByProcessDefinitionId(engine, processDefinitionId)); + + return dto; + } + + public Response getRenderedForm() { + FormService formService = engine.getFormService(); + + Object startForm = formService.getRenderedStartForm(processDefinitionId); + if (startForm != null) { + String content = startForm.toString(); + InputStream stream = new ByteArrayInputStream(content.getBytes(EncodingUtil.DEFAULT_ENCODING)); + return Response + .ok(stream) + .type(MediaType.APPLICATION_XHTML_XML) + .build(); + } + + throw new InvalidRequestException(Status.NOT_FOUND, "No matching rendered start form for process definition with the id " + processDefinitionId + " found."); + } + + public void updateSuspensionState(ProcessDefinitionSuspensionStateDto dto) { + try { + dto.setProcessDefinitionId(processDefinitionId); + dto.updateSuspensionState(engine); + + } catch (IllegalArgumentException e) { + String message = String.format("The suspension state of Process Definition with id %s could not be updated due to: %s", processDefinitionId, e.getMessage()); + throw new InvalidRequestException(Status.BAD_REQUEST, e, message); + } + } + + @Override + public void updateHistoryTimeToLive(HistoryTimeToLiveDto historyTimeToLiveDto) { + engine.getRepositoryService().updateProcessDefinitionHistoryTimeToLive(processDefinitionId, historyTimeToLiveDto.getHistoryTimeToLive()); + } + + public Map getFormVariables(String variableNames, boolean deserializeValues) { + + final FormService formService = engine.getFormService(); + List formVariables = null; + + if(variableNames != null) { + StringListConverter stringListConverter = new StringListConverter(); + formVariables = stringListConverter.convertQueryParameterToType(variableNames); + } + + VariableMap startFormVariables = formService.getStartFormVariables(processDefinitionId, formVariables, deserializeValues); + + return VariableValueDto.fromMap(startFormVariables); + } + + @Override + public List getStaticCalledProcessDefinitions() { + try { + return engine.getRepositoryService().getStaticCalledProcessDefinitions(processDefinitionId).stream() + .map(CalledProcessDefinitionDto::from) + .collect(Collectors.toList()); + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } + } + + @Override + public void restartProcessInstance(RestartProcessInstanceDto restartProcessInstanceDto) { + try { + createRestartProcessInstanceBuilder(restartProcessInstanceDto).execute(); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public BatchDto restartProcessInstanceAsync(RestartProcessInstanceDto restartProcessInstanceDto) { + Batch batch = null; + try { + batch = createRestartProcessInstanceBuilder(restartProcessInstanceDto).executeAsync(); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + return BatchDto.fromBatch(batch); + } + + private RestartProcessInstanceBuilder createRestartProcessInstanceBuilder(RestartProcessInstanceDto restartProcessInstanceDto) { + RuntimeService runtimeService = engine.getRuntimeService(); + RestartProcessInstanceBuilder builder = runtimeService + .restartProcessInstances(processDefinitionId); + + if (restartProcessInstanceDto.getProcessInstanceIds() != null) { + builder.processInstanceIds(restartProcessInstanceDto.getProcessInstanceIds()); + } + + if (restartProcessInstanceDto.getHistoricProcessInstanceQuery() != null) { + builder.historicProcessInstanceQuery(restartProcessInstanceDto.getHistoricProcessInstanceQuery().toQuery(engine)); + } + + if (restartProcessInstanceDto.isInitialVariables()) { + builder.initialSetOfVariables(); + } + + if (restartProcessInstanceDto.isWithoutBusinessKey()) { + builder.withoutBusinessKey(); + } + + if (restartProcessInstanceDto.isSkipCustomListeners()) { + builder.skipCustomListeners(); + } + + if (restartProcessInstanceDto.isSkipIoMappings()) { + builder.skipIoMappings(); + } + restartProcessInstanceDto.applyTo(builder, engine, objectMapper); + return builder; + } + + public Response getDeployedStartForm() { + try { + InputStream deployedStartForm = engine.getFormService().getDeployedStartForm(processDefinitionId); + return Response.ok(deployedStartForm, getStartFormMediaType(processDefinitionId)).build(); + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } catch (AuthorizationException e) { + throw new InvalidRequestException(Status.FORBIDDEN, e.getMessage()); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + protected String getStartFormMediaType(String processDefinitionId) { + String formKey = engine.getFormService().getStartFormKey(processDefinitionId); + CamundaFormRef camundaFormRef = engine.getFormService().getStartFormData(processDefinitionId).getCamundaFormRef(); + if(formKey != null) { + return ContentTypeUtil.getFormContentType(formKey); + } else if(camundaFormRef != null) { + return ContentTypeUtil.getFormContentType(camundaFormRef); + } + return MediaType.APPLICATION_XHTML_XML; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/CaseExecutionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/CaseExecutionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..b955cd9053ed60f5b1305a689ad102bc1ae55a9c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/CaseExecutionResource.java @@ -0,0 +1,70 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionTriggerDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + + +/** + * + * @author Roman Smirnov + * + */ +public interface CaseExecutionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + CaseExecutionDto getCaseExecution(); + + @POST + @Path("/manual-start") + @Consumes(MediaType.APPLICATION_JSON) + void manualStart(CaseExecutionTriggerDto triggerDto); + + @POST + @Path("/disable") + @Consumes(MediaType.APPLICATION_JSON) + void disable(CaseExecutionTriggerDto triggerDto); + + @POST + @Path("/reenable") + @Consumes(MediaType.APPLICATION_JSON) + void reenable(CaseExecutionTriggerDto triggerDto); + + @POST + @Path("/complete") + @Consumes(MediaType.APPLICATION_JSON) + void complete(CaseExecutionTriggerDto triggerDto); + + @POST + @Path("/terminate") + @Consumes(MediaType.APPLICATION_JSON) + void terminate(CaseExecutionTriggerDto triggerDto); + + @Path("/localVariables") + VariableResource getVariablesLocal(); + + @Path("/variables") + VariableResource getVariables(); + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/CaseInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/CaseInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..7ad7588af914c7041529da85e2fc9752ec531ef2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/CaseInstanceResource.java @@ -0,0 +1,55 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionTriggerDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +/** + * + * @author Roman Smirnov + * + */ +public interface CaseInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + CaseInstanceDto getCaseInstance(); + + @POST + @Path("/complete") + @Consumes(MediaType.APPLICATION_JSON) + void complete(CaseExecutionTriggerDto triggerDto); + + @POST + @Path("/close") + @Consumes(MediaType.APPLICATION_JSON) + void close(CaseExecutionTriggerDto triggerDto); + + @POST + @Path("/terminate") + @Consumes(MediaType.APPLICATION_JSON) + void terminate(CaseExecutionTriggerDto triggerDto); + + @Path("/variables") + VariableResource getVariablesResource(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/EventSubscriptionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/EventSubscriptionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..624b36117d5654dfa084007c6a5406e66baf4def --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/EventSubscriptionResource.java @@ -0,0 +1,35 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import org.camunda.bpm.engine.rest.dto.runtime.EventSubscriptionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionTriggerDto; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +public interface EventSubscriptionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + EventSubscriptionDto getEventSubscription(); + + @POST + @Path("/trigger") + @Consumes(MediaType.APPLICATION_JSON) + void triggerEvent(ExecutionTriggerDto triggerDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ExecutionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ExecutionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..46a6432e1911510ed997fdfa5fa47d1fcdbaad67 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ExecutionResource.java @@ -0,0 +1,51 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import org.camunda.bpm.engine.rest.dto.CreateIncidentDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionTriggerDto; +import org.camunda.bpm.engine.rest.dto.runtime.IncidentDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +public interface ExecutionResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + ExecutionDto getExecution(); + + @POST + @Path("/signal") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + void signalExecution(ExecutionTriggerDto triggerDto); + + @Path("/localVariables") + VariableResource getLocalVariables(); + + @Path("/messageSubscriptions/{messageName}") + EventSubscriptionResource getMessageEventSubscription(@PathParam("messageName") String messageName); + + @POST + @Path("/create-incident") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + IncidentDto createIncident(CreateIncidentDto createIncidentDto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/FilterResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/FilterResource.java new file mode 100644 index 0000000000000000000000000000000000000000..7498b9688904f8d51a6b2c457a9946dfa333d72f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/FilterResource.java @@ -0,0 +1,85 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.runtime.FilterDto; +import org.camunda.bpm.engine.rest.hal.Hal; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.UriInfo; + +/** + * @author Sebastian Menski + */ +public interface FilterResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + FilterDto getFilter(@QueryParam("itemCount") Boolean itemCount); + + @DELETE + void deleteFilter(); + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + void updateFilter(FilterDto filterDto); + + @GET + @Path("/singleResult") + @Produces({MediaType.APPLICATION_JSON, Hal.APPLICATION_HAL_JSON}) + Object executeSingleResult(@Context Request request); + + @POST + @Path("/singleResult") + @Produces({MediaType.APPLICATION_JSON, Hal.APPLICATION_HAL_JSON}) + @Consumes(MediaType.APPLICATION_JSON) + Object querySingleResult(@Context Request request, String extendingQuery); + + @GET + @Path("/list") + @Produces({MediaType.APPLICATION_JSON, Hal.APPLICATION_HAL_JSON}) + Object executeList(@Context Request request, @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @POST + @Path("/list") + @Produces({MediaType.APPLICATION_JSON, Hal.APPLICATION_HAL_JSON}) + @Consumes(MediaType.APPLICATION_JSON) + Object queryList(@Context Request request, String extendingQuery, + @QueryParam("firstResult") Integer firstResult, @QueryParam("maxResults") Integer maxResults); + + @GET + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + CountResultDto executeCount(); + + @POST + @Path("/count") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + CountResultDto queryCount(String extendingQuery); + + @OPTIONS + @Produces(MediaType.APPLICATION_JSON) + ResourceOptionsDto availableOperations(@Context UriInfo context); + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/IncidentResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/IncidentResource.java new file mode 100644 index 0000000000000000000000000000000000000000..e8ad1fce71f99064cc00269c81bb2c0075a7e027 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/IncidentResource.java @@ -0,0 +1,50 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.AnnotationDto; +import org.camunda.bpm.engine.rest.dto.runtime.IncidentDto; + +public interface IncidentResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + IncidentDto getIncident(); + + @DELETE + void resolveIncident(); + + @PUT + @Path("/annotation") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + Response setAnnotation(AnnotationDto annotationDto); + + @DELETE + @Path("/annotation") + @Produces(MediaType.APPLICATION_JSON) + Response clearAnnotation(); +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/JobResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/JobResource.java new file mode 100644 index 0000000000000000000000000000000000000000..9b29fdfbc6bf15fa3af5b5f4e99cefa80be8cd84 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/JobResource.java @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.runtime.JobDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDuedateDto; +import org.camunda.bpm.engine.rest.dto.runtime.PriorityDto; +import org.camunda.bpm.engine.rest.dto.runtime.RetriesDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobSuspensionStateDto; + +public interface JobResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + JobDto getJob(); + + @GET + @Path("/stacktrace") + @Produces(MediaType.TEXT_PLAIN) + String getStacktrace(); + + @PUT + @Path("/retries") + @Consumes(MediaType.APPLICATION_JSON) + void setJobRetries(RetriesDto dto); + + @POST + @Path("/execute") + void executeJob(); + + @PUT + @Path("/duedate") + @Consumes(MediaType.APPLICATION_JSON) + void setJobDuedate(JobDuedateDto dto); + + @POST + @Path("/duedate/recalculate") + void recalculateDuedate(@DefaultValue("true") @QueryParam("creationDateBased") boolean creationDateBased); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(JobSuspensionStateDto dto); + + @PUT + @Path("/priority") + @Consumes(MediaType.APPLICATION_JSON) + void setJobPriority(PriorityDto dto); + + @DELETE + void deleteJob(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ProcessInstanceCommentResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ProcessInstanceCommentResource.java new file mode 100644 index 0000000000000000000000000000000000000000..e1a3fa2d88f8fb4afcf4a0fc08e2b8474b2165f6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ProcessInstanceCommentResource.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import java.util.List; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import org.camunda.bpm.engine.rest.dto.task.CommentDto; + +public interface ProcessInstanceCommentResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getComments(); + + @DELETE + @Path("/{commentId}") + @Produces(MediaType.APPLICATION_JSON) + void deleteComment(@PathParam("commentId") String commentId); + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + void updateComment(CommentDto comment); + + @DELETE + void deleteComments(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ProcessInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ProcessInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..a4a5394a1b7debecf1caad1c1ae44e778019c1fe --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/ProcessInstanceResource.java @@ -0,0 +1,75 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.runtime.ActivityInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.modification.ProcessInstanceModificationDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +public interface ProcessInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + ProcessInstanceDto getProcessInstance(); + + @DELETE + void deleteProcessInstance(@QueryParam("skipCustomListeners") @DefaultValue("false") boolean skipCustomListeners, + @QueryParam("skipIoMappings") @DefaultValue("false") boolean skipIoMappings, + @QueryParam("skipSubprocesses") @DefaultValue("false") boolean skipSubprocesses, + @QueryParam("failIfNotExists") @DefaultValue("true") boolean failIfNotExists); + + @Path("/variables") + VariableResource getVariablesResource(); + + @GET + @Path("/activity-instances") + @Produces(MediaType.APPLICATION_JSON) + ActivityInstanceDto getActivityInstanceTree(); + + @PUT + @Path("/suspended") + @Consumes(MediaType.APPLICATION_JSON) + void updateSuspensionState(SuspensionStateDto dto); + + @POST + @Path("/modification") + @Consumes(MediaType.APPLICATION_JSON) + void modifyProcessInstance(ProcessInstanceModificationDto dto); + + @POST + @Path("/modification-async") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + BatchDto modifyProcessInstanceAsync(ProcessInstanceModificationDto dto); + + @Path("/comment") + ProcessInstanceCommentResource getProcessInstanceCommentResource(); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/VariableInstanceResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/VariableInstanceResource.java new file mode 100644 index 0000000000000000000000000000000000000000..2c45c31ea29cd0d4f58c56a2bc5a6f38277df800 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/VariableInstanceResource.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime; + +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.runtime.VariableInstanceDto; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +/** + * + * @author Daniel Meyer + * @author Ronny Bräunlich + */ +public interface VariableInstanceResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + public VariableInstanceDto getResource( + @QueryParam(VariableResource.DESERIALIZE_VALUE_QUERY_PARAM) @DefaultValue("true") boolean deserializeObjectValue); + + + @GET + @Path("/data") + public Response getResourceBinary(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseExecutionResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseExecutionResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..f0ea9f59b5a68788a74301168ccb2346ff6b1ba5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseExecutionResourceImpl.java @@ -0,0 +1,258 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotAllowedException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionTriggerDto; +import org.camunda.bpm.engine.rest.dto.runtime.TriggerVariableValueDto; +import org.camunda.bpm.engine.rest.dto.runtime.VariableNameDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.runtime.CaseExecutionResource; +import org.camunda.bpm.engine.runtime.CaseExecution; +import org.camunda.bpm.engine.runtime.CaseExecutionCommandBuilder; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import javax.ws.rs.core.Response.Status; +import java.util.List; +import java.util.Map; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseExecutionResourceImpl implements CaseExecutionResource { + + protected ProcessEngine engine; + protected String caseExecutionId; + protected ObjectMapper objectMapper; + + public CaseExecutionResourceImpl(ProcessEngine engine, String caseExecutionId, ObjectMapper objectMapper) { + this.engine = engine; + this.caseExecutionId = caseExecutionId; + this.objectMapper = objectMapper; + } + + public CaseExecutionDto getCaseExecution() { + CaseService caseService = engine.getCaseService(); + + CaseExecution execution = caseService + .createCaseExecutionQuery() + .caseExecutionId(caseExecutionId) + .singleResult(); + + if (execution == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Case execution with id " + caseExecutionId + " does not exist."); + } + + CaseExecutionDto result = CaseExecutionDto.fromCaseExecution(execution); + return result; + } + + public void manualStart(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseExecutionId); + + initializeCommand(commandBuilder, triggerDto, "start manually"); + + commandBuilder.manualStart(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("manualStart", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("manualStart", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("manualStart", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("manualStart", Status.INTERNAL_SERVER_ERROR, e); + + } + + } + + public void disable(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseExecutionId); + + initializeCommand(commandBuilder, triggerDto, "disable"); + + commandBuilder.disable(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("disable", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("disable", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("disable", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("disable", Status.INTERNAL_SERVER_ERROR, e); + + } + + } + + public void reenable(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseExecutionId); + + initializeCommand(commandBuilder, triggerDto, "reenable"); + + commandBuilder.reenable(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("reenable", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("reenable", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("reenable", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("reenable", Status.INTERNAL_SERVER_ERROR, e); + + } + } + + public void complete(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseExecutionId); + + initializeCommand(commandBuilder, triggerDto, "complete"); + + commandBuilder.complete(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("complete", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("complete", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("complete", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("complete", Status.INTERNAL_SERVER_ERROR, e); + + } + } + + public void terminate(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseExecutionId); + + initializeCommand(commandBuilder, triggerDto, "terminate"); + + commandBuilder.terminate(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("terminate", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("terminate", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("terminate", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("terminate", Status.INTERNAL_SERVER_ERROR, e); + + } + } + + protected InvalidRequestException createInvalidRequestException(String transition, Status status, ProcessEngineException cause) { + String errorMessage = String.format("Cannot %s case execution %s: %s", transition, caseExecutionId, cause.getMessage()); + return new InvalidRequestException(status, cause, errorMessage); + } + + protected RestException createRestException(String transition, Status status, ProcessEngineException cause) { + String errorMessage = String.format("Cannot %s case execution %s: %s", transition, caseExecutionId, cause.getMessage()); + return new RestException(status, cause, errorMessage); + } + + protected void initializeCommand(CaseExecutionCommandBuilder commandBuilder, CaseExecutionTriggerDto triggerDto, String transition) { + Map variables = triggerDto.getVariables(); + if (variables != null && !variables.isEmpty()) { + initializeCommandWithVariables(commandBuilder, variables, transition); + } + + List deletions = triggerDto.getDeletions(); + if (deletions != null && !deletions.isEmpty()) { + initializeCommandWithDeletions(commandBuilder, deletions, transition); + } + } + + protected void initializeCommandWithVariables(CaseExecutionCommandBuilder commandBuilder, Map variables, String transition) { + for(String variableName : variables.keySet()) { + try { + TriggerVariableValueDto variableValue = variables.get(variableName); + TypedValue typedValue = variableValue.toTypedValue(engine, objectMapper); + + if (variableValue.isLocal()) { + commandBuilder.setVariableLocal(variableName, typedValue); + + } else { + commandBuilder.setVariable(variableName, typedValue); + } + + } catch (RestException e) { + String errorMessage = String.format("Cannot %s case execution %s due to invalid variable %s: %s", transition, caseExecutionId, variableName, e.getMessage()); + throw new RestException(e.getStatus(), e, errorMessage); + + } + } + } + + protected void initializeCommandWithDeletions(CaseExecutionCommandBuilder commandBuilder, List deletions, String transition) { + for (VariableNameDto variableName : deletions) { + if (variableName.isLocal()) { + commandBuilder.removeVariableLocal(variableName.getName()); + } else { + commandBuilder.removeVariable(variableName.getName()); + } + } + } + + public VariableResource getVariablesLocal() { + return new LocalCaseExecutionVariablesResource(engine, caseExecutionId, objectMapper); + } + + public VariableResource getVariables() { + return new CaseExecutionVariablesResource(engine, caseExecutionId, objectMapper); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseExecutionVariablesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseExecutionVariablesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..227a71fd8e0bb576defd2cbcbc9fb49532ba99b0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseExecutionVariablesResource.java @@ -0,0 +1,78 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.sub.impl.AbstractVariablesResource; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import java.util.List; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseExecutionVariablesResource extends AbstractVariablesResource { + + public CaseExecutionVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) { + super(engine, resourceId, objectMapper); + } + + protected VariableMap getVariableEntities(boolean deserializeValues) { + CaseService caseService = engine.getCaseService(); + return caseService.getVariablesTyped(resourceId, deserializeValues); + } + + protected void updateVariableEntities(VariableMap variables, List deletions) { + CaseService caseService = engine.getCaseService(); + caseService + .withCaseExecution(resourceId) + .setVariables(variables) + .removeVariables(deletions) + .execute(); + } + + protected void removeVariableEntity(String variableKey) { + CaseService caseService = engine.getCaseService(); + caseService + .withCaseExecution(resourceId) + .removeVariable(variableKey) + .execute(); + } + + protected String getResourceTypeName() { + return "case execution"; + } + + protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { + CaseService caseService = engine.getCaseService(); + return caseService.getVariableTyped(resourceId, variableKey, deserializeValue); + } + + protected void setVariableEntity(String variableKey, TypedValue variableValue) { + CaseService caseService = engine.getCaseService(); + caseService + .withCaseExecution(resourceId) + .setVariable(variableKey, variableValue) + .execute(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..cf1f20a395ecfd946bdb13a3cc6296f0fb9d7c66 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/CaseInstanceResourceImpl.java @@ -0,0 +1,203 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotAllowedException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.rest.dto.runtime.CaseExecutionTriggerDto; +import org.camunda.bpm.engine.rest.dto.runtime.CaseInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.TriggerVariableValueDto; +import org.camunda.bpm.engine.rest.dto.runtime.VariableNameDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.runtime.CaseInstanceResource; +import org.camunda.bpm.engine.runtime.CaseExecutionCommandBuilder; +import org.camunda.bpm.engine.runtime.CaseInstance; + +import javax.ws.rs.core.Response.Status; +import java.util.List; +import java.util.Map; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseInstanceResourceImpl implements CaseInstanceResource { + + protected ProcessEngine engine; + protected String caseInstanceId; + protected ObjectMapper objectMapper; + + public CaseInstanceResourceImpl(ProcessEngine engine, String caseInstanceId, ObjectMapper objectMapper) { + this.engine = engine; + this.caseInstanceId = caseInstanceId; + this.objectMapper = objectMapper; + } + + public CaseInstanceDto getCaseInstance() { + CaseService caseService = engine.getCaseService(); + + CaseInstance instance = caseService + .createCaseInstanceQuery() + .caseInstanceId(caseInstanceId) + .singleResult(); + + if (instance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Case instance with id " + caseInstanceId + " does not exist."); + } + + CaseInstanceDto result = CaseInstanceDto.fromCaseInstance(instance); + return result; + } + + public void complete(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseInstanceId); + + initializeCommand(commandBuilder, triggerDto, "complete"); + + commandBuilder.complete(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("complete", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("complete", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("complete", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("complete", Status.INTERNAL_SERVER_ERROR, e); + + } + } + + public void close(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseInstanceId); + + initializeCommand(commandBuilder, triggerDto, "close"); + + commandBuilder.close(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("close", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("close", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("close", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("close", Status.INTERNAL_SERVER_ERROR, e); + + } + + } + + public void terminate(CaseExecutionTriggerDto triggerDto) { + try { + CaseService caseService = engine.getCaseService(); + CaseExecutionCommandBuilder commandBuilder = caseService.withCaseExecution(caseInstanceId); + + initializeCommand(commandBuilder, triggerDto, "terminate"); + + commandBuilder.terminate(); + + } catch (NotFoundException e) { + throw createInvalidRequestException("terminate", Status.NOT_FOUND, e); + + } catch (NotValidException e) { + throw createInvalidRequestException("terminate", Status.BAD_REQUEST, e); + + } catch (NotAllowedException e) { + throw createInvalidRequestException("terminate", Status.FORBIDDEN, e); + + } catch (ProcessEngineException e) { + throw createRestException("terminate", Status.INTERNAL_SERVER_ERROR, e); + + } + } + + protected InvalidRequestException createInvalidRequestException(String transition, Status status, ProcessEngineException cause) { + String errorMessage = String.format("Cannot %s case instance %s: %s", transition, caseInstanceId, cause.getMessage()); + return new InvalidRequestException(status, cause, errorMessage); + } + + protected RestException createRestException(String transition, Status status, ProcessEngineException cause) { + String errorMessage = String.format("Cannot %s case instance %s: %s", transition, caseInstanceId, cause.getMessage()); + return new RestException(status, cause, errorMessage); + } + + protected void initializeCommand(CaseExecutionCommandBuilder commandBuilder, CaseExecutionTriggerDto triggerDto, String transition) { + Map variables = triggerDto.getVariables(); + if (variables != null && !variables.isEmpty()) { + initializeCommandWithVariables(commandBuilder, variables, transition); + } + + List deletions = triggerDto.getDeletions(); + if (deletions != null && !deletions.isEmpty()) { + initializeCommandWithDeletions(commandBuilder, deletions, transition); + } + } + + protected void initializeCommandWithVariables(CaseExecutionCommandBuilder commandBuilder, Map variables, String transition) { + for(String variableName : variables.keySet()) { + try { + TriggerVariableValueDto variableValue = variables.get(variableName); + + if (variableValue.isLocal()) { + commandBuilder.setVariableLocal(variableName, variableValue.toTypedValue(engine, objectMapper)); + + } else { + commandBuilder.setVariable(variableName, variableValue.toTypedValue(engine, objectMapper)); + } + + } catch (RestException e) { + String errorMessage = String.format("Cannot %s case instance %s due to invalid variable %s: %s", transition, caseInstanceId, variableName, e.getMessage()); + throw new RestException(e.getStatus(), e, errorMessage); + + } + } + } + + protected void initializeCommandWithDeletions(CaseExecutionCommandBuilder commandBuilder, List deletions, String transition) { + for (VariableNameDto variableName : deletions) { + if (variableName.isLocal()) { + commandBuilder.removeVariableLocal(variableName.getName()); + } else { + commandBuilder.removeVariable(variableName.getName()); + } + } + } + + public VariableResource getVariablesResource() { + return new CaseExecutionVariablesResource(engine, caseInstanceId, objectMapper); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ExecutionResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ExecutionResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..d9ab4059807ce8390ad0c90674f54b1090d6ae3f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ExecutionResourceImpl.java @@ -0,0 +1,108 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.rest.dto.CreateIncidentDto; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionTriggerDto; +import org.camunda.bpm.engine.rest.dto.runtime.IncidentDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.runtime.EventSubscriptionResource; +import org.camunda.bpm.engine.rest.sub.runtime.ExecutionResource; +import org.camunda.bpm.engine.runtime.Execution; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.variable.VariableMap; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ExecutionResourceImpl implements ExecutionResource { + + protected ProcessEngine engine; + protected String executionId; + protected ObjectMapper objectMapper; + + public ExecutionResourceImpl(ProcessEngine engine, String executionId, ObjectMapper objectMapper) { + this.engine = engine; + this.executionId = executionId; + this.objectMapper = objectMapper; + } + + @Override + public ExecutionDto getExecution() { + RuntimeService runtimeService = engine.getRuntimeService(); + Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult(); + + if (execution == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Execution with id " + executionId + " does not exist"); + } + + return ExecutionDto.fromExecution(execution); + } + + @Override + public void signalExecution(ExecutionTriggerDto triggerDto) { + RuntimeService runtimeService = engine.getRuntimeService(); + try { + VariableMap variables = VariableValueDto.toMap(triggerDto.getVariables(), engine, objectMapper); + runtimeService.signal(executionId, variables); + + } catch (RestException e) { + String errorMessage = String.format("Cannot signal execution %s: %s", executionId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } catch (AuthorizationException e) { + throw e; + + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, "Cannot signal execution " + executionId + ": " + e.getMessage()); + + } + } + + @Override + public VariableResource getLocalVariables() { + return new LocalExecutionVariablesResource(engine, executionId, objectMapper); + } + + @Override + public EventSubscriptionResource getMessageEventSubscription(String messageName) { + return new MessageEventSubscriptionResource(engine, executionId, messageName, objectMapper); + } + + @Override + public IncidentDto createIncident(CreateIncidentDto createIncidentDto) { + Incident newIncident = null; + + try { + newIncident = engine.getRuntimeService() + .createIncident(createIncidentDto.getIncidentType(), executionId, createIncidentDto.getConfiguration(), createIncidentDto.getMessage()); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + return IncidentDto.fromIncident(newIncident); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ExecutionVariablesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ExecutionVariablesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..c5b36beec98cef0627c5d8f99152d91a0598b521 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ExecutionVariablesResource.java @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.rest.sub.impl.AbstractVariablesResource; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import java.util.List; + +public class ExecutionVariablesResource extends AbstractVariablesResource { + + private String resourceTypeName; + + public ExecutionVariablesResource(ProcessEngine engine, String resourceId, boolean isProcessInstance, ObjectMapper objectMapper) { + super(engine, resourceId, objectMapper); + if (isProcessInstance) { + resourceTypeName = "process instance"; + } else { + resourceTypeName = "execution"; + } + } + + protected String getResourceTypeName() { + return resourceTypeName; + } + + protected void updateVariableEntities(VariableMap modifications, List deletions) { + RuntimeServiceImpl runtimeService = (RuntimeServiceImpl) engine.getRuntimeService(); + runtimeService.updateVariables(resourceId, modifications, deletions); + } + + protected void removeVariableEntity(String variableKey) { + engine.getRuntimeService().removeVariable(resourceId, variableKey); + } + + protected VariableMap getVariableEntities(boolean deserializeValues) { + return engine.getRuntimeService().getVariablesTyped(resourceId, deserializeValues); + } + + protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { + return engine.getRuntimeService().getVariableTyped(resourceId, variableKey, deserializeValue); + } + + protected void setVariableEntity(String variableKey, TypedValue variableValue) { + engine.getRuntimeService().setVariable(resourceId, variableKey, variableValue); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/FilterResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/FilterResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..eed3489b81df71de76e68f133e1c84fed45d4935 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/FilterResourceImpl.java @@ -0,0 +1,572 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.EntityTypes; +import org.camunda.bpm.engine.FilterService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.impl.VariableInstanceQueryImpl; +import org.camunda.bpm.engine.impl.persistence.entity.VariableInstanceEntity; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.FilterRestService; +import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; +import org.camunda.bpm.engine.rest.dto.CountResultDto; +import org.camunda.bpm.engine.rest.dto.ResourceOptionsDto; +import org.camunda.bpm.engine.rest.dto.runtime.FilterDto; +import org.camunda.bpm.engine.rest.dto.task.TaskDto; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.hal.EmptyHalCollection; +import org.camunda.bpm.engine.rest.hal.EmptyHalResource; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.hal.HalCollectionResource; +import org.camunda.bpm.engine.rest.hal.HalResource; +import org.camunda.bpm.engine.rest.hal.HalVariableValue; +import org.camunda.bpm.engine.rest.hal.task.HalTask; +import org.camunda.bpm.engine.rest.hal.task.HalTaskList; +import org.camunda.bpm.engine.rest.impl.AbstractAuthorizedRestResource; +import org.camunda.bpm.engine.rest.sub.runtime.FilterResource; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Task; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import javax.ws.rs.core.Variant; +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.FILTER; + +/** + * @author Sebastian Menski + */ +public class FilterResourceImpl extends AbstractAuthorizedRestResource implements FilterResource { + + public static final Pattern EMPTY_JSON_BODY = Pattern.compile("\\s*\\{\\s*\\}\\s*"); + public static final String PROPERTIES_VARIABLES_KEY = "variables"; + public static final String PROPERTIES_VARIABLES_NAME_KEY = "name"; + public static final List VARIANTS = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, Hal.APPLICATION_HAL_JSON_TYPE).add().build(); + + protected String relativeRootResourcePath; + protected FilterService filterService; + protected Filter dbFilter; + + public FilterResourceImpl(String processEngineName, ObjectMapper objectMapper, String filterId, String relativeRootResourcePath) { + super(processEngineName, FILTER, filterId, objectMapper); + this.relativeRootResourcePath = relativeRootResourcePath; + filterService = getProcessEngine().getFilterService(); + } + + public FilterDto getFilter(Boolean itemCount) { + Filter filter = getDbFilter(); + FilterDto dto = FilterDto.fromFilter(filter); + if (itemCount != null && itemCount) { + dto.setItemCount(filterService.count(filter.getId())); + } + return dto; + } + + protected Filter getDbFilter() { + if (dbFilter == null) { + dbFilter = filterService.getFilter(resourceId); + + if (dbFilter == null) { + throw filterNotFound(null); + } + } + return dbFilter; + } + + public void deleteFilter() { + try { + filterService.deleteFilter(resourceId); + } + catch (NullValueException e) { + throw filterNotFound(e); + } + } + + public void updateFilter(FilterDto filterDto) { + Filter filter = getDbFilter(); + + try { + filterDto.updateFilter(filter, getProcessEngine()); + } + catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Unable to update filter with invalid content"); + } + + filterService.saveFilter(filter); + } + + public Object executeSingleResult(Request request) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { + return executeJsonSingleResult(); + } + else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { + return executeHalSingleResult(); + } + } + throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + public Object executeJsonSingleResult() { + return queryJsonSingleResult(null); + } + + public Object querySingleResult(Request request, String extendingQuery) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { + return queryJsonSingleResult(extendingQuery); + } + else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { + return queryHalSingleResult(extendingQuery); + } + } + throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + public Object queryJsonSingleResult(String extendingQuery) { + Object entity = executeFilterSingleResult(extendingQuery); + + if (entity != null) { + return convertToDto(entity); + } + else { + return null; + } + } + + public HalResource executeHalSingleResult() { + return queryHalSingleResult(null); + } + + public HalResource queryHalSingleResult(String extendingQuery) { + Object entity = executeFilterSingleResult(extendingQuery); + + if (entity != null) { + return convertToHalResource(entity); + } + else { + return EmptyHalResource.INSTANCE; + } + } + + protected Object executeFilterSingleResult(String extendingQuery) { + try { + return filterService.singleResult(resourceId, convertQuery(extendingQuery)); + } + catch (NullValueException e) { + throw filterNotFound(e); + } + catch (NotValidException e) { + throw invalidQuery(e); + } + catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Filter does not returns a valid single result"); + } + } + + public Object executeList(Request request, Integer firstResult, Integer maxResults) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { + return executeJsonList(firstResult, maxResults); + } + else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { + return executeHalList(firstResult, maxResults); + } + } + throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + public List executeJsonList(Integer firstResult, Integer maxResults) { + return queryJsonList(null, firstResult, maxResults); + } + + public Object queryList(Request request, String extendingQuery, Integer firstResult, Integer maxResults) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { + return queryJsonList(extendingQuery, firstResult ,maxResults); + } + else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { + return queryHalList(extendingQuery, firstResult, maxResults); + } + } + throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + public List queryJsonList(String extendingQuery, Integer firstResult, Integer maxResults) { + List entities = executeFilterList(extendingQuery, firstResult, maxResults); + + if (entities != null && !entities.isEmpty()) { + return convertToDtoList(entities); + } + else { + return Collections.emptyList(); + } + } + + public HalResource executeHalList(Integer firstResult, Integer maxResults) { + return queryHalList(null, firstResult, maxResults); + } + + public HalResource queryHalList(String extendingQuery, Integer firstResult, Integer maxResults) { + List entities = executeFilterList(extendingQuery, firstResult, maxResults); + long count = executeFilterCount(extendingQuery); + + if (entities != null && !entities.isEmpty()) { + return convertToHalCollection(entities, count); + } + else { + return new EmptyHalCollection(count); + } + } + + protected List executeFilterList(String extendingQueryString, Integer firstResult, Integer maxResults) { + Query extendingQuery = convertQuery(extendingQueryString); + try { + if (firstResult != null || maxResults != null) { + if (firstResult == null) { + firstResult = 0; + } + if (maxResults == null) { + maxResults = Integer.MAX_VALUE; + } + return filterService.listPage(resourceId, extendingQuery, firstResult, maxResults); + } else { + return filterService.list(resourceId, extendingQuery); + } + } + catch (NullValueException e) { + throw filterNotFound(e); + } + catch (NotValidException e) { + throw invalidQuery(e); + } + } + + public CountResultDto executeCount() { + return queryCount(null); + } + + public CountResultDto queryCount(String extendingQuery) { + return new CountResultDto(executeFilterCount(extendingQuery)); + } + + protected long executeFilterCount(String extendingQuery) { + try { + return filterService.count(resourceId, convertQuery(extendingQuery)); + } + catch (NullValueException e) { + throw filterNotFound(e); + } + catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Filter cannot be extended by an invalid query"); + } + } + + public ResourceOptionsDto availableOperations(UriInfo context) { + + ResourceOptionsDto dto = new ResourceOptionsDto(); + + UriBuilder baseUriBuilder = context.getBaseUriBuilder() + .path(relativeRootResourcePath) + .path(FilterRestService.PATH) + .path(resourceId); + + URI baseUri = baseUriBuilder.build(); + + if (isAuthorized(READ)) { + dto.addReflexiveLink(baseUri, HttpMethod.GET, "self"); + + URI singleResultUri = baseUriBuilder.clone().path("/singleResult").build(); + dto.addReflexiveLink(singleResultUri, HttpMethod.GET, "singleResult"); + dto.addReflexiveLink(singleResultUri, HttpMethod.POST, "singleResult"); + + URI listUri = baseUriBuilder.clone().path("/list").build(); + dto.addReflexiveLink(listUri, HttpMethod.GET, "list"); + dto.addReflexiveLink(listUri, HttpMethod.POST, "list"); + + URI countUri = baseUriBuilder.clone().path("/count").build(); + dto.addReflexiveLink(countUri, HttpMethod.GET, "count"); + dto.addReflexiveLink(countUri, HttpMethod.POST, "count"); + } + + if (isAuthorized(DELETE)) { + dto.addReflexiveLink(baseUri, HttpMethod.DELETE, "delete"); + } + + if (isAuthorized(UPDATE)) { + dto.addReflexiveLink(baseUri, HttpMethod.PUT, "update"); + } + + return dto; + } + + protected Query convertQuery(String queryString) { + if (isEmptyJson(queryString)) { + return null; + } + else { + String resourceType = getDbFilter().getResourceType(); + AbstractQueryDto queryDto = getQueryDtoForQuery(queryString, resourceType); + queryDto.setObjectMapper(getObjectMapper()); + return queryDto.toQuery(getProcessEngine()); + } + } + + protected Object convertToDto(Object entity) { + if (isEntityOfClass(entity, Task.class)) { + return TaskDto.fromEntity((Task) entity); + } + else { + throw unsupportedEntityClass(entity); + } + } + + protected List convertToDtoList(List entities) { + List dtoList = new ArrayList<>(); + for (Object entity : entities) { + dtoList.add(convertToDto(entity)); + } + return dtoList; + } + + protected HalResource convertToHalResource(Object entity) { + if (isEntityOfClass(entity, Task.class)) { + return convertToHalTask((Task) entity); + } + else { + throw unsupportedEntityClass(entity); + } + } + + protected HalTask convertToHalTask(Task task) { + HalTask halTask = HalTask.generate(task, getProcessEngine()); + Map> variableInstances = getVariableInstancesForTasks(halTask); + if (variableInstances != null) { + embedVariableValuesInHalTask(halTask, variableInstances); + } + return halTask; + } + + @SuppressWarnings("unchecked") + protected HalCollectionResource convertToHalCollection(List entities, long count) { + if (isEntityOfClass(entities.get(0), Task.class)) { + return convertToHalTaskList((List) entities, count); + } else { + throw unsupportedEntityClass(entities.get(0)); + } + } + + @SuppressWarnings("unchecked") + protected HalTaskList convertToHalTaskList(List tasks, long count) { + HalTaskList halTasks = HalTaskList.generate(tasks, count, getProcessEngine()); + Map> variableInstances = getVariableInstancesForTasks(halTasks); + if (variableInstances != null) { + for (HalTask halTask : (List) halTasks.getEmbedded("task")) { + embedVariableValuesInHalTask(halTask, variableInstances); + } + } + return halTasks; + } + + protected void embedVariableValuesInHalTask( HalTask halTask, Map> variableInstances) { + List> variableValues = getVariableValuesForTask(halTask, variableInstances); + halTask.addEmbedded("variable", variableValues); + } + + protected AbstractQueryDto getQueryDtoForQuery(String queryString, String resourceType) { + try { + if (EntityTypes.TASK.equals(resourceType)) { + return getObjectMapper().readValue(queryString, TaskQueryDto.class); + } else { + throw new InvalidRequestException(Status.BAD_REQUEST, "Queries for resource type '" + resourceType + "' are currently not supported by filters."); + } + } catch (IOException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Invalid query for resource type '" + resourceType + "'"); + } + } + + protected List> getVariableValuesForTask(HalTask halTask, Map> variableInstances) { + // converted variables values + List> variableValues = new ArrayList<>(); + + // variable scope ids to check, ordered by visibility + LinkedHashSet variableScopeIds = getVariableScopeIds(halTask); + + // names of already converted variables + Set knownVariableNames = new HashSet<>(); + + for (String variableScopeId : variableScopeIds) { + if (variableInstances.containsKey(variableScopeId)) { + for (VariableInstance variableInstance : variableInstances.get(variableScopeId)) { + if (!knownVariableNames.contains(variableInstance.getName())) { + variableValues.add(HalVariableValue.generateVariableValue(variableInstance, variableScopeId)); + knownVariableNames.add(variableInstance.getName()); + } + } + } + } + + return variableValues; + } + + @SuppressWarnings("unchecked") + protected Map> getVariableInstancesForTasks(HalTaskList halTaskList) { + List halTasks = (List) halTaskList.getEmbedded("task"); + return getVariableInstancesForTasks(halTasks.toArray(new HalTask[halTasks.size()])); + } + + protected Map> getVariableInstancesForTasks(HalTask... halTasks) { + if (halTasks != null && halTasks.length > 0) { + List variableNames = getFilterVariableNames(); + if (variableNames != null && !variableNames.isEmpty()) { + LinkedHashSet variableScopeIds = getVariableScopeIds(halTasks); + return getSortedVariableInstances(variableNames, variableScopeIds); + } + } + return null; + } + + @SuppressWarnings("unchecked") + protected List getFilterVariableNames() { + Map properties = getDbFilter().getProperties(); + if (properties != null) { + try { + List> variables = (List>) properties.get(PROPERTIES_VARIABLES_KEY); + return collectVariableNames(variables); + } + catch (Exception e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e, "Filter property '" + PROPERTIES_VARIABLES_KEY + "' has to be a list of variable definitions with a '" + PROPERTIES_VARIABLES_NAME_KEY + "' property"); + } + } + else { + return null; + } + } + + private List collectVariableNames(List> variables) { + if (variables != null && !variables.isEmpty()) { + List variableNames = new ArrayList<>(); + for (Map variable : variables) { + variableNames.add((String) variable.get(PROPERTIES_VARIABLES_NAME_KEY)); + } + return variableNames; + } + else { + return null; + } + } + + protected LinkedHashSet getVariableScopeIds(HalTask... halTasks) { + // collect scope ids + // the ordering is important because it specifies which variables are visible from a single task + LinkedHashSet variableScopeIds = new LinkedHashSet<>(); + if (halTasks != null && halTasks.length > 0) { + for (HalTask halTask : halTasks) { + variableScopeIds.add(halTask.getId()); + variableScopeIds.add(halTask.getExecutionId()); + variableScopeIds.add(halTask.getProcessInstanceId()); + variableScopeIds.add(halTask.getCaseExecutionId()); + variableScopeIds.add(halTask.getCaseInstanceId()); + } + } + + // remove null from set which was probably added due an unset id + variableScopeIds.remove(null); + + return variableScopeIds; + } + + protected Map> getSortedVariableInstances(Collection variableNames, Collection variableScopeIds) { + List variableInstances = queryVariablesInstancesByVariableScopeIds(variableNames, variableScopeIds); + Map> sortedVariableInstances = new HashMap<>(); + for (VariableInstance variableInstance : variableInstances) { + String variableScopeId = ((VariableInstanceEntity) variableInstance).getVariableScopeId(); + if (!sortedVariableInstances.containsKey(variableScopeId)) { + sortedVariableInstances.put(variableScopeId, new ArrayList()); + } + sortedVariableInstances.get(variableScopeId).add(variableInstance); + } + return sortedVariableInstances; + } + + protected List queryVariablesInstancesByVariableScopeIds(Collection variableNames, Collection variableScopeIds) { + + VariableInstanceQueryImpl query = (VariableInstanceQueryImpl) getProcessEngine().getRuntimeService() + .createVariableInstanceQuery() + .disableBinaryFetching() + .disableCustomObjectDeserialization() + .variableNameIn(variableNames.toArray(new String[0])) + .variableScopeIdIn(variableScopeIds.toArray(new String[0])); + + // the number of results is capped at: + // #tasks * #variableNames * 5 (we have five variable scopes per task) + // this value may exceed the configured query pagination limit, so we make an unbounded query. + // As #tasks is bounded by the pagination limit, it will never load an unbounded number of variables. + return query.unlimitedList(); + + } + + protected boolean isEntityOfClass(Object entity, Class entityClass) { + return entityClass.isAssignableFrom(entity.getClass()); + } + + protected boolean isEmptyJson(String jsonString) { + return jsonString == null || jsonString.trim().isEmpty() || EMPTY_JSON_BODY.matcher(jsonString).matches(); + } + + protected InvalidRequestException filterNotFound(Exception cause) { + return new InvalidRequestException(Status.NOT_FOUND, cause, "Filter with id '" + resourceId + "' does not exist."); + } + + protected InvalidRequestException invalidQuery(Exception cause) { + return new InvalidRequestException(Status.BAD_REQUEST, cause, "Filter cannot be extended by an invalid query"); + } + + protected InvalidRequestException unsupportedEntityClass(Object entity) { + return new InvalidRequestException(Status.BAD_REQUEST, "Entities of class '" + entity.getClass().getCanonicalName() + "' are currently not supported by filters."); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/JobResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/JobResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..5ddd8b85591c6ef1a681ad054cc1cc2ba9873fd7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/JobResourceImpl.java @@ -0,0 +1,166 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.management.SetJobRetriesBuilder; +import org.camunda.bpm.engine.rest.dto.runtime.JobDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobDuedateDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.PriorityDto; +import org.camunda.bpm.engine.rest.dto.runtime.RetriesDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.runtime.JobResource; +import org.camunda.bpm.engine.runtime.Job; + +public class JobResourceImpl implements JobResource { + + private ProcessEngine engine; + private String jobId; + + public JobResourceImpl(ProcessEngine engine, String jobId) { + this.engine = engine; + this.jobId = jobId; + } + + @Override + public JobDto getJob() { + ManagementService managementService = engine.getManagementService(); + Job job = managementService.createJobQuery().jobId(jobId).singleResult(); + + if (job == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Job with id " + jobId + " does not exist"); + } + + return JobDto.fromJob(job); + } + + @Override + public String getStacktrace() { + try { + ManagementService managementService = engine.getManagementService(); + String stacktrace = managementService.getJobExceptionStacktrace(jobId); + return stacktrace; + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } + } + + @Override + public void setJobRetries(RetriesDto dto) { + try { + ManagementService managementService = engine.getManagementService(); + SetJobRetriesBuilder builder = managementService + .setJobRetries(dto.getRetries()) + .jobId(jobId); + if (dto.isDueDateSet()) { + builder.dueDate(dto.getDueDate()); + } + builder.execute(); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + } + + @Override + public void executeJob() { + try { + ManagementService managementService = engine.getManagementService(); + managementService.executeJob(this.jobId); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } catch (RuntimeException r) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, r.getMessage()); + } + } + + @Override + public void setJobDuedate(JobDuedateDto dto) { + try { + ManagementService managementService = engine.getManagementService(); + managementService.setJobDuedate(jobId, dto.getDuedate(), dto.isCascade()); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + } + + @Override + public void recalculateDuedate(boolean creationDateBased) { + try { + ManagementService managementService = engine.getManagementService(); + managementService.recalculateJobDuedate(jobId, creationDateBased); + } catch (AuthorizationException e) { + throw e; + } catch(NotFoundException e) {// rewrite status code from bad request (400) to not found (404) + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + } + + public void updateSuspensionState(JobSuspensionStateDto dto) { + dto.setJobId(jobId); + dto.updateSuspensionState(engine); + } + + @Override + public void setJobPriority(PriorityDto dto) { + if (dto.getPriority() == null) { + throw new RestException(Status.BAD_REQUEST, "Priority for job '" + jobId + "' cannot be null."); + } + + try { + ManagementService managementService = engine.getManagementService(); + managementService.setJobPriority(jobId, dto.getPriority()); + } catch (AuthorizationException e) { + throw e; + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + } + + public void deleteJob() { + try { + engine.getManagementService() + .deleteJob(jobId); + } catch (AuthorizationException e) { + throw e; + } catch (NullValueException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/LocalCaseExecutionVariablesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/LocalCaseExecutionVariablesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..2f332bacf9b3a0e5fd3dae25513a6cc29411537c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/LocalCaseExecutionVariablesResource.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.sub.impl.AbstractVariablesResource; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import java.util.List; + +/** + * + * @author Roman Smirnov + * + */ +public class LocalCaseExecutionVariablesResource extends AbstractVariablesResource { + + public LocalCaseExecutionVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) { + super(engine, resourceId, objectMapper); + } + + protected VariableMap getVariableEntities(boolean deserializeValues) { + CaseService caseService = engine.getCaseService(); + return caseService.getVariablesLocalTyped(resourceId, deserializeValues); + } + + protected void updateVariableEntities(VariableMap variables, List deletions) { + CaseService caseService = engine.getCaseService(); + caseService + .withCaseExecution(resourceId) + .setVariablesLocal(variables) + .removeVariablesLocal(deletions) + .execute(); + } + + protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { + CaseService caseService = engine.getCaseService(); + return caseService.getVariableLocalTyped(resourceId, variableKey, deserializeValue); + } + + protected void setVariableEntity(String variableKey, TypedValue variableValue) { + CaseService caseService = engine.getCaseService(); + caseService.withCaseExecution(resourceId) + .setVariableLocal(variableKey, variableValue) + .execute(); + } + + protected void removeVariableEntity(String variableKey) { + CaseService caseService = engine.getCaseService(); + caseService + .withCaseExecution(resourceId) + .removeVariableLocal(variableKey) + .execute(); + } + + protected String getResourceTypeName() { + return "case execution"; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/LocalExecutionVariablesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/LocalExecutionVariablesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..98c494d5b436ea1008b157dff873622044bdc42f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/LocalExecutionVariablesResource.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.rest.sub.impl.AbstractVariablesResource; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import java.util.List; + +/** + * + * @author Daniel Meyer + */ +public class LocalExecutionVariablesResource extends AbstractVariablesResource { + + public LocalExecutionVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) { + super(engine, resourceId, objectMapper); + } + + protected String getResourceTypeName() { + return "execution"; + } + + protected void updateVariableEntities(VariableMap modifications, List deletions) { + RuntimeServiceImpl runtimeService = (RuntimeServiceImpl) engine.getRuntimeService(); + runtimeService.updateVariablesLocal(resourceId, modifications, deletions); + } + + protected void removeVariableEntity(String variableKey) { + engine.getRuntimeService().removeVariableLocal(resourceId, variableKey); + } + + protected VariableMap getVariableEntities(boolean deserializeValues) { + return engine.getRuntimeService().getVariablesLocalTyped(resourceId, deserializeValues); + } + + protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { + return engine.getRuntimeService().getVariableLocalTyped(resourceId, variableKey, deserializeValue); + } + + protected void setVariableEntity(String variableKey, TypedValue variableValue) { + engine.getRuntimeService().setVariableLocal(resourceId, variableKey, variableValue); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/MessageEventSubscriptionResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/MessageEventSubscriptionResource.java new file mode 100644 index 0000000000000000000000000000000000000000..be06d5e766f40541f6b12fd5d4abd1c3f175db52 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/MessageEventSubscriptionResource.java @@ -0,0 +1,90 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.runtime.EventSubscriptionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ExecutionTriggerDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.sub.runtime.EventSubscriptionResource; +import org.camunda.bpm.engine.runtime.EventSubscription; +import org.camunda.bpm.engine.variable.VariableMap; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class MessageEventSubscriptionResource implements EventSubscriptionResource { + + protected static final String MESSAGE_EVENT_TYPE = "message"; + + protected ProcessEngine engine; + protected String executionId; + protected String messageName; + + protected ObjectMapper objectMapper; + + public MessageEventSubscriptionResource(ProcessEngine engine, String executionId, String messageName, ObjectMapper objectMapper) { + this.engine = engine; + this.executionId = executionId; + this.messageName = messageName; + this.objectMapper = objectMapper; + } + + @Override + public EventSubscriptionDto getEventSubscription() { + RuntimeService runtimeService = engine.getRuntimeService(); + EventSubscription eventSubscription = runtimeService.createEventSubscriptionQuery() + .executionId(executionId).eventName(messageName).eventType(MESSAGE_EVENT_TYPE).singleResult(); + + if (eventSubscription == null) { + String errorMessage = String.format("Message event subscription for execution %s named %s does not exist", executionId, messageName); + throw new InvalidRequestException(Status.NOT_FOUND, errorMessage); + } + + return EventSubscriptionDto.fromEventSubscription(eventSubscription); + } + + @Override + public void triggerEvent(ExecutionTriggerDto triggerDto) { + RuntimeService runtimeService = engine.getRuntimeService(); + + + try { + VariableMap variables = VariableValueDto.toMap(triggerDto.getVariables(), engine, objectMapper); + runtimeService.messageEventReceived(messageName, executionId, variables); + + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, String.format("Cannot trigger message %s for execution %s: %s", + messageName, executionId, e.getMessage())); + + } catch (RestException e) { + String errorMessage = String.format("Cannot trigger message %s for execution %s: %s", messageName, executionId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ProcessInstanceCommentResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ProcessInstanceCommentResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..fe175b84fff9f9c0e160789d77bd00be9259a8c7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ProcessInstanceCommentResourceImpl.java @@ -0,0 +1,144 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.dto.task.CommentDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.runtime.ProcessInstanceCommentResource; +import org.camunda.bpm.engine.task.Comment; + +public class ProcessInstanceCommentResourceImpl implements ProcessInstanceCommentResource { + + private ProcessEngine engine; + private String processInstanceId; + + public ProcessInstanceCommentResourceImpl(ProcessEngine engine, String processInstanceId) { + this.engine = engine; + this.processInstanceId = processInstanceId; + } + + @Override + public List getComments() { + if (!isHistoryEnabled()) { + return Collections.emptyList(); + } + + ensureProcessInstanceExists(Status.NOT_FOUND); + + List processInstanceComments = engine.getTaskService().getProcessInstanceComments(processInstanceId); + + List comments = new ArrayList(); + for (Comment comment : processInstanceComments) { + comments.add(CommentDto.fromComment(comment)); + } + + return comments; + } + + /** + * Deletes a comment by a given commentId + */ + @Override + public void deleteComment(String commentId) { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureProcessInstanceExists(Status.NOT_FOUND); + + TaskService taskService = engine.getTaskService(); + try { + taskService.deleteProcessInstanceComment(processInstanceId, commentId); + } catch (AuthorizationException e) { + throw e; + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + /** + * Updates message for a given processInstanceId and commentId + */ + @Override + public void updateComment(CommentDto comment) { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureProcessInstanceExists(Status.NOT_FOUND); + + TaskService taskService = engine.getTaskService(); + try { + taskService.updateProcessInstanceComment(processInstanceId, comment.getId(), comment.getMessage()); + } catch (AuthorizationException e) { + throw e; + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + /** + * Deletes all comments by a given processInstanceId + */ + @Override + public void deleteComments() { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureProcessInstanceExists(Status.NOT_FOUND); + TaskService taskService = engine.getTaskService(); + + try { + taskService.deleteProcessInstanceComments(processInstanceId); + } catch (AuthorizationException e) { + throw e; + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + private void ensureHistoryEnabled(Status status) { + if (!isHistoryEnabled()) { + throw new InvalidRequestException(status, "History is not enabled"); + } + } + + private boolean isHistoryEnabled() { + IdentityService identityService = engine.getIdentityService(); + Authentication currentAuthentication = identityService.getCurrentAuthentication(); + try { + identityService.clearAuthentication(); + int historyLevel = engine.getManagementService().getHistoryLevel(); + return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE; + } finally { + identityService.setAuthentication(currentAuthentication); + } + } + + private void ensureProcessInstanceExists(Status status) { + HistoricProcessInstance historicProcessInstance = engine.getHistoryService().createHistoricProcessInstanceQuery() + .processInstanceId(processInstanceId).singleResult(); + if (historicProcessInstance == null) { + throw new InvalidRequestException(status, "No process instance found for id " + processInstanceId); + } + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ProcessInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ProcessInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..642af2693368af15408761083551da297e3df28c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/ProcessInstanceResourceImpl.java @@ -0,0 +1,164 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.rest.dto.SuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.runtime.ActivityInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.runtime.modification.ProcessInstanceModificationDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.runtime.ProcessInstanceCommentResource; +import org.camunda.bpm.engine.rest.sub.runtime.ProcessInstanceResource; +import org.camunda.bpm.engine.runtime.ActivityInstance; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationBuilder; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class ProcessInstanceResourceImpl implements ProcessInstanceResource { + + protected ProcessEngine engine; + protected String processInstanceId; + protected ObjectMapper objectMapper; + + public ProcessInstanceResourceImpl(ProcessEngine engine, String processInstanceId, ObjectMapper objectMapper) { + this.engine = engine; + this.processInstanceId = processInstanceId; + this.objectMapper = objectMapper; + } + + @Override + public ProcessInstanceDto getProcessInstance() { + RuntimeService runtimeService = engine.getRuntimeService(); + ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult(); + + if (instance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Process instance with id " + processInstanceId + " does not exist"); + } + + ProcessInstanceDto result = ProcessInstanceDto.fromProcessInstance(instance); + return result; + } + + @Override + public void deleteProcessInstance(boolean skipCustomListeners, boolean skipIoMappings, boolean skipSubprocesses, boolean failIfNotExists) { + RuntimeService runtimeService = engine.getRuntimeService(); + try { + if (failIfNotExists) { + runtimeService.deleteProcessInstance(processInstanceId, null, skipCustomListeners, true, skipIoMappings, skipSubprocesses); + } else { + runtimeService.deleteProcessInstanceIfExists(processInstanceId, null, skipCustomListeners, true, skipIoMappings, skipSubprocesses); + } + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e, e.getMessage()); + } + + } + + @Override + public VariableResource getVariablesResource() { + return new ExecutionVariablesResource(engine, processInstanceId, true, objectMapper); + } + + @Override + public ActivityInstanceDto getActivityInstanceTree() { + RuntimeService runtimeService = engine.getRuntimeService(); + + ActivityInstance activityInstance = null; + + try { + activityInstance = runtimeService.getActivityInstance(processInstanceId); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.INTERNAL_SERVER_ERROR, e, e.getMessage()); + } + + if (activityInstance == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Process instance with id " + processInstanceId + " does not exist"); + } + + ActivityInstanceDto result = ActivityInstanceDto.fromActivityInstance(activityInstance); + return result; + } + + @Override + public void updateSuspensionState(SuspensionStateDto dto) { + dto.updateSuspensionState(engine, processInstanceId); + } + + @Override + public void modifyProcessInstance(ProcessInstanceModificationDto dto) { + if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) { + ProcessInstanceModificationBuilder modificationBuilder = + engine.getRuntimeService().createProcessInstanceModification(processInstanceId); + + dto.applyTo(modificationBuilder, engine, objectMapper); + + if (dto.getAnnotation() != null) { + modificationBuilder.setAnnotation(dto.getAnnotation()); + } + + modificationBuilder.cancellationSourceExternal(true); + + modificationBuilder.execute(dto.isSkipCustomListeners(), dto.isSkipIoMappings()); + } + } + + @Override + public BatchDto modifyProcessInstanceAsync(ProcessInstanceModificationDto dto) { + Batch batch = null; + if (dto.getInstructions() != null && !dto.getInstructions().isEmpty()) { + ProcessInstanceModificationBuilder modificationBuilder = + engine.getRuntimeService().createProcessInstanceModification(processInstanceId); + + dto.applyTo(modificationBuilder, engine, objectMapper); + + if (dto.getAnnotation() != null) { + modificationBuilder.setAnnotation(dto.getAnnotation()); + } + + modificationBuilder.cancellationSourceExternal(true); + + try { + batch = modificationBuilder.executeAsync(dto.isSkipCustomListeners(), dto.isSkipIoMappings()); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + return BatchDto.fromBatch(batch); + } + + throw new InvalidRequestException(Status.BAD_REQUEST, "The provided instuctions are invalid."); + } + + @Override + public ProcessInstanceCommentResource getProcessInstanceCommentResource() { + return new ProcessInstanceCommentResourceImpl(engine, processInstanceId); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/VariableInstanceResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/VariableInstanceResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..1fb2d20599283b4843ac67f0a5ab27761e4a9e89 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/runtime/impl/VariableInstanceResourceImpl.java @@ -0,0 +1,77 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.runtime.impl; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.dto.runtime.VariableInstanceDto; +import org.camunda.bpm.engine.rest.sub.AbstractResourceProvider; +import org.camunda.bpm.engine.rest.sub.runtime.VariableInstanceResource; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.runtime.VariableInstanceQuery; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Daniel Meyer + * @author Ronny Bräunlich + * + */ +public class VariableInstanceResourceImpl extends AbstractResourceProvider implements + VariableInstanceResource { + + public VariableInstanceResourceImpl(String variableId, ProcessEngine engine) { + super(variableId, engine); + } + + protected VariableInstanceQuery baseQuery() { + return getEngine().getRuntimeService().createVariableInstanceQuery().variableId(getId()); + } + + @Override + protected Query baseQueryForBinaryVariable() { + return baseQuery().disableCustomObjectDeserialization(); + } + + @Override + protected Query baseQueryForVariable(boolean deserializeObjectValue) { + VariableInstanceQuery baseQuery = baseQuery(); + + // do not fetch byte arrays + baseQuery.disableBinaryFetching(); + + if (!deserializeObjectValue) { + baseQuery.disableCustomObjectDeserialization(); + } + return baseQuery; + } + + @Override + protected TypedValue transformQueryResultIntoTypedValue(VariableInstance queryResult) { + return queryResult.getTypedValue(); + } + + @Override + protected VariableInstanceDto transformToDto(VariableInstance queryResult) { + return VariableInstanceDto.fromVariableInstance(queryResult); + } + + @Override + protected String getResourceNameForErrorMessage() { + return "Variable instance"; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskAttachmentResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskAttachmentResource.java new file mode 100644 index 0000000000000000000000000000000000000000..a474a9153a8632758b5153b264718800bec8008e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskAttachmentResource.java @@ -0,0 +1,56 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task; + +import org.camunda.bpm.engine.rest.dto.task.AttachmentDto; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData; + +import javax.ws.rs.*; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import java.io.InputStream; +import java.util.List; + +public interface TaskAttachmentResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getAttachments(); + + @GET + @Path("/{attachmentId}") + @Produces(MediaType.APPLICATION_JSON) + AttachmentDto getAttachment(@PathParam("attachmentId") String attachmentId); + + @GET + @Path("/{attachmentId}/data") + @Produces(MediaType.APPLICATION_OCTET_STREAM) + InputStream getAttachmentData(@PathParam("attachmentId") String attachmentId); + + @DELETE + @Path("/{attachmentId}") + @Produces(MediaType.APPLICATION_JSON) + void deleteAttachment(@PathParam("attachmentId") String attachmentId); + + @POST + @Path("/create") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.APPLICATION_JSON) + AttachmentDto addAttachment(@Context UriInfo uriInfo, MultipartFormData multipartFormData); + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskCommentResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskCommentResource.java new file mode 100644 index 0000000000000000000000000000000000000000..261c6ef077ddff6648bcdd3925d1a99c99cde013 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskCommentResource.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task; + +import java.util.List; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.rest.dto.task.CommentDto; + +public interface TaskCommentResource { + + @GET + @Produces(MediaType.APPLICATION_JSON) + List getComments(); + + @GET + @Path("/{commentId}") + @Produces(MediaType.APPLICATION_JSON) + CommentDto getComment(@PathParam("commentId") String commentId); + + @POST + @Path("/create") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + CommentDto createComment(@Context UriInfo uriInfo, CommentDto comment); + + @DELETE + @Path("/{commentId}") + @Produces(MediaType.APPLICATION_JSON) + void deleteComment(@PathParam("commentId") String commentId); + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + void updateComment(CommentDto comment); + + @DELETE + void deleteComments(); + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskReportResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskReportResource.java new file mode 100644 index 0000000000000000000000000000000000000000..a2ea2912928bcb9ca2cd9df8c08fe989c2c541b5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskReportResource.java @@ -0,0 +1,36 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; + +@Produces(MediaType.APPLICATION_JSON) +public interface TaskReportResource { + + String PATH = "/report"; + + @GET + @Path("candidate-group-count") + @Produces({ MediaType.APPLICATION_JSON, "text/csv", "application/csv" }) + Response getTaskCountByCandidateGroupReport(@Context Request request); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskResource.java new file mode 100644 index 0000000000000000000000000000000000000000..239c16bd94e1ccd48a06a47d4bcfbd66f606178c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/TaskResource.java @@ -0,0 +1,153 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task; + +import java.util.List; +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.DefaultValue; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; + +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.task.CompleteTaskDto; +import org.camunda.bpm.engine.rest.dto.task.FormDto; +import org.camunda.bpm.engine.rest.dto.task.IdentityLinkDto; +import org.camunda.bpm.engine.rest.dto.task.TaskBpmnErrorDto; +import org.camunda.bpm.engine.rest.dto.task.TaskEscalationDto; +import org.camunda.bpm.engine.rest.dto.task.TaskDto; +import org.camunda.bpm.engine.rest.dto.task.UserIdDto; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.sub.VariableResource; + +public interface TaskResource { + + @GET + @Produces({MediaType.APPLICATION_JSON, Hal.APPLICATION_HAL_JSON}) + Object getTask(@Context Request request); + + @GET + @Path("/form") + @Produces(MediaType.APPLICATION_JSON) + FormDto getForm(); + + @POST + @Path("/submit-form") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Response submit(CompleteTaskDto dto); + + @GET + @Path("/rendered-form") + @Produces(MediaType.APPLICATION_XHTML_XML) + Response getRenderedForm(); + + @GET + @Path("/deployed-form") + Response getDeployedForm(); + + @POST + @Path("/claim") + @Consumes(MediaType.APPLICATION_JSON) + void claim(UserIdDto dto); + + @POST + @Path("/unclaim") + void unclaim(); + + @POST + @Path("/complete") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Response complete(CompleteTaskDto dto); + + @POST + @Path("/resolve") + @Consumes(MediaType.APPLICATION_JSON) + void resolve(CompleteTaskDto dto); + + @POST + @Path("/delegate") + @Consumes(MediaType.APPLICATION_JSON) + void delegate(UserIdDto delegatedUser); + + @POST + @Path("/assignee") + @Consumes(MediaType.APPLICATION_JSON) + void setAssignee(UserIdDto dto); + + @GET + @Path("/identity-links") + @Produces(MediaType.APPLICATION_JSON) + List getIdentityLinks(@QueryParam("type") String type); + + @POST + @Path("/identity-links") + @Consumes(MediaType.APPLICATION_JSON) + void addIdentityLink(IdentityLinkDto identityLink); + + @POST + @Path("/identity-links/delete") + @Consumes(MediaType.APPLICATION_JSON) + void deleteIdentityLink(IdentityLinkDto identityLink); + + @Path("/comment") + TaskCommentResource getTaskCommentResource(); + + @Path("/attachment") + TaskAttachmentResource getAttachmentResource(); + + @Path("/variables") + VariableResource getVariables(); + + @Path("/localVariables") + VariableResource getLocalVariables(); + + @GET + @Path("/form-variables") + @Produces(MediaType.APPLICATION_JSON) + Map getFormVariables(@QueryParam("variableNames") String variableNames, + @QueryParam(VariableResource.DESERIALIZE_VALUES_QUERY_PARAM) @DefaultValue("true") boolean deserializeValues); + + @PUT + @Consumes(MediaType.APPLICATION_JSON) + public void updateTask(TaskDto task); + + @DELETE + void deleteTask(@PathParam("id") String id); + + @POST + @Path("/bpmnError") + @Consumes(MediaType.APPLICATION_JSON) + void handleBpmnError(TaskBpmnErrorDto dto); + + @POST + @Path("/bpmnEscalation") + @Consumes(MediaType.APPLICATION_JSON) + void handleEscalation(TaskEscalationDto dto); +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/LocalTaskVariablesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/LocalTaskVariablesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..0f15c85acadacc9058f42c430a26e283a3dd96d9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/LocalTaskVariablesResource.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task.impl; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.TaskServiceImpl; +import org.camunda.bpm.engine.rest.sub.impl.AbstractVariablesResource; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import java.util.List; + +public class LocalTaskVariablesResource extends AbstractVariablesResource { + + public LocalTaskVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) { + super(engine, resourceId, objectMapper); + } + + protected String getResourceTypeName() { + return "task"; + } + + protected void removeVariableEntity(String variableKey) { + engine.getTaskService().removeVariableLocal(resourceId, variableKey); + } + + protected VariableMap getVariableEntities(boolean deserializeValues) { + return engine.getTaskService().getVariablesLocalTyped(resourceId, deserializeValues); + } + + protected void updateVariableEntities(VariableMap modifications, List deletions) { + TaskServiceImpl taskService = (TaskServiceImpl) engine.getTaskService(); + taskService.updateVariablesLocal(resourceId, modifications, deletions); + } + + protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { + return engine.getTaskService().getVariableLocalTyped(resourceId, variableKey, deserializeValue); + } + + protected void setVariableEntity(String variableKey, TypedValue variableValue) { + engine.getTaskService().setVariableLocal(resourceId, variableKey, variableValue); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskAttachmentResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskAttachmentResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a5b71fcc41557ddd6dbd61b2704f5b13fe804559 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskAttachmentResourceImpl.java @@ -0,0 +1,191 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task.impl; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.dto.task.AttachmentDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData; +import org.camunda.bpm.engine.rest.mapper.MultipartFormData.FormPart; +import org.camunda.bpm.engine.rest.sub.task.TaskAttachmentResource; +import org.camunda.bpm.engine.task.Attachment; + +public class TaskAttachmentResourceImpl implements TaskAttachmentResource { + + private ProcessEngine engine; + private String taskId; + private String rootResourcePath; + + public TaskAttachmentResourceImpl(ProcessEngine engine, String taskId, String rootResourcePath) { + this.engine = engine; + this.taskId = taskId; + this.rootResourcePath = rootResourcePath; + } + + @Override + public List getAttachments() { + if (!isHistoryEnabled()) { + return Collections.emptyList(); + } + + ensureTaskExists(Status.NOT_FOUND); + + List taskAttachments = engine.getTaskService().getTaskAttachments(taskId); + + List attachments = new ArrayList(); + for (Attachment attachment : taskAttachments) { + attachments.add(AttachmentDto.fromAttachment(attachment)); + } + + return attachments; + } + + @Override + public AttachmentDto getAttachment(String attachmentId) { + ensureHistoryEnabled(Status.NOT_FOUND); + + Attachment attachment = engine.getTaskService().getTaskAttachment(taskId, attachmentId); + + if (attachment == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Task attachment with id " + attachmentId + " does not exist for task id '" + taskId + "'."); + } + + return AttachmentDto.fromAttachment(attachment); + } + + @Override + public InputStream getAttachmentData(String attachmentId) { + ensureHistoryEnabled(Status.NOT_FOUND); + + InputStream attachmentData = engine.getTaskService().getTaskAttachmentContent(taskId, attachmentId); + + if (attachmentData != null) { + return attachmentData; + } + else { + throw new InvalidRequestException(Status.NOT_FOUND, "Attachment content for attachment with id '" + attachmentId + "' does not exist for task id '" + taskId + "'."); + } + } + + @Override + public void deleteAttachment(String attachmentId) { + ensureHistoryEnabled(Status.FORBIDDEN); + + try { + engine.getTaskService().deleteTaskAttachment(taskId, attachmentId); + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.NOT_FOUND, "Deletion is not possible. No attachment exists for task id '" + taskId + "' and attachment id '" + attachmentId + "'."); + } + } + + @Override + public AttachmentDto addAttachment(UriInfo uriInfo, MultipartFormData payload) { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureTaskExists(Status.BAD_REQUEST); + + FormPart attachmentNamePart = payload.getNamedPart("attachment-name"); + FormPart attachmentTypePart = payload.getNamedPart("attachment-type"); + FormPart attachmentDescriptionPart = payload.getNamedPart("attachment-description"); + FormPart contentPart = payload.getNamedPart("content"); + FormPart urlPart = payload.getNamedPart("url"); + + if (urlPart == null && contentPart == null) { + throw new InvalidRequestException(Status.BAD_REQUEST, "No content or url to remote content exists to create the task attachment."); + } + + String attachmentName = null; + String attachmentDescription = null; + String attachmentType = null; + if (attachmentNamePart != null) { + attachmentName = attachmentNamePart.getTextContent(); + } + if (attachmentDescriptionPart != null) { + attachmentDescription = attachmentDescriptionPart.getTextContent(); + } + if (attachmentTypePart != null) { + attachmentType = attachmentTypePart.getTextContent(); + } + + Attachment attachment = null; + try { + if (contentPart != null) { + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(contentPart.getBinaryContent()); + attachment = engine.getTaskService().createAttachment(attachmentType, taskId, null, attachmentName, attachmentDescription, byteArrayInputStream); + } else if (urlPart != null) { + attachment = engine.getTaskService().createAttachment(attachmentType, taskId, null, attachmentName, attachmentDescription, urlPart.getTextContent()); + } + } catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Task id is null"); + } + + URI uri = uriInfo.getBaseUriBuilder() + .path(rootResourcePath) + .path(TaskRestService.PATH) + .path(taskId + "/attachment/" + attachment.getId()) + .build(); + + AttachmentDto attachmentDto = AttachmentDto.fromAttachment(attachment); + + // GET / + attachmentDto.addReflexiveLink(uri, HttpMethod.GET, "self"); + + return attachmentDto; + } + + private boolean isHistoryEnabled() { + IdentityService identityService = engine.getIdentityService(); + Authentication currentAuthentication = identityService.getCurrentAuthentication(); + try { + identityService.clearAuthentication(); + int historyLevel = engine.getManagementService().getHistoryLevel(); + return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE; + } finally { + identityService.setAuthentication(currentAuthentication); + } + } + + private void ensureHistoryEnabled(Status status) { + if (!isHistoryEnabled()) { + throw new InvalidRequestException(status, "History is not enabled"); + } + } + + private void ensureTaskExists(Status status) { + HistoricTaskInstance historicTaskInstance = engine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).singleResult(); + if (historicTaskInstance == null) { + throw new InvalidRequestException(status, "No task found for task id " + taskId); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskCommentResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskCommentResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..8a24336172cc53eabb7ec3041b666dcde75fac1b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskCommentResourceImpl.java @@ -0,0 +1,175 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task.impl; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.UriInfo; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.TaskRestService; +import org.camunda.bpm.engine.rest.dto.task.CommentDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.task.TaskCommentResource; +import org.camunda.bpm.engine.task.Comment; + +public class TaskCommentResourceImpl implements TaskCommentResource { + + private ProcessEngine engine; + private String taskId; + private String rootResourcePath; + + public TaskCommentResourceImpl(ProcessEngine engine, String taskId, String rootResourcePath) { + this.engine = engine; + this.taskId = taskId; + this.rootResourcePath = rootResourcePath; + } + + public List getComments() { + if (!isHistoryEnabled()) { + return Collections.emptyList(); + } + + ensureTaskExists(Status.NOT_FOUND); + + List taskComments = engine.getTaskService().getTaskComments(taskId); + + List comments = new ArrayList(); + for (Comment comment : taskComments) { + comments.add(CommentDto.fromComment(comment)); + } + + return comments; + } + + public CommentDto getComment(String commentId) { + ensureHistoryEnabled(Status.NOT_FOUND); + + Comment comment = engine.getTaskService().getTaskComment(taskId, commentId); + if (comment == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "Task comment with id " + commentId + " does not exist for task id '" + taskId + "'."); + } + + return CommentDto.fromComment(comment); + } + + public void deleteComment(String commentId) { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureTaskExists(Status.NOT_FOUND); + + TaskService taskService = engine.getTaskService(); + try { + taskService.deleteTaskComment(taskId, commentId); + } catch (AuthorizationException e) { + throw e; + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + public void updateComment(CommentDto comment) { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureTaskExists(Status.NOT_FOUND); + + try { + engine.getTaskService().updateTaskComment(taskId, comment.getId(), comment.getMessage()); + } catch (AuthorizationException e) { + throw e; + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + public void deleteComments() { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureTaskExists(Status.NOT_FOUND); + TaskService taskService = engine.getTaskService(); + + try { + taskService.deleteTaskComments(taskId); + } catch (AuthorizationException e) { + throw e; + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + public CommentDto createComment(UriInfo uriInfo, CommentDto commentDto) { + ensureHistoryEnabled(Status.FORBIDDEN); + ensureTaskExists(Status.BAD_REQUEST); + + Comment comment; + + String processInstanceId = commentDto.getProcessInstanceId(); + try { + comment = engine.getTaskService().createComment(taskId, processInstanceId, commentDto.getMessage()); + } + catch (ProcessEngineException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Not enough parameters submitted"); + } + + URI uri = uriInfo.getBaseUriBuilder() + .path(rootResourcePath) + .path(TaskRestService.PATH) + .path(taskId + "/comment/" + comment.getId()) + .build(); + + CommentDto resultDto = CommentDto.fromComment(comment); + + // GET / + resultDto.addReflexiveLink(uri, HttpMethod.GET, "self"); + + return resultDto; + } + + private boolean isHistoryEnabled() { + IdentityService identityService = engine.getIdentityService(); + Authentication currentAuthentication = identityService.getCurrentAuthentication(); + try { + identityService.clearAuthentication(); + int historyLevel = engine.getManagementService().getHistoryLevel(); + return historyLevel > ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE; + } finally { + identityService.setAuthentication(currentAuthentication); + } + } + + private void ensureHistoryEnabled(Status status) { + if (!isHistoryEnabled()) { + throw new InvalidRequestException(status, "History is not enabled"); + } + } + + private void ensureTaskExists(Status status) { + HistoricTaskInstance historicTaskInstance = engine.getHistoryService().createHistoricTaskInstanceQuery().taskId(taskId).singleResult(); + if (historicTaskInstance == null) { + throw new InvalidRequestException(status, "No task found for task id " + taskId); + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskReportResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskReportResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..6666ddea0f3eb712dea0aa2697e093aa61838860 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskReportResourceImpl.java @@ -0,0 +1,86 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task.impl; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.dto.converter.TaskReportResultToCsvConverter; +import org.camunda.bpm.engine.rest.dto.task.TaskCountByCandidateGroupResultDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.sub.task.TaskReportResource; +import org.camunda.bpm.engine.rest.util.URLEncodingUtil; +import org.camunda.bpm.engine.task.TaskCountByCandidateGroupResult; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.Variant; +import java.util.ArrayList; +import java.util.List; + +public class TaskReportResourceImpl implements TaskReportResource { + + public static final MediaType APPLICATION_CSV_TYPE = new MediaType("application", "csv"); + public static final MediaType TEXT_CSV_TYPE = new MediaType("text", "csv"); + public static final List VARIANTS = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, APPLICATION_CSV_TYPE, TEXT_CSV_TYPE).add().build(); + + protected ProcessEngine engine; + + public TaskReportResourceImpl(ProcessEngine engine) { + this.engine = engine; + } + + public Response getTaskCountByCandidateGroupReport(Request request) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + MediaType mediaType = variant.getMediaType(); + + if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) { + List result = getTaskCountByCandidateGroupResultAsJson(); + return Response.ok(result, mediaType).build(); + } + else if (APPLICATION_CSV_TYPE.equals(mediaType) || TEXT_CSV_TYPE.equals(mediaType)) { + String csv = getReportResultAsCsv(); + return Response + .ok(csv, mediaType) + .header("Content-Disposition", URLEncodingUtil.buildAttachmentValue("task-count-by-candidate-group.csv")) + .build(); + } + } + throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + @SuppressWarnings("unchecked") + protected List queryTaskCountByCandidateGroupReport() { + TaskCountByCandidateGroupResultDto reportDto = new TaskCountByCandidateGroupResultDto(); + return (List) reportDto.executeTaskCountByCandidateGroupReport(engine); + } + + protected List getTaskCountByCandidateGroupResultAsJson() { + List reports = queryTaskCountByCandidateGroupReport(); + List result = new ArrayList(); + for (TaskCountByCandidateGroupResult report : reports) { + result.add(TaskCountByCandidateGroupResultDto.fromTaskCountByCandidateGroupResultDto(report)); + } + return result; + } + + protected String getReportResultAsCsv() { + List reports = queryTaskCountByCandidateGroupReport(); + return TaskReportResultToCsvConverter.convertCandidateGroupReportResult(reports); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskResourceImpl.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskResourceImpl.java new file mode 100644 index 0000000000000000000000000000000000000000..a52124e84ae1d26f37e5f7e126f0b6c77fe7d2ad --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskResourceImpl.java @@ -0,0 +1,498 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task.impl; + +import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Request; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; +import javax.ws.rs.core.Variant; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.FormService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.form.FormData; +import org.camunda.bpm.engine.impl.form.validator.FormFieldValidationException; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; +import org.camunda.bpm.engine.rest.dto.task.*; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.hal.task.HalTask; +import org.camunda.bpm.engine.rest.sub.VariableResource; +import org.camunda.bpm.engine.rest.sub.task.TaskAttachmentResource; +import org.camunda.bpm.engine.rest.sub.task.TaskCommentResource; +import org.camunda.bpm.engine.rest.sub.task.TaskResource; +import org.camunda.bpm.engine.rest.util.ApplicationContextPathUtil; +import org.camunda.bpm.engine.rest.util.ContentTypeUtil; +import org.camunda.bpm.engine.rest.util.EncodingUtil; +import org.camunda.bpm.engine.task.IdentityLink; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.variable.VariableMap; + +import com.fasterxml.jackson.databind.ObjectMapper; + +public class TaskResourceImpl implements TaskResource { + + public static final List VARIANTS = Variant.mediaTypes(MediaType.APPLICATION_JSON_TYPE, Hal.APPLICATION_HAL_JSON_TYPE).add().build(); + + protected ProcessEngine engine; + protected String taskId; + protected String rootResourcePath; + protected ObjectMapper objectMapper; + protected boolean withCommentAttachmentInfo; + protected boolean withTaskVariablesInReturn; + protected boolean withTaskLocalVariablesInReturn; + + public TaskResourceImpl(ProcessEngine engine, + String taskId, + String rootResourcePath, + ObjectMapper objectMapper, + boolean withCommentAttachmentInfo, + boolean withTaskVariablesInReturn, + boolean withTaskLocalVariablesInReturn) { + this.engine = engine; + this.taskId = taskId; + this.rootResourcePath = rootResourcePath; + this.objectMapper = objectMapper; + this.withCommentAttachmentInfo = withCommentAttachmentInfo; + this.withTaskVariablesInReturn = withTaskVariablesInReturn; + this.withTaskLocalVariablesInReturn = withTaskLocalVariablesInReturn; + } + + @Override + public void claim(UserIdDto dto) { + TaskService taskService = engine.getTaskService(); + + taskService.claim(taskId, dto.getUserId()); + } + + @Override + public void unclaim() { + engine.getTaskService().setAssignee(taskId, null); + } + + @Override + public Response complete(CompleteTaskDto dto) { + TaskService taskService = engine.getTaskService(); + + try { + VariableMap variables = VariableValueDto.toMap(dto.getVariables(), engine, objectMapper); + if (dto.isWithVariablesInReturn()) { + VariableMap taskVariables = taskService.completeWithVariablesInReturn(taskId, variables, false); + + Map body = VariableValueDto.fromMap(taskVariables, true); + + return Response + .ok(body) + .type(MediaType.APPLICATION_JSON) + .build(); + } else { + taskService.complete(taskId, variables); + return Response.noContent().build(); + } + + } catch (RestException e) { + String errorMessage = String.format("Cannot complete task %s: %s", taskId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } catch (AuthorizationException e) { + throw e; + + } catch (FormFieldValidationException e) { + String errorMessage = String.format("Cannot complete task %s: %s", taskId, e.getMessage()); + throw new RestException(Status.BAD_REQUEST, e, errorMessage); + + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot complete task %s: %s", taskId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + } + + @Override + public Response submit(CompleteTaskDto dto) { + FormService formService = engine.getFormService(); + + try { + VariableMap variables = VariableValueDto.toMap(dto.getVariables(), engine, objectMapper); + if (dto.isWithVariablesInReturn()) { + VariableMap taskVariables = formService.submitTaskFormWithVariablesInReturn(taskId, variables, false); + + Map body = VariableValueDto.fromMap(taskVariables, true); + return Response + .ok(body) + .type(MediaType.APPLICATION_JSON) + .build(); + } else { + formService.submitTaskForm(taskId, variables); + return Response.noContent().build(); + } + + } catch (RestException e) { + String errorMessage = String.format("Cannot submit task form %s: %s", taskId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } catch (AuthorizationException e) { + throw e; + + } catch (FormFieldValidationException e) { + String errorMessage = String.format("Cannot submit task form %s: %s", taskId, e.getMessage()); + throw new RestException(Status.BAD_REQUEST, e, errorMessage); + + } catch (ProcessEngineException e) { + String errorMessage = String.format("Cannot submit task form %s: %s", taskId, e.getMessage()); + throw new RestException(Status.INTERNAL_SERVER_ERROR, e, errorMessage); + } + + } + + @Override + public void delegate(UserIdDto delegatedUser) { + engine.getTaskService().delegateTask(taskId, delegatedUser.getUserId()); + } + + @Override + public Object getTask(Request request) { + Variant variant = request.selectVariant(VARIANTS); + if (variant != null) { + if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) { + return getJsonTask(); + } + else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) { + return getHalTask(); + } + } + throw new InvalidRequestException(Status.NOT_ACCEPTABLE, "No acceptable content-type found"); + } + + public TaskDto getJsonTask() { + Task task = getTaskById(taskId, withCommentAttachmentInfo); + if (task == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "No matching task with id " + taskId); + } + if ((withTaskVariablesInReturn || withTaskLocalVariablesInReturn) && withCommentAttachmentInfo) { + Map taskVariables = getTaskVariables(withTaskVariablesInReturn); + return TaskWithAttachmentAndCommentDto.fromEntity(task, taskVariables); + } + if (withCommentAttachmentInfo) { + return TaskWithAttachmentAndCommentDto.fromEntity(task, null); + } + if (withTaskVariablesInReturn || withTaskLocalVariablesInReturn) { + Map taskVariables = getTaskVariables(withTaskVariablesInReturn); + return TaskWithVariablesDto.fromEntity(task, taskVariables); + } else { + return TaskDto.fromEntity(task); + } + } + + public HalTask getHalTask() { + Task task = getTaskById(taskId, withCommentAttachmentInfo); + if (task == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "No matching task with id " + taskId); + } + + return HalTask.generate(task, engine); + } + + @Override + public FormDto getForm() { + FormService formService = engine.getFormService(); + Task task = getTaskById(taskId, withCommentAttachmentInfo); + FormData formData; + try { + formData = formService.getTaskFormData(taskId); + } catch (AuthorizationException e) { + throw e; + } catch (ProcessEngineException e) { + throw new RestException(Status.BAD_REQUEST, e, "Cannot get form for task " + taskId); + } + + FormDto dto = FormDto.fromFormData(formData); + if(dto.getKey() == null || dto.getKey().isEmpty()) { + if(formData != null && formData.getFormFields() != null && !formData.getFormFields().isEmpty()) { + dto.setKey("embedded:engine://engine/:engine/task/"+taskId+"/rendered-form"); + } + } + + // to get the application context path it is necessary to + // execute it without authentication (tries to fetch the + // process definition), because: + // - user 'demo' has READ permission on a specific task resource + // - user 'demo' does not have a READ permission on the corresponding + // process definition + // -> running the following lines with authorization would lead + // to an AuthorizationException because the user 'demo' does not + // have READ permission on the corresponding process definition + runWithoutAuthorization(() -> { + String processDefinitionId = task.getProcessDefinitionId(); + String caseDefinitionId = task.getCaseDefinitionId(); + if (processDefinitionId != null) { + dto.setContextPath(ApplicationContextPathUtil.getApplicationPathByProcessDefinitionId(engine, processDefinitionId)); + + } else if (caseDefinitionId != null) { + dto.setContextPath(ApplicationContextPathUtil.getApplicationPathByCaseDefinitionId(engine, caseDefinitionId)); + } + return null; + }); + + return dto; + } + + @Override + public Response getRenderedForm() { + FormService formService = engine.getFormService(); + + Object renderedTaskForm = formService.getRenderedTaskForm(taskId); + if(renderedTaskForm != null) { + String content = renderedTaskForm.toString(); + InputStream stream = new ByteArrayInputStream(content.getBytes(EncodingUtil.DEFAULT_ENCODING)); + return Response + .ok(stream) + .type(MediaType.APPLICATION_XHTML_XML) + .build(); + } + + throw new InvalidRequestException(Status.NOT_FOUND, "No matching rendered form for task with the id " + taskId + " found."); + } + + @Override + public void resolve(CompleteTaskDto dto) { + TaskService taskService = engine.getTaskService(); + + try { + VariableMap variables = VariableValueDto.toMap(dto.getVariables(), engine, objectMapper); + taskService.resolveTask(taskId, variables); + + } catch (RestException e) { + String errorMessage = String.format("Cannot resolve task %s: %s", taskId, e.getMessage()); + throw new InvalidRequestException(e.getStatus(), e, errorMessage); + + } + + } + + public void setAssignee(UserIdDto dto) { + TaskService taskService = engine.getTaskService(); + taskService.setAssignee(taskId, dto.getUserId()); + } + + @Override + public List getIdentityLinks(String type) { + TaskService taskService = engine.getTaskService(); + List identityLinks = taskService.getIdentityLinksForTask(taskId); + + List result = new ArrayList<>(); + for (IdentityLink link : identityLinks) { + if (type == null || type.equals(link.getType())) { + result.add(IdentityLinkDto.fromIdentityLink(link)); + } + } + + return result; + } + + @Override + public void addIdentityLink(IdentityLinkDto identityLink) { + TaskService taskService = engine.getTaskService(); + + identityLink.validate(); + + if (identityLink.getUserId() != null) { + taskService.addUserIdentityLink(taskId, identityLink.getUserId(), identityLink.getType()); + } else if (identityLink.getGroupId() != null) { + taskService.addGroupIdentityLink(taskId, identityLink.getGroupId(), identityLink.getType()); + } + + } + + @Override + public void deleteIdentityLink(IdentityLinkDto identityLink) { + TaskService taskService = engine.getTaskService(); + + identityLink.validate(); + + if (identityLink.getUserId() != null) { + taskService.deleteUserIdentityLink(taskId, identityLink.getUserId(), identityLink.getType()); + } else if (identityLink.getGroupId() != null) { + taskService.deleteGroupIdentityLink(taskId, identityLink.getGroupId(), identityLink.getType()); + } + + } + + public TaskCommentResource getTaskCommentResource() { + return new TaskCommentResourceImpl(engine, taskId, rootResourcePath); + } + + public TaskAttachmentResource getAttachmentResource() { + return new TaskAttachmentResourceImpl(engine, taskId, rootResourcePath); + } + + public VariableResource getLocalVariables() { + return new LocalTaskVariablesResource(engine, taskId, objectMapper); + } + + public VariableResource getVariables() { + return new TaskVariablesResource(engine, taskId, objectMapper); + } + + public Map getFormVariables(String variableNames, boolean deserializeValues) { + + final FormService formService = engine.getFormService(); + List formVariables = null; + + if(variableNames != null) { + StringListConverter stringListConverter = new StringListConverter(); + formVariables = stringListConverter.convertQueryParameterToType(variableNames); + } + + VariableMap startFormVariables = formService.getTaskFormVariables(taskId, formVariables, deserializeValues); + + return VariableValueDto.fromMap(startFormVariables); + } + + public void updateTask(TaskDto taskDto) { + TaskService taskService = engine.getTaskService(); + + Task task = getTaskById(taskId, withCommentAttachmentInfo); + + if (task == null) { + throw new InvalidRequestException(Status.NOT_FOUND, "No matching task with id " + taskId); + } + + taskDto.updateTask(task); + taskService.saveTask(task); + } + + @Override + public void deleteTask(String id) { + TaskService taskService = engine.getTaskService(); + + try { + taskService.deleteTask(id); + } + catch (NotValidException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e, "Could not delete task: " + e.getMessage()); + } + } + + @Override + public Response getDeployedForm() { + try { + InputStream deployedTaskForm = engine.getFormService().getDeployedTaskForm(taskId); + return Response.ok(deployedTaskForm, getTaskFormMediaType(taskId)).build(); + } catch (NotFoundException e) { + throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage()); + } catch (NullValueException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } catch (AuthorizationException e) { + throw new InvalidRequestException(Status.FORBIDDEN, e.getMessage()); + } catch (BadUserRequestException e) { + throw new InvalidRequestException(Status.BAD_REQUEST, e.getMessage()); + } + } + + @Override + public void handleBpmnError(TaskBpmnErrorDto dto) { + TaskService taskService = engine.getTaskService(); + + try { + taskService.handleBpmnError(taskId, dto.getErrorCode(), dto.getErrorMessage(), + VariableValueDto.toMap(dto.getVariables(), engine, objectMapper)); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, e.getMessage()); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + @Override + public void handleEscalation(TaskEscalationDto dto) { + TaskService taskService = engine.getTaskService(); + + try { + taskService.handleEscalation(taskId, dto.getEscalationCode(), VariableValueDto.toMap(dto.getVariables(), engine, objectMapper)); + } catch (NotFoundException e) { + throw new RestException(Status.NOT_FOUND, e, e.getMessage()); + } catch (BadUserRequestException e) { + throw new RestException(Status.BAD_REQUEST, e, e.getMessage()); + } + } + + protected Task getTaskById(String id, boolean withCommentAttachmentInfo) { + if (withCommentAttachmentInfo) { + return engine.getTaskService().createTaskQuery().taskId(id).withCommentAttachmentInfo().initializeFormKeys().singleResult(); + } + else{ + return engine.getTaskService().createTaskQuery().taskId(id).initializeFormKeys().singleResult(); + } + } + + protected String getTaskFormMediaType(String taskId) { + Task task = engine.getTaskService().createTaskQuery().initializeFormKeys().taskId(taskId).singleResult(); + ensureNotNull("No task found for taskId '" + taskId + "'", "task", task); + String formKey = task.getFormKey(); + if(formKey != null) { + return ContentTypeUtil.getFormContentType(formKey); + } else if(task.getCamundaFormRef() != null) { + return ContentTypeUtil.getFormContentType(task.getCamundaFormRef()); + } + return MediaType.APPLICATION_XHTML_XML; + } + + protected V runWithoutAuthorization(Supplier action) { + IdentityService identityService = engine.getIdentityService(); + Authentication currentAuthentication = identityService.getCurrentAuthentication(); + try { + identityService.clearAuthentication(); + return action.get(); + } catch (Exception e) { + throw e; + } finally { + identityService.setAuthentication(currentAuthentication); + } + } + + private Map getTaskVariables(boolean withTaskVariablesInReturn) { + VariableResource variableResource; + if (withTaskVariablesInReturn) { + variableResource = this.getVariables(); + } else { + variableResource = this.getLocalVariables(); + } + return variableResource.getVariables(true); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskVariablesResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskVariablesResource.java new file mode 100644 index 0000000000000000000000000000000000000000..e754a50eb5ab015d41f1d687db57d1c874599dd3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/sub/task/impl/TaskVariablesResource.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.sub.task.impl; + +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.TaskServiceImpl; +import org.camunda.bpm.engine.rest.sub.impl.AbstractVariablesResource; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.value.TypedValue; + +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @author Daniel Meyer + * + */ +public class TaskVariablesResource extends AbstractVariablesResource { + + public TaskVariablesResource(ProcessEngine engine, String resourceId, ObjectMapper objectMapper) { + super(engine, resourceId, objectMapper); + } + + protected String getResourceTypeName() { + return "task"; + } + + protected TypedValue getVariableEntity(String variableKey, boolean deserializeValue) { + return engine.getTaskService().getVariableTyped(resourceId, variableKey, deserializeValue); + } + + protected VariableMap getVariableEntities(boolean deserializeValues) { + return engine.getTaskService().getVariablesTyped(resourceId, deserializeValues); + } + + protected void removeVariableEntity(String variableKey) { + engine.getTaskService().removeVariable(resourceId, variableKey); + } + + protected void updateVariableEntities(VariableMap modifications, List deletions) { + TaskServiceImpl taskService = (TaskServiceImpl) engine.getTaskService(); + taskService.updateVariables(resourceId, modifications, deletions); + } + + protected void setVariableEntity(String variableKey, TypedValue variableValue) { + engine.getTaskService().setVariable(resourceId, variableKey, variableValue); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ApplicationContextPathUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ApplicationContextPathUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..c96476dc6d4c1ce736b826aaf464ea0c45c78d24 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ApplicationContextPathUtil.java @@ -0,0 +1,72 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import org.camunda.bpm.BpmPlatform; +import org.camunda.bpm.ProcessApplicationService; +import org.camunda.bpm.application.ProcessApplicationInfo; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.ProcessDefinition; + +public class ApplicationContextPathUtil { + + public static String getApplicationPathByProcessDefinitionId(ProcessEngine engine, String processDefinitionId) { + ProcessDefinition processDefinition = engine.getRepositoryService().getProcessDefinition(processDefinitionId); + + if (processDefinition == null) { + return null; + } + + return getApplicationPathForDeployment(engine, processDefinition.getDeploymentId()); + } + + public static String getApplicationPathByCaseDefinitionId(ProcessEngine engine, String caseDefinitionId) { + CaseDefinition caseDefinition = engine.getRepositoryService().getCaseDefinition(caseDefinitionId); + + if (caseDefinition == null) { + return null; + } + + return getApplicationPathForDeployment(engine, caseDefinition.getDeploymentId()); + } + + public static String getApplicationPathForDeployment(ProcessEngine engine, String deploymentId) { + + // get the name of the process application that made the deployment + String processApplicationName = null; + IdentityService identityService = engine.getIdentityService(); + Authentication currentAuthentication = identityService.getCurrentAuthentication(); + try { + identityService.clearAuthentication(); + processApplicationName = engine.getManagementService().getProcessApplicationForDeployment(deploymentId); + } finally { + identityService.setAuthentication(currentAuthentication); + } + + if (processApplicationName == null) { + // no a process application deployment + return null; + } else { + ProcessApplicationService processApplicationService = BpmPlatform.getProcessApplicationService(); + ProcessApplicationInfo processApplicationInfo = processApplicationService.getProcessApplicationInfo(processApplicationName); + return processApplicationInfo.getProperties().get(ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ContentTypeUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ContentTypeUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..4c1340231ac8ef64af89d92dd65e19a343ba027f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ContentTypeUtil.java @@ -0,0 +1,44 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import javax.ws.rs.core.MediaType; + +import org.camunda.bpm.engine.form.CamundaFormRef; + +public class ContentTypeUtil { + + private static final String SUFFIX_FORM_FILE = ".form"; + + /** + * @return the content type to use for the provided form's key + * + */ + public static String getFormContentType(String formKey) { + if (formKey.endsWith(SUFFIX_FORM_FILE)) { + return MediaType.APPLICATION_JSON; + } + return MediaType.APPLICATION_XHTML_XML; + } + + public static String getFormContentType(CamundaFormRef formRef) { + if(formRef != null && formRef.getKey() != null && formRef.getBinding() != null) { + return MediaType.APPLICATION_JSON; + } + return MediaType.APPLICATION_XHTML_XML; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/EncodingUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/EncodingUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..550a7aeb223a15e64578f0d1848cb2277b3df04c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/EncodingUtil.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import java.nio.charset.Charset; + +/** + * @author: Johannes Heinemann + */ +public class EncodingUtil { + + public static final Charset DEFAULT_ENCODING = getDefaultEncoding(); + + protected static Charset getDefaultEncoding() { + Charset charset = null; + try { + charset = Charset.forName("UTF-8"); + }catch (Exception e){ + charset = Charset.defaultCharset(); + } + return charset; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/EngineUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/EngineUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..5671813828ad9f292eb04d9ddb05f4c88d045f94 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/EngineUtil.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider; + +import javax.ws.rs.core.Response.Status; +import java.util.Iterator; +import java.util.ServiceLoader; + +public class EngineUtil { + + /** + * Look up the process engine from the {@link ProcessEngineProvider}. If engineName is null, the default engine is returned. + * @param engineName + * @return + */ + public static ProcessEngine lookupProcessEngine(String engineName) { + + ServiceLoader serviceLoader = ServiceLoader.load(ProcessEngineProvider.class); + Iterator iterator = serviceLoader.iterator(); + + if(iterator.hasNext()) { + ProcessEngineProvider provider = iterator.next(); + if (engineName == null) { + return provider.getDefaultProcessEngine(); + } else { + return provider.getProcessEngine(engineName); + } + } else { + throw new RestException(Status.INTERNAL_SERVER_ERROR, "Could not find an implementation of the "+ProcessEngineProvider.class+"- SPI"); + } + } + + public static ProcessEngineProvider getProcessEngineProvider() { + ServiceLoader serviceLoader = ServiceLoader.load(ProcessEngineProvider.class); + Iterator iterator = serviceLoader.iterator(); + + if (iterator.hasNext()) { + ProcessEngineProvider provider = iterator.next(); + return provider; + } else { + throw new RestException(Status.INTERNAL_SERVER_ERROR, "No process engine provider found"); + } + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/PathUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/PathUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..64e9398a940dcbe749d852789c894faf6cc42d9f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/PathUtil.java @@ -0,0 +1,32 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +/** + * @author Daniel Meyer + * + */ +public class PathUtil { + + public static String decodePathParam(String param) { + + return param + .replaceAll("%2F", "/") + .replaceAll("%5C", "\\\\"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ProvidersUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ProvidersUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..f7dc5b239efdc28bc4f2ceb32f6b801a7c248930 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ProvidersUtil.java @@ -0,0 +1,48 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import org.camunda.bpm.engine.rest.exception.RestException; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Providers; + +/** + * @author Thorben Lindhauer + * + */ +public class ProvidersUtil { + + public static T resolveFromContext(Providers providers, Class clazz) { + return resolveFromContext(providers, clazz, null); + } + + public static T resolveFromContext(Providers providers, Class clazz, Class type) { + return resolveFromContext(providers, clazz, null, type); + } + + public static T resolveFromContext(Providers providers, Class clazz, MediaType mediaType, Class type) { + ContextResolver contextResolver = providers.getContextResolver(clazz, mediaType); + + if (contextResolver == null) { + throw new RestException("No context resolver found for class " + clazz.getName()); + } + + return contextResolver.getContext(type); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/QueryUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/QueryUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..44e9d2b82f2b5a6be70ff5998d5a875638f5fe03 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/QueryUtil.java @@ -0,0 +1,45 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import java.util.List; +import org.camunda.bpm.engine.query.Query; + +public class QueryUtil { + + private QueryUtil() {} + + public static , U> List list(Query query, Integer firstResult, Integer maxResults) { + List results; + if (firstResult != null || maxResults != null) { + results = executePaginatedQuery(query, firstResult, maxResults); + } else { + results = query.list(); + } + return results; + } + + private static , U> List executePaginatedQuery(Query query, Integer firstResult, Integer maxResults) { + if (firstResult == null) { + firstResult = 0; + } + if (maxResults == null) { + maxResults = Integer.MAX_VALUE; + } + return query.listPage(firstResult, maxResults); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ResourceUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ResourceUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..76e6da255f427152371fbf4ba36f6da49aae0ac9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/ResourceUtil.java @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import org.camunda.bpm.engine.authorization.Resource; + +public class ResourceUtil implements Resource { + + protected String resourceName; + protected int resourceType; + + public ResourceUtil(String resourceName, int resourceType) { + this.resourceName = resourceName; + this.resourceType = resourceType; + } + + public String resourceName() { + return resourceName; + } + + public int resourceType() { + return resourceType; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); + result = prime * result + resourceType; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ResourceUtil other = (ResourceUtil) obj; + if (resourceName == null) { + if (other.resourceName != null) + return false; + } else if (!resourceName.equals(other.resourceName)) + return false; + if (resourceType != other.resourceType) + return false; + return true; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/URLEncodingUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/URLEncodingUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..81f34d92b308b82e80683e7cb923a10b3f653494 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/URLEncodingUtil.java @@ -0,0 +1,47 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +import static java.text.MessageFormat.format; + +public class URLEncodingUtil { + + /** + * Encode a string value using `UTF-8` encoding scheme + */ + public static String encode(String value) { + if (value != null) { + try { + return URLEncoder.encode(value, StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException ex) { + // should not happen + return value; + } + } + + return null; + } + + public static String buildAttachmentValue(String attachmentFileName) { + return format("attachment; filename=\"{0}\"; filename*=UTF-8''''{1}", attachmentFileName, encode(attachmentFileName)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/WebApplicationUtil.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/WebApplicationUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..ea4a22e6cfe1b5eef0a1da33914d8d6822a9e651 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/java/org/camunda/bpm/engine/rest/util/WebApplicationUtil.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.util; + +import static org.camunda.bpm.engine.rest.util.EngineUtil.getProcessEngineProvider; + +import org.camunda.bpm.engine.impl.ManagementServiceImpl; +import org.camunda.bpm.engine.impl.diagnostics.PlatformDiagnosticsRegistry; +import org.camunda.bpm.engine.impl.telemetry.dto.LicenseKeyDataImpl; +import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider; + +public class WebApplicationUtil { + + public static void setApplicationServer(String serverInfo) { + if (serverInfo != null && !serverInfo.isEmpty() ) { + // set the application server info globally for all engines in the container + if (PlatformDiagnosticsRegistry.getApplicationServer() == null) { + PlatformDiagnosticsRegistry.setApplicationServer(serverInfo); + } + } + } + + public static void setLicenseKey(LicenseKeyDataImpl licenseKeyData) { + if (licenseKeyData != null) { + ProcessEngineProvider processEngineProvider = getProcessEngineProvider(); + for (String engineName : processEngineProvider.getProcessEngineNames()) { + if (engineName != null) { + ManagementServiceImpl managementService = (ManagementServiceImpl) processEngineProvider.getProcessEngine(engineName).getManagementService(); + managementService.setLicenseKeyForDiagnostics(licenseKeyData); + } + } + } + } + + /** + * Adds the web application name to the telemetry data of the engine. + * + * @param engineName + * the engine for which the web application usage should be indicated + * @param webapp + * the web application that is used with the engine + * @return whether the web application was successfully added or not + */ + public static boolean setWebapp(String engineName, String webapp) { + ProcessEngineProvider processEngineProvider = getProcessEngineProvider(); + ManagementServiceImpl managementService = (ManagementServiceImpl) processEngineProvider.getProcessEngine(engineName).getManagementService(); + return managementService.addWebappToTelemetry(webapp); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/resources/META-INF/services/org.camunda.bpm.engine.rest.spi.FetchAndLockHandler b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/resources/META-INF/services/org.camunda.bpm.engine.rest.spi.FetchAndLockHandler new file mode 100644 index 0000000000000000000000000000000000000000..a3fcef3774b42c22ae2fb52930514a812c98e30f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/main/resources/META-INF/services/org.camunda.bpm.engine.rest.spi.FetchAndLockHandler @@ -0,0 +1 @@ +org.camunda.bpm.engine.rest.impl.FetchAndLockHandlerImpl \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AbstractRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AbstractRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b468442862b52b6ab2ffe96334cdd8c96229dbf7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AbstractRestServiceTest.java @@ -0,0 +1,213 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Iterator; +import java.util.Properties; +import java.util.ServiceLoader; + +import javax.ws.rs.core.MediaType; + +import org.apache.http.entity.ContentType; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.persistence.entity.ActivityInstanceImpl; +import org.camunda.bpm.engine.impl.persistence.entity.TransitionInstanceImpl; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.spi.ProcessEngineProvider; +import org.camunda.bpm.engine.rest.spi.impl.MockedProcessEngineProvider; +import org.camunda.bpm.engine.runtime.ActivityInstance; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.runtime.TransitionInstance; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.BytesValue; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.junit.Before; + +import io.restassured.RestAssured; +import io.restassured.http.Header; + +public abstract class AbstractRestServiceTest { + + protected static ProcessEngine processEngine; + protected static final String TEST_RESOURCE_ROOT_PATH = "/rest-test"; + protected static int PORT; + + protected static final Header ACCEPT_WILDCARD_HEADER = new Header("Accept", MediaType.WILDCARD); + protected static final Header ACCEPT_JSON_HEADER = new Header("Accept", MediaType.APPLICATION_JSON); + protected static final Header ACCEPT_HAL_HEADER = new Header("Accept", Hal.APPLICATION_HAL_JSON); + + protected static final String POST_JSON_CONTENT_TYPE = ContentType.create(MediaType.APPLICATION_JSON, "UTF-8").toString(); + protected static final String XHTML_XML_CONTENT_TYPE = ContentType.create(MediaType.APPLICATION_XHTML_XML).toString(); + + protected static final String EMPTY_JSON_OBJECT = "{}"; + + private static final String PROPERTIES_FILE_PATH = "/testconfig.properties"; + private static final String PORT_PROPERTY = "rest.http.port"; + + protected static final String EXAMPLE_VARIABLE_KEY = "aVariableKey"; + protected static final TypedValue EXAMPLE_VARIABLE_VALUE = Variables.stringValue("aVariableValue"); + protected static final String EXAMPLE_BYTES_VARIABLE_KEY = "aBytesVariableKey"; + protected static final BytesValue EXAMPLE_VARIABLE_VALUE_BYTES = Variables.byteArrayValue("someBytes".getBytes()); + protected static final String EXAMPLE_ANOTHER_VARIABLE_KEY = "anotherVariableKey"; + + protected static final VariableMap EXAMPLE_VARIABLES = Variables.createVariables(); + static { + EXAMPLE_VARIABLES.putValueTyped(EXAMPLE_VARIABLE_KEY, EXAMPLE_VARIABLE_VALUE); + } + + protected static final VariableMap EXAMPLE_VARIABLES_WITH_NULL_VALUE = Variables.createVariables(); + static { + EXAMPLE_VARIABLES_WITH_NULL_VALUE.putValueTyped(EXAMPLE_ANOTHER_VARIABLE_KEY, Variables.untypedNullValue()); + } + + protected static final String EXAMPLE_ACTIVITY_INSTANCE_ID = "anActivityInstanceId"; + protected static final String EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID = "aParentActivityInstanceId"; + protected static final String EXAMPLE_ACTIVITY_ID = "anActivityId"; + protected static final String EXAMPLE_ACTIVITY_NAME = "anActivityName"; + protected static final String EXAMPLE_PROCESS_INSTANCE_ID = "aProcessInstanceId"; + protected static final String EXAMPLE_PROCESS_DEFINITION_ID = "aProcessDefinitionId"; + protected static final String EXAMPLE_PROCESS_DEFINITION_KEY = "aKey"; + protected static final String EXAMPLE_BUSINESS_KEY = "aBusinessKey"; + protected static final String EXAMPLE_EXECUTION_ID = "anExecutionId"; + protected static final String EXAMPLE_INCIDENT_ID = "anIncidentId"; + protected static final String EXAMPLE_ANOTHER_INCIDENT_ID = "anotherIncidentId"; + + protected static final String CHILD_EXAMPLE_ACTIVITY_INSTANCE_ID = "aChildActivityInstanceId"; + protected static final String CHILD_EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID = "aChildParentActivityInstanceId"; + protected static final String CHILD_EXAMPLE_ACTIVITY_ID = "aChildActivityId"; + protected static final String CHILD_EXAMPLE_ACTIVITY_TYPE = "aChildActivityType"; + protected static final String CHILD_EXAMPLE_ACTIVITY_NAME = "aChildActivityName"; + protected static final String CHILD_EXAMPLE_PROCESS_INSTANCE_ID = "aChildProcessInstanceId"; + protected static final String CHILD_EXAMPLE_PROCESS_DEFINITION_ID = "aChildProcessDefinitionId"; + protected static final String CHILD_EXAMPLE_BUSINESS_KEY = "aChildBusinessKey"; + + protected static final ActivityInstance EXAMPLE_ACTIVITY_INSTANCE = new ActivityInstanceImpl(); + static { + ActivityInstanceImpl instance = (ActivityInstanceImpl) EXAMPLE_ACTIVITY_INSTANCE; + instance.setId(EXAMPLE_ACTIVITY_INSTANCE_ID); + instance.setParentActivityInstanceId(EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID); + instance.setActivityId(EXAMPLE_ACTIVITY_ID); + instance.setActivityType(CHILD_EXAMPLE_ACTIVITY_TYPE); + instance.setActivityName(EXAMPLE_ACTIVITY_NAME); + instance.setProcessInstanceId(EXAMPLE_PROCESS_INSTANCE_ID); + instance.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + instance.setBusinessKey(EXAMPLE_BUSINESS_KEY); + instance.setExecutionIds(new String[]{EXAMPLE_EXECUTION_ID}); + instance.setIncidents(new Incident[] {MockProvider.createMockIncident()}); + + ActivityInstanceImpl childActivity = new ActivityInstanceImpl(); + childActivity.setId(CHILD_EXAMPLE_ACTIVITY_INSTANCE_ID); + childActivity.setParentActivityInstanceId(CHILD_EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID); + childActivity.setActivityId(CHILD_EXAMPLE_ACTIVITY_ID); + childActivity.setActivityName(CHILD_EXAMPLE_ACTIVITY_NAME); + childActivity.setActivityType(CHILD_EXAMPLE_ACTIVITY_TYPE); + childActivity.setProcessInstanceId(CHILD_EXAMPLE_PROCESS_INSTANCE_ID); + childActivity.setProcessDefinitionId(CHILD_EXAMPLE_PROCESS_DEFINITION_ID); + childActivity.setBusinessKey(CHILD_EXAMPLE_BUSINESS_KEY); + childActivity.setExecutionIds(new String[]{EXAMPLE_EXECUTION_ID}); + childActivity.setChildActivityInstances(new ActivityInstance[0]); + childActivity.setChildTransitionInstances(new TransitionInstance[0]); + childActivity.setIncidentIds(new String[]{EXAMPLE_INCIDENT_ID}); + childActivity.setIncidents(new Incident[] {MockProvider.createMockIncident()}); + + TransitionInstanceImpl childTransition = new TransitionInstanceImpl(); + childTransition.setId(CHILD_EXAMPLE_ACTIVITY_INSTANCE_ID); + childTransition.setParentActivityInstanceId(CHILD_EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID); + childTransition.setActivityId(CHILD_EXAMPLE_ACTIVITY_ID); + childTransition.setActivityName(CHILD_EXAMPLE_ACTIVITY_NAME); + childTransition.setActivityType(CHILD_EXAMPLE_ACTIVITY_TYPE); + childTransition.setProcessInstanceId(CHILD_EXAMPLE_PROCESS_INSTANCE_ID); + childTransition.setProcessDefinitionId(CHILD_EXAMPLE_PROCESS_DEFINITION_ID); + childTransition.setExecutionId(EXAMPLE_EXECUTION_ID); + childTransition.setIncidentIds(new String[]{EXAMPLE_ANOTHER_INCIDENT_ID}); + childTransition.setIncidents(new Incident[] {MockProvider.createMockIncident()}); + + instance.setChildActivityInstances(new ActivityInstance[]{childActivity}); + instance.setChildTransitionInstances(new TransitionInstance[]{childTransition}); + } + + + private static Properties connectionProperties = null; + private static MockedProcessEngineProvider processEngineProvider = null; + + @Before + public void setUp() throws IOException { + setupTestScenario(); + } + + protected static void setupTestScenario() throws IOException { + setupRestAssured(); + + if (processEngineProvider == null) { + ServiceLoader serviceLoader = ServiceLoader + .load(ProcessEngineProvider.class); + Iterator iterator = serviceLoader.iterator(); + + if (iterator.hasNext()) { + processEngineProvider = (MockedProcessEngineProvider) iterator.next(); + } + } + + // reset engine mocks before every test + processEngineProvider.resetEngines(); + + processEngine = processEngineProvider.getDefaultProcessEngine(); + } + + protected ProcessEngine getProcessEngine(String name) { + ServiceLoader serviceLoader = ServiceLoader + .load(ProcessEngineProvider.class); + Iterator iterator = serviceLoader.iterator(); + + if (iterator.hasNext()) { + ProcessEngineProvider provider = iterator.next(); + return provider.getProcessEngine(name); + } else { + throw new ProcessEngineException("No provider found"); + } + } + + private static void setupRestAssured() throws IOException { + if (connectionProperties == null) { + InputStream propStream = null; + try { + propStream = AbstractRestServiceTest.class.getResourceAsStream(PROPERTIES_FILE_PATH); + connectionProperties = new Properties(); + connectionProperties.load(propStream); + } finally { + propStream.close(); + } + } + + PORT = Integer.parseInt(connectionProperties.getProperty(PORT_PROPERTY)); + RestAssured.port = PORT; + } + + protected File getFile(String path) throws URISyntaxException { + URI uri = this.getClass().getResource(path).toURI(); + return new File(uri); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AuthorizationRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AuthorizationRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b1e45667c86b7de47e81d4006c2552563b76fbf1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AuthorizationRestServiceInteractionTest.java @@ -0,0 +1,1121 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.AUTHORIZATION; +import static org.camunda.bpm.engine.authorization.Resources.BATCH; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_DEFINITION; +import static org.camunda.bpm.engine.authorization.Resources.PROCESS_INSTANCE; +import static org.camunda.bpm.engine.authorization.Resources.TASK; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.AuthorizationQuery; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Permissions; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.authorization.Resources; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.impl.AuthorizationServiceImpl; +import org.camunda.bpm.engine.impl.IdentityServiceImpl; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.cfg.auth.DefaultPermissionProvider; +import org.camunda.bpm.engine.impl.cfg.auth.PermissionProvider; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.dto.authorization.AuthorizationDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.ResourceUtil; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; + +/** + * @author Daniel Meyer + * + */ +public class AuthorizationRestServiceInteractionTest extends AbstractRestServiceTest { + + protected static final String SERVICE_PATH = TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH; + protected static final String AUTH_CREATE_PATH = SERVICE_PATH + "/create"; + protected static final String AUTH_CHECK_PATH = SERVICE_PATH + "/check"; + protected static final String AUTH_RESOURCE_PATH = SERVICE_PATH + "/{id}"; + + protected AuthorizationService authorizationServiceMock; + protected IdentityService identityServiceMock; + protected ProcessEngineConfigurationImpl processEngineConfigurationMock; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + @Before + public void setUpRuntimeData() { + authorizationServiceMock = mock(AuthorizationServiceImpl.class); + identityServiceMock = mock(IdentityServiceImpl.class); + processEngineConfigurationMock = mock(ProcessEngineConfigurationImpl.class); + + when(processEngine.getAuthorizationService()).thenReturn(authorizationServiceMock); + when(processEngine.getIdentityService()).thenReturn(identityServiceMock); + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationMock); + when(processEngineConfigurationMock.getPermissionProvider()).thenReturn(new DefaultPermissionProvider()); + } + + @Test + public void testIsUserAuthorizedTrue() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource)).thenReturn(true); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(true)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testIsUserAuthorizedFalse() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource)).thenReturn(false); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(false)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void testIsUserAuthorizedBatchResource() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + String resourceName = BATCH.resourceName(); + int resourceType = BATCH.resourceType(); + ResourceUtil resource = new ResourceUtil(resourceName, resourceType); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, resourceType); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource)).thenReturn(true); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", resourceName) + .queryParam("resourceType", resourceType) + .then().expect().statusCode(Status.OK.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(resourceName)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(true)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void testIsUserAuthorizedProcessDefinitionResource() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + String resourceName = PROCESS_DEFINITION.resourceName(); + int resourceType = PROCESS_DEFINITION.resourceType(); + ResourceUtil resource = new ResourceUtil(resourceName, resourceType); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, resourceType); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource)).thenReturn(false); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", resourceName) + .queryParam("resourceType", resourceType) + .then().expect().statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(resourceName)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(false)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testIsUserAuthorizedProcessInstanceResource() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + int resourceType = PROCESS_INSTANCE.resourceType(); + String resourceName = PROCESS_INSTANCE.resourceName(); + ResourceUtil resource = new ResourceUtil(resourceName, resourceType); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, resourceType); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource)).thenReturn(true); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", resourceName) + .queryParam("resourceType", resourceType) + .then().expect().statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(resourceName)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(true)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testIsUserAuthorizedTaskResource() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + int resourceType = TASK.resourceType(); + String resourceName = TASK.resourceName(); + ResourceUtil resource = new ResourceUtil(resourceName, resourceType); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, resourceType); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource)).thenReturn(true); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", resourceName) + .queryParam("resourceType", resourceType) + .then().expect().statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(resourceName)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(true)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testIsUserAuthorizedWithUserIdTrue() { + + List currentUserGroups = new ArrayList(); + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, currentUserGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + + List userToCheckGroups = setupGroupQueryMock(); + + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, currentUserGroups, Permissions.READ, Resources.AUTHORIZATION)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID2, userToCheckGroups, permission, resource)).thenReturn(true); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .queryParam("userId", MockProvider.EXAMPLE_USER_ID2) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(true)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, currentUserGroups, Permissions.READ, Resources.AUTHORIZATION); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID2, userToCheckGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void testIsUserAuthorizedWithUserIdFalse() { + + List currentUserGroups = new ArrayList(); + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, currentUserGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + + List userToCheckGroups = setupGroupQueryMock(); + + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, currentUserGroups, Permissions.READ, Resources.AUTHORIZATION)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID2, userToCheckGroups, permission, resource)).thenReturn(false); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .queryParam("userId", MockProvider.EXAMPLE_USER_ID2) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME)) + .body("resourceId", equalTo(null)) + .body("authorized", equalTo(false)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, currentUserGroups, Permissions.READ, Resources.AUTHORIZATION); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID2, userToCheckGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void testIsUserAuthorizedWithUserIdNoReadPermission() { + + List currentUserGroups = new ArrayList(); + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, currentUserGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + + List userToCheckGroups = setupGroupQueryMock(); + + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, currentUserGroups, Permissions.READ, Resources.AUTHORIZATION)).thenReturn(false); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .queryParam("userId", MockProvider.EXAMPLE_USER_ID2) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("You must have READ permission for Authorization resource.")) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, currentUserGroups, Permissions.READ, Resources.AUTHORIZATION); + verify(authorizationServiceMock, never()).isUserAuthorized(MockProvider.EXAMPLE_USER_ID2, userToCheckGroups, permission, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void testIsUserAuthorizedNotValidPermission() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + String resourceName = BATCH.resourceName(); + int resourceType = BATCH.resourceType(); + ResourceUtil resource = new ResourceUtil(resourceName, resourceType); + + // ACCESS permission is not valid for BATCH + + given() + .queryParam("permissionName", Permissions.ACCESS.name()) + .queryParam("resourceName", resourceName) + .queryParam("resourceType", resourceType) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo("The permission 'ACCESS' is not valid for 'BATCH' resource type.")) + .when() + .get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(0)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, Permissions.ACCESS, resource); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void testIsUserAuthorizedResourceIdTrue() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource, MockProvider.EXAMPLE_RESOURCE_ID)).thenReturn(true); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .queryParam("resourceId", MockProvider.EXAMPLE_RESOURCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME)) + .body("resourceId", equalTo(MockProvider.EXAMPLE_RESOURCE_ID)) + .body("authorized", equalTo(true)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource, MockProvider.EXAMPLE_RESOURCE_ID); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testIsUserAuthorizedResourceIdFalse() { + + List exampleGroups = new ArrayList(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, exampleGroups); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource, MockProvider.EXAMPLE_RESOURCE_ID)).thenReturn(false); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .queryParam("resourceId", MockProvider.EXAMPLE_RESOURCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()).contentType(MediaType.APPLICATION_JSON) + .body("permissionName", equalTo(MockProvider.EXAMPLE_PERMISSION_NAME)) + .body("resourceName", equalTo(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME)) + .body("resourceId", equalTo(MockProvider.EXAMPLE_RESOURCE_ID)) + .body("authorized", equalTo(false)) + .when().get(AUTH_CHECK_PATH); + + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource, MockProvider.EXAMPLE_RESOURCE_ID); + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + @SuppressWarnings("unchecked") + public void testIsUserAuthorizedNoAuthentication() { + + List exampleGroups = new ArrayList(); + + when(identityServiceMock.getCurrentAuthentication()).thenReturn(null); + + ResourceUtil resource = new ResourceUtil(MockProvider.EXAMPLE_RESOURCE_TYPE_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + Permission permission = getPermissionProvider().getPermissionForName(MockProvider.EXAMPLE_PERMISSION_NAME, MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, exampleGroups, permission, resource)).thenReturn(false); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .then().expect().statusCode(Status.UNAUTHORIZED.getStatusCode()) + .when().get(AUTH_CHECK_PATH); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + verify(authorizationServiceMock, never()).isUserAuthorized(any(String.class), any(List.class), any(Permission.class), any(Resource.class)); + verify(authorizationServiceMock, never()).isUserAuthorized(any(String.class), any(List.class), any(Permission.class), any(Resource.class), any(String.class)); + + } + + @Test + @SuppressWarnings("unchecked") + public void testIsUserAuthorizedBadRequests() { + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(AUTH_CHECK_PATH); + + given() + .queryParam("permissionName", MockProvider.EXAMPLE_PERMISSION_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(AUTH_CHECK_PATH); + + given() + .queryParam("resourceName", MockProvider.EXAMPLE_RESOURCE_TYPE_NAME) + .queryParam("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(AUTH_CHECK_PATH); + + verify(identityServiceMock, never()).getCurrentAuthentication(); + verify(authorizationServiceMock, never()).isUserAuthorized(any(String.class), any(List.class), any(Permission.class), any(Resource.class)); + verify(authorizationServiceMock, never()).isUserAuthorized(any(String.class), any(List.class), any(Permission.class), any(Resource.class), any(String.class)); + + } + + @Test + public void testCreateGlobalAuthorization() { + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + when(authorizationServiceMock.createNewAuthorization(Authorization.AUTH_TYPE_GLOBAL)).thenReturn(authorization); + when(authorizationServiceMock.saveAuthorization(authorization)).thenReturn(authorization); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + given() + .body(dto).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(AUTH_CREATE_PATH); + + verify(authorizationServiceMock).createNewAuthorization(Authorization.AUTH_TYPE_GLOBAL); + verify(authorization).setUserId(Authorization.ANY); + verify(authorization, times(4)).setResourceType(authorization.getAuthorizationType()); + verify(authorization, times(2)).setResourceId(authorization.getResourceId()); + verify(authorization, times(2)).setPermissions(authorization.getPermissions(Permissions.values())); + verify(authorizationServiceMock).saveAuthorization(authorization); + } + + @Test + public void testCreateGrantAuthorization() { + + Authorization authorization = MockProvider.createMockGrantAuthorization(); + when(authorizationServiceMock.createNewAuthorization(Authorization.AUTH_TYPE_GRANT)).thenReturn(authorization); + when(authorizationServiceMock.saveAuthorization(authorization)).thenReturn(authorization); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + given() + .body(dto).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(AUTH_CREATE_PATH); + + verify(authorizationServiceMock).createNewAuthorization(Authorization.AUTH_TYPE_GRANT); + verify(authorization, times(2)).setUserId(authorization.getUserId()); + verify(authorization, times(4)).setResourceType(authorization.getAuthorizationType()); + verify(authorization, times(2)).setResourceId(authorization.getResourceId()); + verify(authorization, times(2)).setPermissions(authorization.getPermissions(Permissions.values())); + verify(authorizationServiceMock).saveAuthorization(authorization); + } + + @Test + public void testCreateRevokeAuthorization() { + + Authorization authorization = MockProvider.createMockRevokeAuthorization(); + when(authorizationServiceMock.createNewAuthorization(Authorization.AUTH_TYPE_REVOKE)).thenReturn(authorization); + when(authorizationServiceMock.saveAuthorization(authorization)).thenReturn(authorization); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + given() + .body(dto).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(AUTH_CREATE_PATH); + + verify(authorizationServiceMock).createNewAuthorization(Authorization.AUTH_TYPE_REVOKE); + verify(authorization, times(2)).setUserId(authorization.getUserId()); + verify(authorization, times(4)).setResourceType(authorization.getAuthorizationType()); + verify(authorization, times(2)).setResourceId(authorization.getResourceId()); + verify(authorization, times(2)).setPermissions(authorization.getPermissions(Permissions.values())); + verify(authorizationServiceMock).saveAuthorization(authorization); + } + + @Test + public void testCreateAuthorizationThrowsAuthorizationException() { + String message = "expected authorization exception"; + when(authorizationServiceMock.createNewAuthorization(Authorization.AUTH_TYPE_GRANT)).thenThrow(new AuthorizationException(message)); + + Authorization authorization = MockProvider.createMockGrantAuthorization(); + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + given() + .body(dto) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(AUTH_CREATE_PATH); + } + + @Test + public void testCreateAuthorizationNotValidPermission() { + Authorization authorization = MockProvider.createMockGrantAuthorization(); + when(authorizationServiceMock.createNewAuthorization(Authorization.AUTH_TYPE_GRANT)).thenReturn(authorization); + + Map jsonBody = new HashMap(); + + jsonBody.put("type", Authorization.AUTH_TYPE_GRANT); + jsonBody.put("permissions", Arrays.asList(Permissions.READ_INSTANCE.name())); + jsonBody.put("userId", MockProvider.EXAMPLE_USER_ID + ","+MockProvider.EXAMPLE_USER_ID2); + jsonBody.put("groupId", MockProvider.EXAMPLE_GROUP_ID+","+MockProvider.EXAMPLE_GROUP_ID2); + jsonBody.put("resourceType", Resources.TASK.resourceType()); + jsonBody.put("resourceId", MockProvider.EXAMPLE_RESOURCE_ID); + + // READ_INSTANCE permission is not valid for TASK + + given() + .body(jsonBody) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo("The permission 'READ_INSTANCE' is not valid for 'TASK' resource type.")) + .when() + .post(AUTH_CREATE_PATH); + + verify(authorizationServiceMock, times(1)).createNewAuthorization(Authorization.AUTH_TYPE_GRANT); + verify(authorizationServiceMock, never()).saveAuthorization(authorization); + } + + @Test + public void testSaveAuthorizationThrowsAuthorizationException() { + String message = "expected authorization exception"; + when(authorizationServiceMock.saveAuthorization(any(Authorization.class))).thenThrow(new AuthorizationException(message)); + + Authorization authorization = MockProvider.createMockGrantAuthorization(); + when(authorizationServiceMock.createNewAuthorization(Authorization.AUTH_TYPE_GRANT)).thenReturn(authorization); + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + given() + .body(dto) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(AUTH_CREATE_PATH); + } + + @Test + public void testDeleteAuthorization() { + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(AUTH_RESOURCE_PATH); + + verify(authorizationQuery).authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID); + verify(authorizationServiceMock).deleteAuthorization(MockProvider.EXAMPLE_AUTHORIZATION_ID); + + } + + @Test + public void testDeleteNonExistingAuthorization() { + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("message", equalTo("Authorization with id "+MockProvider.EXAMPLE_AUTHORIZATION_ID+" does not exist.")) + .when() + .delete(AUTH_RESOURCE_PATH); + + verify(authorizationServiceMock, never()).deleteAuthorization(MockProvider.EXAMPLE_AUTHORIZATION_ID); + + } + + @Test + public void testDeleteAuthorizationThrowsAuthorizationException() { + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + String message = "expected authorization exception"; + doThrow(new AuthorizationException(message)).when(authorizationServiceMock).deleteAuthorization(MockProvider.EXAMPLE_AUTHORIZATION_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(AUTH_RESOURCE_PATH); + } + + @Test + public void testUpdateAuthorization() { + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .body(dto).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(AUTH_RESOURCE_PATH); + + verify(authorizationQuery).authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID); + + verify(authorization).setGroupId(dto.getGroupId()); + verify(authorization).setUserId(dto.getUserId()); + verify(authorization).setResourceId(dto.getResourceId()); + verify(authorization).setResourceType(dto.getResourceType()); + + verify(authorizationServiceMock).saveAuthorization(authorization); + + } + + @Test + public void testUpdateNonExistingAuthorization() { + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(null); + + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .body(dto).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("message", equalTo("Authorization with id "+MockProvider.EXAMPLE_AUTHORIZATION_ID+" does not exist.")) + .when() + .put(AUTH_RESOURCE_PATH); + + verify(authorizationServiceMock, never()).saveAuthorization(authorization); + + } + + @Test + public void testUpdateAuthorizationThrowsAuthorizationException() { + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + AuthorizationDto dto = AuthorizationDto.fromAuthorization(authorization, processEngineConfigurationMock); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + String message = "expected authorization exception"; + when(authorizationServiceMock.saveAuthorization(any(Authorization.class))).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .body(dto).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(AUTH_RESOURCE_PATH); + } + + @Test + public void testUpdateAuthorizationNotValidPermission() { + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + Map jsonBody = new HashMap(); + + jsonBody.put("permissions", Arrays.asList(Permissions.TASK_WORK.name())); + jsonBody.put("userId", MockProvider.EXAMPLE_USER_ID + ","+MockProvider.EXAMPLE_USER_ID2); + jsonBody.put("groupId", MockProvider.EXAMPLE_GROUP_ID+","+MockProvider.EXAMPLE_GROUP_ID2); + jsonBody.put("resourceType", Resources.PROCESS_INSTANCE.resourceType()); + jsonBody.put("resourceId", MockProvider.EXAMPLE_RESOURCE_ID); + + // READ_INSTANCE permission is not valid for TASK + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .body(jsonBody).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo("The permission 'TASK_WORK' is not valid for 'PROCESS_INSTANCE' resource type.")) + .when() + .put(AUTH_RESOURCE_PATH); + + verify(authorizationServiceMock, never()).saveAuthorization(authorization); + } + + @Test + public void testGetAuthorizationById() { + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body("id", equalTo(authorization.getId())) + .body("type", equalTo(authorization.getAuthorizationType())) + .body("permissions[0]", equalTo(Permissions.READ.getName())) + .body("permissions[1]", equalTo(Permissions.UPDATE.getName())) + .body("userId", equalTo(authorization.getUserId())) + .body("groupId", equalTo(authorization.getGroupId())) + .body("resourceType", equalTo(authorization.getResourceType())) + .body("resourceId", equalTo(authorization.getResourceId())) + .body("removalTime", equalTo(MockProvider.EXAMPLE_AUTH_REMOVAL_TIME)) + .body("rootProcessInstanceId", equalTo(authorization.getRootProcessInstanceId())) + .when() + .get(AUTH_RESOURCE_PATH); + + } + + @Test + public void testGetNonExistingAuthorizationById() { + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("message", equalTo("Authorization with id "+MockProvider.EXAMPLE_AUTHORIZATION_ID+" does not exist.")) + .when() + .get(AUTH_RESOURCE_PATH); + + } + + @Test + public void testAuthenticationRestServiceOptions() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl+"/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl+"/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_PATH); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testAuthenticationRestServiceOptionsWithAuthorizationDisabled() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl + "/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl + "/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_PATH); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testAuthorizationResourceOptions() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH + "/" + MockProvider.EXAMPLE_AUTHORIZATION_ID; + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(null); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullAuthorizationUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullAuthorizationUrl)) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when() + .options(AUTH_RESOURCE_PATH); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + + } + + @Test + public void testAuthorizationResourceOptionsUnauthorized() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH + "/" + MockProvider.EXAMPLE_AUTHORIZATION_ID; + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(false); + + when(processEngine.getProcessEngineConfiguration().isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1]", nullValue()) + .body("links[2]", nullValue()) + + .when() + .options(AUTH_RESOURCE_PATH); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID); + + } + + @Test + public void testAuthorizationResourceOptionsUpdateUnauthorized() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH + "/" + MockProvider.EXAMPLE_AUTHORIZATION_ID; + + Authorization authorization = MockProvider.createMockGlobalAuthorization(); + + AuthorizationQuery authorizationQuery = mock(AuthorizationQuery.class); + when(authorizationServiceMock.createAuthorizationQuery()).thenReturn(authorizationQuery); + when(authorizationQuery.authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(authorizationQuery); + when(authorizationQuery.singleResult()).thenReturn(authorization); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID)).thenReturn(false); + + when(processEngine.getProcessEngineConfiguration().isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullAuthorizationUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2]", nullValue()) + + .when() + .options(AUTH_RESOURCE_PATH); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, AUTHORIZATION, MockProvider.EXAMPLE_AUTHORIZATION_ID); + + } + + @Test + public void testAuthorizationResourceOptionsWithAuthorizationDisabled() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH + "/" + MockProvider.EXAMPLE_AUTHORIZATION_ID; + + when(processEngine.getProcessEngineConfiguration().isAuthorizationEnabled()).thenReturn(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_AUTHORIZATION_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullAuthorizationUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullAuthorizationUrl)) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when() + .options(AUTH_RESOURCE_PATH); + + verifyNoAuthorizationCheckPerformed(); + } + + protected void verifyNoAuthorizationCheckPerformed() { + verify(identityServiceMock, times(0)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(0)).isUserAuthorized(anyString(), anyList(), any(Permission.class), any(Resource.class)); + } + + + protected PermissionProvider getPermissionProvider() { + return processEngineConfigurationMock.getPermissionProvider(); + } + + protected List setupGroupQueryMock() { + GroupQuery mockGroupQuery = mock(GroupQuery.class); + List groupMocks = MockProvider.createMockGroups(); + when(identityServiceMock.createGroupQuery()).thenReturn(mockGroupQuery); + when(mockGroupQuery.groupMember(anyString())).thenReturn(mockGroupQuery); + when(mockGroupQuery.unlimitedList()).thenReturn(groupMocks); + List groupIds = new ArrayList(); + for (Group group : groupMocks) { + groupIds.add(group.getId()); + } + return groupIds; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AuthorizationRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AuthorizationRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..28e333d7788b423981fece5404512ef707d5756c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/AuthorizationRestServiceQueryTest.java @@ -0,0 +1,242 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.AuthorizationQuery; +import org.camunda.bpm.engine.authorization.Permissions; +import org.camunda.bpm.engine.impl.AuthorizationServiceImpl; +import org.camunda.bpm.engine.impl.IdentityServiceImpl; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.cfg.auth.DefaultPermissionProvider; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +/** + * @author Daniel Meyer + * + */ +public class AuthorizationRestServiceQueryTest extends AbstractRestServiceTest { + + protected static final String SERVICE_PATH = TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH; + protected static final String SERVICE_COUNT_PATH = TEST_RESOURCE_ROOT_PATH + AuthorizationRestService.PATH+"/count"; + + protected AuthorizationService authorizationServiceMock; + protected IdentityService identityServiceMock; + protected ProcessEngineConfigurationImpl processEngineConfigurationMock; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + @Before + public void setUpRuntimeData() { + authorizationServiceMock = mock(AuthorizationServiceImpl.class); + identityServiceMock = mock(IdentityServiceImpl.class); + processEngineConfigurationMock = mock(ProcessEngineConfigurationImpl.class); + + when(processEngine.getAuthorizationService()).thenReturn(authorizationServiceMock); + when(processEngine.getIdentityService()).thenReturn(identityServiceMock); + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationMock); + when(processEngineConfigurationMock.getPermissionProvider()).thenReturn(new DefaultPermissionProvider()); + } + + private AuthorizationQuery setUpMockQuery(List list) { + AuthorizationQuery query = mock(AuthorizationQuery.class); + when(query.list()).thenReturn(list); + when(query.count()).thenReturn((long) list.size()); + + when(processEngine.getAuthorizationService().createAuthorizationQuery()).thenReturn(query); + + return query; + } + + @Test + public void testEmptyQuery() { + + setUpMockQuery(MockProvider.createMockAuthorizations()); + + String queryKey = ""; + given().queryParam("name", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(SERVICE_PATH); + + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "resourceType") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(SERVICE_PATH); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(SERVICE_PATH); + } + + @Test + public void testNoParametersQuery() { + + AuthorizationQuery mockQuery = setUpMockQuery(MockProvider.createMockAuthorizations()); + + expect().statusCode(Status.OK.getStatusCode()).when().get(SERVICE_PATH); + + verify(mockQuery).list(); + verifyNoMoreInteractions(mockQuery); + } + + @Test + public void testSimpleAuthorizationQuery() { + + List mockAuthorizations = MockProvider.createMockGlobalAuthorizations(); + AuthorizationQuery mockQuery = setUpMockQuery(mockAuthorizations); + + Response response = given().queryParam("type", Authorization.AUTH_TYPE_GLOBAL) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(SERVICE_PATH); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).authorizationType(Authorization.AUTH_TYPE_GLOBAL); + inOrder.verify(mockQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one authorization returned.", 1, instances.size()); + Assert.assertNotNull("The returned authorization should not be null.", instances.get(0)); + + Authorization mockAuthorization = mockAuthorizations.get(0); + + Assert.assertEquals(mockAuthorization.getId(), from(content).getString("[0].id")); + Assert.assertEquals(mockAuthorization.getAuthorizationType(), from(content).getInt("[0].type")); + Assert.assertEquals(Permissions.READ.getName(), from(content).getString("[0].permissions[0]")); + Assert.assertEquals(Permissions.UPDATE.getName(), from(content).getString("[0].permissions[1]")); + Assert.assertEquals(mockAuthorization.getUserId(), from(content).getString("[0].userId")); + Assert.assertEquals(mockAuthorization.getGroupId(), from(content).getString("[0].groupId")); + Assert.assertEquals(mockAuthorization.getResourceType(), from(content).getInt("[0].resourceType")); + Assert.assertEquals(mockAuthorization.getResourceId(), from(content).getString("[0].resourceId")); + Assert.assertEquals(mockAuthorization.getRemovalTime(), + DateTimeUtil.parseDate(from(content).getString("[0].removalTime"))); + Assert.assertEquals(mockAuthorization.getRootProcessInstanceId(), + from(content).getString("[0].rootProcessInstanceId")); + + } + + @Test + public void testCompleteGetParameters() { + + List mockAuthorizations = MockProvider.createMockGlobalAuthorizations(); + AuthorizationQuery mockQuery = setUpMockQuery(mockAuthorizations); + + Map queryParameters = getCompleteStringQueryParameters(); + + RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE); + for (Entry paramEntry : queryParameters.entrySet()) { + requestSpecification.param(paramEntry.getKey(), paramEntry.getValue()); + } + + requestSpecification.expect().statusCode(Status.OK.getStatusCode()) + .when().get(SERVICE_PATH); + + verify(mockQuery).authorizationId(MockProvider.EXAMPLE_AUTHORIZATION_ID); + verify(mockQuery).authorizationType(MockProvider.EXAMPLE_AUTHORIZATION_TYPE); + verify(mockQuery).userIdIn(new String[]{MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_ID2}); + verify(mockQuery).groupIdIn(new String[]{MockProvider.EXAMPLE_GROUP_ID, MockProvider.EXAMPLE_GROUP_ID2}); + verify(mockQuery).resourceType(MockProvider.EXAMPLE_RESOURCE_TYPE_ID); + verify(mockQuery).resourceId(MockProvider.EXAMPLE_RESOURCE_ID); + + verify(mockQuery).list(); + + } + + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("id", MockProvider.EXAMPLE_AUTHORIZATION_ID); + parameters.put("type", MockProvider.EXAMPLE_AUTHORIZATION_TYPE_STRING); + parameters.put("userIdIn", MockProvider.EXAMPLE_USER_ID + ","+MockProvider.EXAMPLE_USER_ID2); + parameters.put("groupIdIn", MockProvider.EXAMPLE_GROUP_ID+","+MockProvider.EXAMPLE_GROUP_ID2); + parameters.put("resourceType", MockProvider.EXAMPLE_RESOURCE_TYPE_ID_STRING); + parameters.put("resourceId", MockProvider.EXAMPLE_RESOURCE_ID); + + return parameters; + } + + @Test + public void testQueryCount() { + + AuthorizationQuery mockQuery = setUpMockQuery(MockProvider.createMockAuthorizations()); + + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(3)) + .when().get(SERVICE_COUNT_PATH); + + verify(mockQuery).count(); + } + + @Test + public void testSuccessfulPagination() { + + AuthorizationQuery mockQuery = setUpMockQuery(MockProvider.createMockAuthorizations()); + + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(SERVICE_PATH); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5e8784d47df4f08b0e8d0bc9e83e1592900a5a39 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceInteractionTest.java @@ -0,0 +1,338 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static java.util.Collections.singletonMap; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.util.JsonPathUtil.from; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.batch.BatchQuery; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class BatchRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String BATCH_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/batch"; + protected static final String SINGLE_BATCH_RESOURCE_URL = BATCH_RESOURCE_URL + "/{id}"; + protected static final String SUSPENDED_BATCH_RESOURCE_URL = SINGLE_BATCH_RESOURCE_URL + "/suspended"; + + protected ManagementService managementServiceMock; + protected BatchQuery queryMock; + + @Before + public void setUpBatchQueryMock() { + Batch batchMock = MockProvider.createMockBatch(); + + queryMock = mock(BatchQuery.class); + when(queryMock.batchId(eq(MockProvider.EXAMPLE_BATCH_ID))).thenReturn(queryMock); + when(queryMock.singleResult()).thenReturn(batchMock); + + managementServiceMock = mock(ManagementService.class); + when(managementServiceMock.createBatchQuery()).thenReturn(queryMock); + + when(processEngine.getManagementService()).thenReturn(managementServiceMock); + } + + @Test + public void testGetBatch() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_BATCH_RESOURCE_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + inOrder.verify(queryMock).singleResult(); + inOrder.verifyNoMoreInteractions(); + + verifyBatchJson(response.asString()); + } + + @Test + public void testGetNonExistingBatch() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + BatchQuery batchQuery = mock(BatchQuery.class); + when(batchQuery.batchId(nonExistingId)).thenReturn(batchQuery); + when(batchQuery.singleResult()).thenReturn(null); + when(managementServiceMock.createBatchQuery()).thenReturn(batchQuery); + + given() + .pathParam("id", nonExistingId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Batch with id '" + nonExistingId + "' does not exist")) + .when() + .get(SINGLE_BATCH_RESOURCE_URL); + } + + @Test + public void deleteBatch() { + given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_BATCH_RESOURCE_URL); + + verify(managementServiceMock).deleteBatch(eq(MockProvider.EXAMPLE_BATCH_ID), eq(false)); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void deleteBatchNotCascade() { + given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .queryParam("cascade", false) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_BATCH_RESOURCE_URL); + + verify(managementServiceMock).deleteBatch(eq(MockProvider.EXAMPLE_BATCH_ID), eq(false)); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void deleteBatchCascade() { + given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .queryParam("cascade", true) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_BATCH_RESOURCE_URL); + + verify(managementServiceMock).deleteBatch(eq(MockProvider.EXAMPLE_BATCH_ID), eq(true)); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void deleteNonExistingBatch() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + + doThrow(new BadUserRequestException("Batch for id '" + nonExistingId + "' cannot be found")) + .when(managementServiceMock).deleteBatch(eq(nonExistingId), eq(false)); + + given() + .pathParam("id", nonExistingId) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Unable to delete batch with id '" + nonExistingId + "'")) + .when() + .delete(SINGLE_BATCH_RESOURCE_URL); + } + + @Test + public void deleteNonExistingBatchNotCascade() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + + doThrow(new BadUserRequestException("Batch for id '" + nonExistingId + "' cannot be found")) + .when(managementServiceMock).deleteBatch(eq(nonExistingId), eq(false)); + + given() + .pathParam("id", nonExistingId) + .queryParam("cascade", false) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Unable to delete batch with id '" + nonExistingId + "'")) + .when() + .delete(SINGLE_BATCH_RESOURCE_URL); + } + + @Test + public void deleteNonExistingBatchCascade() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + + doThrow(new BadUserRequestException("Batch for id '" + nonExistingId + "' cannot be found")) + .when(managementServiceMock).deleteBatch(eq(nonExistingId), eq(true)); + + given() + .pathParam("id", nonExistingId) + .queryParam("cascade", true) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Unable to delete batch with id '" + nonExistingId + "'")) + .when() + .delete(SINGLE_BATCH_RESOURCE_URL); + } + + @Test + public void suspendBatch() { + given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .contentType(ContentType.JSON) + .body(singletonMap("suspended", true)) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SUSPENDED_BATCH_RESOURCE_URL); + + verify(managementServiceMock).suspendBatchById(eq(MockProvider.EXAMPLE_BATCH_ID)); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void suspendNonExistingBatch() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + + doThrow(new BadUserRequestException("Batch for id '" + nonExistingId + "' cannot be found")) + .when(managementServiceMock).suspendBatchById(eq(nonExistingId)); + + given() + .pathParam("id", nonExistingId) + .contentType(ContentType.JSON) + .body(singletonMap("suspended", true)) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Unable to suspend batch with id '" + nonExistingId + "'")) + .when() + .put(SUSPENDED_BATCH_RESOURCE_URL); + } + + @Test + public void suspendBatchUnauthorized() { + String batchId = MockProvider.EXAMPLE_BATCH_ID; + String expectedMessage = "The user with id 'userId' does not have 'UPDATE' permission on resource '" + batchId + "' of type 'Batch'."; + + doThrow(new AuthorizationException(expectedMessage)) + .when(managementServiceMock).suspendBatchById(eq(batchId)); + + given() + .pathParam("id", batchId) + .contentType(ContentType.JSON) + .body(singletonMap("suspended", true)) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(SUSPENDED_BATCH_RESOURCE_URL); + + } + + @Test + public void activateBatch() { + given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .contentType(ContentType.JSON) + .body(singletonMap("suspended", false)) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SUSPENDED_BATCH_RESOURCE_URL); + + verify(managementServiceMock).activateBatchById(eq(MockProvider.EXAMPLE_BATCH_ID)); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void activateNonExistingBatch() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + + doThrow(new BadUserRequestException("Batch for id '" + nonExistingId + "' cannot be found")) + .when(managementServiceMock).activateBatchById(eq(nonExistingId)); + + given() + .pathParam("id", nonExistingId) + .contentType(ContentType.JSON) + .body(singletonMap("suspended", false)) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Unable to activate batch with id '" + nonExistingId + "'")) + .when() + .put(SUSPENDED_BATCH_RESOURCE_URL); + } + + @Test + public void activateBatchUnauthorized() { + String batchId = MockProvider.EXAMPLE_BATCH_ID; + String expectedMessage = "The user with id 'userId' does not have 'UPDATE' permission on resource '" + batchId + "' of type 'Batch'."; + + doThrow(new AuthorizationException(expectedMessage)) + .when(managementServiceMock).activateBatchById(eq(batchId)); + + given() + .pathParam("id", batchId) + .contentType(ContentType.JSON) + .body(singletonMap("suspended", false)) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(SUSPENDED_BATCH_RESOURCE_URL); + + } + + protected void verifyBatchJson(String batchJson) { + BatchDto batch = from(batchJson).getObject("", BatchDto.class); + String returnedStartTime = from(batchJson).getString("startTime"); + String returnedExecStartTime = from(batchJson).getString("executionStartTime"); + + assertNotNull("The returned batch should not be null.", batch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId()); + assertEquals(MockProvider.EXAMPLE_USER_ID, batch.getCreateUserId()); + assertEquals(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME, returnedStartTime); + assertEquals(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME, returnedExecStartTime); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f2b34b9dcd8dc79710332f6f6b254fadeb291e5f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceQueryTest.java @@ -0,0 +1,288 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.util.JsonPathUtil.from; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.batch.BatchQuery; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class BatchRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String BATCH_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/batch"; + protected static final String BATCH_QUERY_COUNT_URL = BATCH_RESOURCE_URL + "/count"; + + protected BatchQuery queryMock; + + @Before + public void setUpBatchQueryMock() { + List mockedBatches = MockProvider.createMockBatches(); + queryMock = mock(BatchQuery.class); + + when(queryMock.list()).thenReturn(mockedBatches); + when(queryMock.count()).thenReturn((long) mockedBatches.size()); + + when(processEngine.getManagementService().createBatchQuery()).thenReturn(queryMock); + } + + @Test + public void testNoParametersQuery() { + Response response = given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_RESOURCE_URL); + + verify(queryMock).list(); + verifyNoMoreInteractions(queryMock); + + verifyBatchListJson(response.asString()); + } + + @Test + public void testUnknownQueryParameter() { + Response response = given() + .queryParam("unknown", "unknown") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_RESOURCE_URL); + + verify(queryMock, never()).batchId(anyString()); + verify(queryMock).list(); + + verifyBatchListJson(response.asString()); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "batchId") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(BATCH_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(BATCH_RESOURCE_URL); + } + + @Test + public void testBatchQueryByBatchId() { + Response response = given() + .queryParam("batchId", MockProvider.EXAMPLE_BATCH_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_RESOURCE_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + inOrder.verify(queryMock).list(); + inOrder.verifyNoMoreInteractions(); + + verifyBatchListJson(response.asString()); + } + + @Test + public void testQueryActiveBatches() { + Response response = given() + .queryParam("suspended", false) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_RESOURCE_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).active(); + inOrder.verify(queryMock).list(); + inOrder.verifyNoMoreInteractions(); + + verifyBatchListJson(response.asString()); + } + + @Test + public void testFullBatchQuery() { + Response response = given() + .queryParams(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_RESOURCE_URL); + + verifyQueryParameterInvocations(); + verify(queryMock).list(); + verifyNoMoreInteractions(queryMock); + + verifyBatchListJson(response.asString()); + } + + @Test + public void testQueryCount() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(BATCH_QUERY_COUNT_URL); + + verify(queryMock).count(); + verifyNoMoreInteractions(queryMock); + } + + @Test + public void testFullQueryCount() { + given() + .params(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(BATCH_QUERY_COUNT_URL); + + verifyQueryParameterInvocations(); + verify(queryMock).count(); + verifyNoMoreInteractions(queryMock); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("batchId", "desc", Status.OK); + inOrder.verify(queryMock).orderById(); + inOrder.verify(queryMock).desc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("batchId", "asc", Status.OK); + inOrder.verify(queryMock).orderById(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(queryMock).orderByTenantId(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(queryMock).orderByTenantId(); + inOrder.verify(queryMock).desc(); + } + + private void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(BATCH_RESOURCE_URL); + } + + protected Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("batchId", MockProvider.EXAMPLE_BATCH_ID); + parameters.put("type", MockProvider.EXAMPLE_BATCH_TYPE); + parameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID + "," + MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + parameters.put("withoutTenantId", true); + parameters.put("suspended", true); + + return parameters; + } + + protected void verifyQueryParameterInvocations() { + verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + verify(queryMock).type(MockProvider.EXAMPLE_BATCH_TYPE); + verify(queryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(queryMock).withoutTenantId(); + verify(queryMock).suspended(); + } + + protected void verifyBatchListJson(String batchListJson) { + List batches = from(batchListJson).get(); + assertEquals("There should be one batch returned.", 1, batches.size()); + + BatchDto batch = from(batchListJson).getObject("[0]", BatchDto.class); + String returnedStartTime = from(batchListJson).getString("[0].startTime"); + + assertNotNull("The returned batch should not be null.", batch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_CREATED, batch.getJobsCreated()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId()); + assertEquals(MockProvider.EXAMPLE_USER_ID, batch.getCreateUserId()); + assertEquals(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME, returnedStartTime); + assertTrue(batch.isSuspended()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceStatisticsTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceStatisticsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5e585b3305fd1e55eceaffe603ae1fbda1773d56 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/BatchRestServiceStatisticsTest.java @@ -0,0 +1,337 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.util.JsonPathUtil.from; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.batch.BatchStatistics; +import org.camunda.bpm.engine.batch.BatchStatisticsQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.dto.batch.BatchStatisticsDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class BatchRestServiceStatisticsTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String BATCH_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/batch"; + protected static final String BATCH_STATISTICS_URL = BATCH_RESOURCE_URL + "/statistics"; + protected static final String BATCH_STATISTICS_COUNT_URL = BATCH_STATISTICS_URL + "/count"; + + protected BatchStatisticsQuery queryMock; + protected List mockBatchStatisticsList; + + @Before + public void setUpBatchStatisticsMock() { + mockBatchStatisticsList = MockProvider.createMockBatchStatisticsList(); + + queryMock = mock(BatchStatisticsQuery.class); + + when(queryMock.list()).thenReturn(mockBatchStatisticsList); + when(queryMock.count()).thenReturn((long) mockBatchStatisticsList.size()); + + when(processEngine.getManagementService().createBatchStatisticsQuery()).thenReturn(queryMock); + } + + @Test + public void testQuery() { + Response response = given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_STATISTICS_URL); + + verify(queryMock).list(); + verifyNoMoreInteractions(queryMock); + + verifyBatchStatisticsListJson(response.asString()); + } + + @Test + public void testUnknownQueryParameter() { + Response response = given() + .queryParam("unknown", "unknown") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_STATISTICS_URL); + + verify(queryMock, never()).batchId(anyString()); + verify(queryMock).list(); + verifyNoMoreInteractions(queryMock); + + verifyBatchStatisticsListJson(response.asString()); + } + + @Test + public void testBatchQueryByBatchId() { + Response response = given() + .queryParam("batchId", MockProvider.EXAMPLE_BATCH_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_STATISTICS_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + inOrder.verify(queryMock).list(); + inOrder.verifyNoMoreInteractions(); + + verifyBatchStatisticsListJson(response.asString()); + } + + @Test + public void testQueryActiveBatches() { + Response response = given() + .queryParam("suspended", false) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_STATISTICS_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).active(); + inOrder.verify(queryMock).list(); + inOrder.verifyNoMoreInteractions(); + + verifyBatchStatisticsListJson(response.asString()); + } + + @Test + public void testFullBatchQuery() { + Response response = given() + .queryParams(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_STATISTICS_URL); + + verifyQueryParameterInvocations(); + verify(queryMock).list(); + verifyNoMoreInteractions(queryMock); + + verifyBatchStatisticsListJson(response.asString()); + } + + @Test + public void testQueryCount() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(BATCH_STATISTICS_COUNT_URL); + + verify(queryMock).count(); + verifyNoMoreInteractions(queryMock); + } + + @Test + public void testFullQueryCount() { + given() + .params(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(BATCH_STATISTICS_COUNT_URL); + + verifyQueryParameterInvocations(); + verify(queryMock).count(); + verifyNoMoreInteractions(queryMock); + } + + + @Test + public void testQueryPagination() { + when(queryMock.listPage(1, 2)) + .thenReturn(mockBatchStatisticsList); + + Response response = given() + .queryParam("firstResult", 1) + .queryParam("maxResults", 2) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(BATCH_STATISTICS_URL); + + + verify(queryMock).listPage(1, 2); + verifyNoMoreInteractions(queryMock); + + verifyBatchStatisticsListJson(response.asString()); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("batchId", "desc", Status.OK); + inOrder.verify(queryMock).orderById(); + inOrder.verify(queryMock).desc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("batchId", "asc", Status.OK); + inOrder.verify(queryMock).orderById(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(queryMock).orderByTenantId(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(queryMock).orderByTenantId(); + inOrder.verify(queryMock).desc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("startTime", "asc", Status.OK); + inOrder.verify(queryMock).orderByStartTime(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("startTime", "desc", Status.OK); + inOrder.verify(queryMock).orderByStartTime(); + inOrder.verify(queryMock).desc(); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "batchId") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(BATCH_STATISTICS_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(BATCH_STATISTICS_URL); + } + + protected Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("batchId", MockProvider.EXAMPLE_BATCH_ID); + parameters.put("type", MockProvider.EXAMPLE_BATCH_TYPE); + parameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID + "," + MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + parameters.put("withoutTenantId", true); + parameters.put("suspended", true); + parameters.put("createdBy", MockProvider.EXAMPLE_USER_ID); + parameters.put("startedBefore", MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME); + parameters.put("startedAfter", MockProvider.EXAMPLE_HISTORIC_BATCH_END_TIME); + parameters.put("withFailures", true); + parameters.put("withoutFailures", true); + + return parameters; + } + + protected void verifyQueryParameterInvocations() { + verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + verify(queryMock).type(MockProvider.EXAMPLE_BATCH_TYPE); + verify(queryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(queryMock).withoutTenantId(); + verify(queryMock).suspended(); + verify(queryMock).createdBy(MockProvider.EXAMPLE_USER_ID); + verify(queryMock).startedBefore(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME)); + verify(queryMock).startedAfter(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_END_TIME)); + verify(queryMock).withFailures(); + verify(queryMock).withoutFailures(); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(BATCH_STATISTICS_URL); + } + + protected void verifyBatchStatisticsListJson(String batchStatisticsListJson) { + List batches = from(batchStatisticsListJson).get(); + assertEquals("There should be one batch statistics returned.", 1, batches.size()); + + BatchStatisticsDto batchStatistics = from(batchStatisticsListJson).getObject("[0]", BatchStatisticsDto.class); + String returnedStartTime = from(batchStatisticsListJson).getString("[0].startTime"); + + assertNotNull("The returned batch statistics should not be null.", batchStatistics); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batchStatistics.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batchStatistics.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batchStatistics.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_CREATED, batchStatistics.getJobsCreated()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batchStatistics.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batchStatistics.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batchStatistics.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batchStatistics.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batchStatistics.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batchStatistics.getTenantId()); + assertEquals(MockProvider.EXAMPLE_USER_ID, batchStatistics.getCreateUserId()); + assertEquals(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME, returnedStartTime); + assertEquals(MockProvider.EXAMPLE_BATCH_REMAINING_JOBS, batchStatistics.getRemainingJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_COMPLETED_JOBS, batchStatistics.getCompletedJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_FAILED_JOBS, batchStatistics.getFailedJobs()); + assertTrue(batchStatistics.isSuspended()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseDefinitionRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseDefinitionRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9544a1084a266fc2f3bedbb7df9920c14553154a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseDefinitionRestServiceInteractionTest.java @@ -0,0 +1,711 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.impl.util.ReflectUtil; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.EqualsVariableMap; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.sub.repository.impl.ProcessDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.CaseInstance; +import org.camunda.bpm.engine.runtime.CaseInstanceBuilder; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Roman Smirnov + * + */ +public class CaseDefinitionRestServiceInteractionTest extends AbstractRestServiceTest { + + protected static final String CASE_DEFINITION_URL = TEST_RESOURCE_ROOT_PATH + "/case-definition"; + protected static final String SINGLE_CASE_DEFINITION_URL = CASE_DEFINITION_URL + "/{id}"; + protected static final String SINGLE_CASE_DEFINITION_BY_KEY_URL = CASE_DEFINITION_URL + "/key/{key}"; + protected static final String SINGLE_CASE_DEFINITION_BY_KEY_AND_TENANT_ID_URL = CASE_DEFINITION_URL + "/key/{key}/tenant-id/{tenant-id}"; + + protected static final String XML_DEFINITION_URL = SINGLE_CASE_DEFINITION_URL + "/xml"; + protected static final String XML_DEFINITION_BY_KEY_URL = SINGLE_CASE_DEFINITION_BY_KEY_URL + "/xml"; + + protected static final String CREATE_INSTANCE_URL = SINGLE_CASE_DEFINITION_URL + "/create"; + protected static final String CREATE_INSTANCE_BY_KEY_URL = SINGLE_CASE_DEFINITION_BY_KEY_URL + "/create"; + protected static final String CREATE_INSTANCE_BY_KEY_AND_TENANT_ID_URL = SINGLE_CASE_DEFINITION_BY_KEY_AND_TENANT_ID_URL + "/create"; + + protected static final String DIAGRAM_DEFINITION_URL = SINGLE_CASE_DEFINITION_URL + "/diagram"; + + protected static final String UPDATE_HISTORY_TIME_TO_LIVE_URL = SINGLE_CASE_DEFINITION_URL + "/history-time-to-live"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + private RepositoryService repositoryServiceMock; + private CaseService caseServiceMock; + private CaseDefinitionQuery caseDefinitionQueryMock; + private CaseInstanceBuilder caseInstanceBuilder; + + @Before + public void setUpRuntime() { + CaseDefinition mockCaseDefinition = MockProvider.createMockCaseDefinition(); + + setUpRuntimeData(mockCaseDefinition); + + caseServiceMock = mock(CaseService.class); + + when(processEngine.getCaseService()).thenReturn(caseServiceMock); + + caseInstanceBuilder = mock(CaseInstanceBuilder.class); + CaseInstance mockCaseInstance = MockProvider.createMockCaseInstance(); + + when(caseServiceMock.withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID)).thenReturn(caseInstanceBuilder); + when(caseInstanceBuilder.businessKey(any())).thenReturn(caseInstanceBuilder); + when(caseInstanceBuilder.setVariables(any())).thenReturn(caseInstanceBuilder); + when(caseInstanceBuilder.create()).thenReturn(mockCaseInstance); + } + + private void setUpRuntimeData(CaseDefinition mockCaseDefinition) { + repositoryServiceMock = mock(RepositoryService.class); + + when(processEngine.getRepositoryService()).thenReturn(repositoryServiceMock); + when(repositoryServiceMock.getCaseDefinition(eq(MockProvider.EXAMPLE_CASE_DEFINITION_ID))).thenReturn(mockCaseDefinition); + when(repositoryServiceMock.getCaseModel(eq(MockProvider.EXAMPLE_CASE_DEFINITION_ID))).thenReturn(createMockCaseDefinitionCmmnXml()); + + caseDefinitionQueryMock = mock(CaseDefinitionQuery.class); + when(caseDefinitionQueryMock.caseDefinitionKey(MockProvider.EXAMPLE_CASE_DEFINITION_KEY)).thenReturn(caseDefinitionQueryMock); + when(caseDefinitionQueryMock.tenantIdIn(any())).thenReturn(caseDefinitionQueryMock); + when(caseDefinitionQueryMock.withoutTenantId()).thenReturn(caseDefinitionQueryMock); + when(caseDefinitionQueryMock.latestVersion()).thenReturn(caseDefinitionQueryMock); + when(caseDefinitionQueryMock.singleResult()).thenReturn(mockCaseDefinition); + when(caseDefinitionQueryMock.list()).thenReturn(Collections.singletonList(mockCaseDefinition)); + when(repositoryServiceMock.createCaseDefinitionQuery()).thenReturn(caseDefinitionQueryMock); + } + + private InputStream createMockCaseDefinitionCmmnXml() { + // do not close the input stream, will be done in implementation + InputStream cmmnXmlInputStream = ReflectUtil.getResourceAsStream("cases/case-model.cmmn"); + Assert.assertNotNull(cmmnXmlInputStream); + return cmmnXmlInputStream; + } + + @Test + public void testCaseDefinitionCmmnXmlRetrieval() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(XML_DEFINITION_URL); + + String responseContent = response.asString(); + Assert.assertTrue(responseContent.contains(MockProvider.EXAMPLE_CASE_DEFINITION_ID)); + Assert.assertTrue(responseContent.contains(" emptyList()); + + given() + .pathParam("key", nonExistingKey) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching case definition with key: " + nonExistingKey)) + .when() + .get(SINGLE_CASE_DEFINITION_BY_KEY_URL); + } + + @Test + public void testDefinitionRetrieval_ByKeyAndTenantId() { + CaseDefinition mockDefinition = MockProvider.mockCaseDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(); + setUpRuntimeData(mockDefinition); + + given() + .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_NAME)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_RESOURCE_NAME)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .when() + .get(SINGLE_CASE_DEFINITION_BY_KEY_AND_TENANT_ID_URL); + + verify(caseDefinitionQueryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(repositoryServiceMock).getCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + } + + @Test + public void testNonExistingCaseDefinitionRetrieval_ByKeyAndTenantId() { + String nonExistingKey = "aNonExistingDefinitionKey"; + String nonExistingTenantId = "aNonExistingTenantId"; + + when(repositoryServiceMock.createCaseDefinitionQuery().caseDefinitionKey(nonExistingKey)).thenReturn(caseDefinitionQueryMock); + when(caseDefinitionQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("key", nonExistingKey) + .pathParam("tenant-id", nonExistingTenantId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching case definition with key: " + nonExistingKey + " and tenant-id: " + nonExistingTenantId)) + .when().get(SINGLE_CASE_DEFINITION_BY_KEY_AND_TENANT_ID_URL); + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionKeyAndTenantId() { + CaseDefinition mockDefinition = MockProvider.mockCaseDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(); + setUpRuntimeData(mockDefinition); + + given() + .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_BY_KEY_AND_TENANT_ID_URL); + + verify(caseDefinitionQueryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).create(); + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionId() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_URL); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey(null); + verify(caseInstanceBuilder).setVariables(null); + verify(caseInstanceBuilder).create(); + + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionKey() { + given() + .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_BY_KEY_URL); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey(null); + verify(caseInstanceBuilder).setVariables(null); + verify(caseInstanceBuilder).create(); + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionIdWithBusinessKey() { + Map params = new HashMap(); + params.put("businessKey", MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_URL); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + verify(caseInstanceBuilder).setVariables(null); + verify(caseInstanceBuilder).create(); + + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionKeyWithBusinessKey() { + Map params = new HashMap(); + params.put("businessKey", MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + + given() + .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_BY_KEY_URL); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + verify(caseInstanceBuilder).setVariables(null); + verify(caseInstanceBuilder).create(); + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionIdWithVariables() { + Map variables = new HashMap(); + variables.put("aVariableName", VariablesBuilder.getVariableValueMap("abc", ValueType.STRING.getName())); + variables.put("anotherVariableName", VariablesBuilder.getVariableValueMap(900, ValueType.INTEGER.getName())); + + Map params = new HashMap(); + params.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_URL); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey(null); + verify(caseInstanceBuilder).setVariables(argThat(EqualsVariableMap.matches() + .matcher("aVariableName", EqualsPrimitiveValue.stringValue("abc")) + .matcher("anotherVariableName", EqualsPrimitiveValue.integerValue(900)))); + verify(caseInstanceBuilder).create(); + + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionKeyWithVariables() { + Map variables = new HashMap(); + variables.put("aVariableName", VariablesBuilder.getVariableValueMap("abc", null)); + variables.put("anotherVariableName", VariablesBuilder.getVariableValueMap(900, null)); + + Map params = new HashMap(); + params.put("variables", variables); + + given() + .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_BY_KEY_URL); + + Map expectedVariables = new HashMap(); + expectedVariables.put("aVariableName", "abc"); + expectedVariables.put("anotherVariableName", 999); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey(null); + verify(caseInstanceBuilder).setVariables(argThat(EqualsVariableMap.matches() + .matcher("aVariableName", EqualsUntypedValue.matcher().value("abc")) + .matcher("anotherVariableName", EqualsUntypedValue.matcher().value(900)))); + verify(caseInstanceBuilder).create(); + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionIdWithBusinessKeyAndVariables() { + Map variables = new HashMap(); + variables.put("aVariableName", VariablesBuilder.getVariableValueMap("abc", null)); + variables.put("anotherVariableName", VariablesBuilder.getVariableValueMap(900, null)); + + Map params = new HashMap(); + params.put("variables", variables); + params.put("businessKey", "aBusinessKey"); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_URL); + + Map expectedVariables = new HashMap(); + expectedVariables.put("aVariableName", "abc"); + expectedVariables.put("anotherVariableName", 999); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey("aBusinessKey"); + verify(caseInstanceBuilder).setVariables(argThat(EqualsVariableMap.matches() + .matcher("aVariableName", EqualsUntypedValue.matcher().value("abc")) + .matcher("anotherVariableName", EqualsUntypedValue.matcher().value(900)))); + verify(caseInstanceBuilder).create(); + + } + + @Test + public void testCreateCaseInstanceByCaseDefinitionKeyWithBusinessKeyAndVariables() { + Map variables = new HashMap(); + variables.put("aVariableName", VariablesBuilder.getVariableValueMap("abc", null)); + variables.put("anotherVariableName", VariablesBuilder.getVariableValueMap(900, null)); + + Map params = new HashMap(); + params.put("variables", variables); + params.put("businessKey", "aBusinessKey"); + + given() + .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .when() + .post(CREATE_INSTANCE_BY_KEY_URL); + + Map expectedVariables = new HashMap(); + expectedVariables.put("aVariableName", "abc"); + expectedVariables.put("anotherVariableName", 999); + + verify(caseServiceMock).withCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(caseInstanceBuilder).businessKey("aBusinessKey"); + verify(caseInstanceBuilder).setVariables(argThat(EqualsVariableMap.matches() + .matcher("aVariableName", EqualsUntypedValue.matcher().value("abc")) + .matcher("anotherVariableName", EqualsUntypedValue.matcher().value(900)))); + verify(caseInstanceBuilder).create(); + } + + @Test + public void testCreateCaseInstanceByInvalidCaseDefinitionId() { + when(caseInstanceBuilder.create()) + .thenThrow(new ProcessEngineException("expected exception")); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate case definition aCaseDefnitionId: expected exception")) + .when() + .post(CREATE_INSTANCE_URL); + } + + @Test + public void testCreateCaseInstanceByInvalidCaseDefinitionKey() { + when(caseInstanceBuilder.create()) + .thenThrow(new ProcessEngineException("expected exception")); + + given() + .pathParam("key", MockProvider.EXAMPLE_CASE_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate case definition aCaseDefnitionId: expected exception")) + .when() + .post(CREATE_INSTANCE_BY_KEY_URL); + } + + @Test + public void testCaseDiagramRetrieval() throws FileNotFoundException, URISyntaxException { + // setup additional mock behavior + File file = getFile("/processes/todo-process.png"); + when(repositoryServiceMock.getCaseDiagram(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .thenReturn(new FileInputStream(file)); + + // call method + byte[] actual = given().pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/png") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_CASE_DEFINITION_DIAGRAM_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_CASE_DEFINITION_DIAGRAM_RESOURCE_NAME) + .when().get(DIAGRAM_DEFINITION_URL).getBody().asByteArray(); + + // verify service interaction + verify(repositoryServiceMock).getCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(repositoryServiceMock).getCaseDiagram(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + + // compare input stream with response body bytes + byte[] expected = IoUtil.readInputStream(new FileInputStream(file), "case diagram"); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void testCaseDiagramNullFilename() throws FileNotFoundException, URISyntaxException { + // setup additional mock behavior + File file = getFile("/processes/todo-process.png"); + when(repositoryServiceMock.getCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID).getDiagramResourceName()) + .thenReturn(null); + when(repositoryServiceMock.getCaseDiagram(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .thenReturn(new FileInputStream(file)); + + // call method + byte[] actual = given().pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("application/octet-stream") + .header("Content-Disposition", "attachment; " + + "filename=\"" + null + "\"; "+ + "filename*=UTF-8''" + null) + .when().get(DIAGRAM_DEFINITION_URL).getBody().asByteArray(); + + // verify service interaction + verify(repositoryServiceMock).getCaseDiagram(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + + // compare input stream with response body bytes + byte[] expected = IoUtil.readInputStream(new FileInputStream(file), "case diagram"); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void testCaseDiagramNotExist() { + // setup additional mock behavior + when(repositoryServiceMock.getCaseDiagram(MockProvider.EXAMPLE_CASE_DEFINITION_ID)).thenReturn(null); + + // call method + given().pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().get(DIAGRAM_DEFINITION_URL); + + // verify service interaction + verify(repositoryServiceMock).getCaseDefinition(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + verify(repositoryServiceMock).getCaseDiagram(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + } + + @Test + public void testProcessDiagramMediaType() { + Assert.assertEquals("image/png", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.png")); + Assert.assertEquals("image/png", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.PNG")); + Assert.assertEquals("image/svg+xml", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.svg")); + Assert.assertEquals("image/jpeg", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.jpeg")); + Assert.assertEquals("image/jpeg", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.jpg")); + Assert.assertEquals("image/gif", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.gif")); + Assert.assertEquals("image/bmp", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.bmp")); + Assert.assertEquals("application/octet-stream", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("process.UNKNOWN")); + } + + @Test + public void testUpdateHistoryTimeToLive() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(5)) + .contentType(ContentType.JSON) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateCaseDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_CASE_DEFINITION_ID, 5); + } + + @Test + public void testUpdateHistoryTimeToLiveNullValue() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .body(new HistoryTimeToLiveDto()) + .contentType(ContentType.JSON) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateCaseDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_CASE_DEFINITION_ID, null); + } + + @Test + public void testUpdateHistoryTimeToLiveNegativeValue() { + String expectedMessage = "expectedMessage"; + + doThrow(new BadUserRequestException(expectedMessage)) + .when(repositoryServiceMock) + .updateCaseDefinitionHistoryTimeToLive(eq(MockProvider.EXAMPLE_CASE_DEFINITION_ID), eq(-1)); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(-1)) + .contentType(ContentType.JSON) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(BadUserRequestException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateCaseDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_CASE_DEFINITION_ID, -1); + } + + @Test + public void testUpdateHistoryTimeToLiveAuthorizationException() { + String expectedMessage = "expectedMessage"; + + doThrow(new AuthorizationException(expectedMessage)) + .when(repositoryServiceMock) + .updateCaseDefinitionHistoryTimeToLive(eq(MockProvider.EXAMPLE_CASE_DEFINITION_ID), eq(5)); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(5)) + .contentType(ContentType.JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateCaseDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_CASE_DEFINITION_ID, 5); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseDefinitionRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseDefinitionRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7dcc0690022a6e2fcc4b8ace9c95a72e66beac23 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseDefinitionRestServiceQueryTest.java @@ -0,0 +1,504 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Roman Smirnov + * + */ +public class CaseDefinitionRestServiceQueryTest extends AbstractRestServiceTest { + + protected static final String CASE_DEFINITION_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/case-definition"; + protected static final String CASE_DEFINITION_COUNT_QUERY_URL = CASE_DEFINITION_QUERY_URL + "/count"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + private CaseDefinitionQuery mockedQuery; + + @Before + public void setUpRuntime() { + mockedQuery = createMockCaseDefinitionQuery(MockProvider.createMockCaseDefinitions()); + } + + private CaseDefinitionQuery createMockCaseDefinitionQuery(List mockedDefinitions) { + CaseDefinitionQuery sampleDefinitionsQuery = mock(CaseDefinitionQuery.class); + + when(sampleDefinitionsQuery.list()).thenReturn(mockedDefinitions); + when(sampleDefinitionsQuery.count()).thenReturn((long) mockedDefinitions.size()); + when(processEngine.getRepositoryService().createCaseDefinitionQuery()).thenReturn(sampleDefinitionsQuery); + + return sampleDefinitionsQuery; + } + + @Test + public void testEmptyQuery() { + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testInvalidNumericParameter() { + String anInvalidIntegerQueryParam = "aString"; + + given() + .queryParam("version", anInvalidIntegerQueryParam) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'version' to value 'aString': " + + "Cannot convert value aString to java type java.lang.Integer")) + .when() + .get(CASE_DEFINITION_QUERY_URL); + } + + /** + * We assume that boolean query parameters that are not "true" + * or "false" are evaluated to "false" and don't cause a 400 error. + */ + @Test + public void testInvalidBooleanParameter() { + String anInvalidBooleanQueryParam = "neitherTrueNorFalse"; + given() + .queryParam("active", anInvalidBooleanQueryParam) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("id", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "id") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + } + + @Test + public void testSortingParameters() { + // asc + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("id", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("name", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("version", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionVersion(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("key", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("category", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionCategory(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + // desc + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("id", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("name", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("version", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionVersion(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("key", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("category", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionCategory(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testCaseDefinitionRetrieval() { + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> caseDefinitions = from(content).getList(""); + + assertThat(caseDefinitions).hasSize(1); + assertThat(caseDefinitions.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedKey = from(content).getString("[0].key"); + String returnedCategory = from(content).getString("[0].category"); + String returnedName = from(content).getString("[0].name"); + int returnedVersion = from(content).getInt("[0].version"); + String returnedResource = from(content).getString("[0].resource"); + String returnedDeploymentId = from(content).getString("[0].deploymentId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + assertThat(returnedKey).isEqualTo(MockProvider.EXAMPLE_CASE_DEFINITION_KEY); + assertThat(returnedCategory).isEqualTo(MockProvider.EXAMPLE_CASE_DEFINITION_CATEGORY); + assertThat(returnedName).isEqualTo(MockProvider.EXAMPLE_CASE_DEFINITION_NAME); + assertThat(returnedVersion).isEqualTo(MockProvider.EXAMPLE_CASE_DEFINITION_VERSION); + assertThat(returnedResource).isEqualTo(MockProvider.EXAMPLE_CASE_DEFINITION_RESOURCE_NAME); + assertThat(returnedDeploymentId).isEqualTo(MockProvider.EXAMPLE_DEPLOYMENT_ID); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testAdditionalParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given() + .queryParams(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + // assert query invocation + verify(mockedQuery).caseDefinitionId(queryParameters.get("caseDefinitionId")); + verify(mockedQuery).caseDefinitionCategory(queryParameters.get("category")); + verify(mockedQuery).caseDefinitionCategoryLike(queryParameters.get("categoryLike")); + verify(mockedQuery).caseDefinitionName(queryParameters.get("name")); + verify(mockedQuery).caseDefinitionNameLike(queryParameters.get("nameLike")); + verify(mockedQuery).deploymentId(queryParameters.get("deploymentId")); + verify(mockedQuery).caseDefinitionKey(queryParameters.get("key")); + verify(mockedQuery).caseDefinitionKeyLike(queryParameters.get("keyLike")); + verify(mockedQuery).caseDefinitionVersion(Integer.parseInt(queryParameters.get("version"))); + verify(mockedQuery).latestVersion(); + verify(mockedQuery).caseDefinitionResourceName(queryParameters.get("resourceName")); + verify(mockedQuery).caseDefinitionResourceNameLike(queryParameters.get("resourceNameLike")); + verify(mockedQuery).list(); + } + + @Test + public void testCaseDefinitionRetrievalByList() { + mockedQuery = createMockCaseDefinitionQuery(MockProvider.createMockTwoCaseDefinitions()); + + Response response = given() + .queryParam("caseDefinitionIdIn", MockProvider.EXAMPLE_CASE_DEFINITION_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).caseDefinitionIdIn(MockProvider.EXAMPLE_CASE_DEFINITION_ID, MockProvider.ANOTHER_EXAMPLE_CASE_DEFINITION_ID); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedDefinitionId1 = from(content).getString("[0].id"); + String returnedDefinitionId2 = from(content).getString("[1].id"); + + assertThat(returnedDefinitionId1).isEqualTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + assertThat(returnedDefinitionId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_CASE_DEFINITION_ID); + } + + @Test + public void testCaseDefinitionRetrievalByEmptyList() { + given() + .queryParam("caseDefinitionIdIn", "") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery, never()).caseDefinitionIdIn(Mockito.any()); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseDefinitionTenantIdList() { + List caseDefinitions = Arrays.asList( + MockProvider.mockCaseDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.mockCaseDefinition().id(MockProvider.ANOTHER_EXAMPLE_CASE_DEFINITION_ID).tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build()); + mockedQuery = createMockCaseDefinitionQuery(caseDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testCaseDefinitionWithoutTenantId() { + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testCaseDefinitionTenantIdIncludeDefinitionsWithoutTenantid() { + List caseDefinitions = Arrays.asList( + MockProvider.mockCaseDefinition().tenantId(null).build(), + MockProvider.mockCaseDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockedQuery = createMockCaseDefinitionQuery(caseDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("includeCaseDefinitionsWithoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockedQuery).includeCaseDefinitionsWithoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(CASE_DEFINITION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("caseDefinitionId", "anId"); + parameters.put("category", "cat"); + parameters.put("categoryLike", "catlike"); + parameters.put("name", "name"); + parameters.put("nameLike", "namelike"); + parameters.put("deploymentId", "depId"); + parameters.put("key", "key"); + parameters.put("keyLike", "keylike"); + parameters.put("version", "1"); + parameters.put("latestVersion", "true"); + parameters.put("resourceName", "res"); + parameters.put("resourceNameLike", "resLike"); + + return parameters; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseExecutionRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseExecutionRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a05bdf24302725a48618a5bc10c763cef245c21d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseExecutionRestServiceInteractionTest.java @@ -0,0 +1,3950 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.rest.dto.runtime.VariableNameDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.helper.variable.EqualsNullValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.CaseExecution; +import org.camunda.bpm.engine.runtime.CaseExecutionCommandBuilder; +import org.camunda.bpm.engine.runtime.CaseExecutionQuery; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.value.BooleanValue; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** +* +* @author Roman Smirnov +* +*/ +public class CaseExecutionRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String CASE_EXECUTION_URL = TEST_RESOURCE_ROOT_PATH + "/case-execution"; + protected static final String SINGLE_CASE_EXECUTION_URL = CASE_EXECUTION_URL + "/{id}"; + + protected static final String CASE_EXECUTION_MANUAL_START_URL = SINGLE_CASE_EXECUTION_URL + "/manual-start"; + protected static final String CASE_EXECUTION_REENABLE_URL = SINGLE_CASE_EXECUTION_URL + "/reenable"; + protected static final String CASE_EXECUTION_DISABLE_URL = SINGLE_CASE_EXECUTION_URL + "/disable"; + protected static final String CASE_EXECUTION_COMPLETE_URL = SINGLE_CASE_EXECUTION_URL + "/complete"; + protected static final String CASE_EXECUTION_TERMINATE_URL = SINGLE_CASE_EXECUTION_URL + "/terminate"; + + protected static final String CASE_EXECUTION_LOCAL_VARIABLES_URL = SINGLE_CASE_EXECUTION_URL + "/localVariables"; + protected static final String CASE_EXECUTION_VARIABLES_URL = SINGLE_CASE_EXECUTION_URL + "/variables"; + protected static final String SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL = CASE_EXECUTION_LOCAL_VARIABLES_URL + "/{varId}"; + protected static final String SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL = SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL + "/data"; + protected static final String SINGLE_CASE_EXECUTION_VARIABLE_URL = CASE_EXECUTION_VARIABLES_URL + "/{varId}"; + protected static final String SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL = SINGLE_CASE_EXECUTION_VARIABLE_URL + "/data"; + + private CaseService caseServiceMock; + private CaseExecutionQuery caseExecutionQueryMock; + private CaseExecutionCommandBuilder caseExecutionCommandBuilderMock; + + @Before + public void setUpRuntime() { + CaseExecution mockCaseExecution = MockProvider.createMockCaseExecution(); + + caseServiceMock = mock(CaseService.class); + + when(processEngine.getCaseService()).thenReturn(caseServiceMock); + + caseExecutionQueryMock = mock(CaseExecutionQuery.class); + + when(caseServiceMock.createCaseExecutionQuery()).thenReturn(caseExecutionQueryMock); + when(caseExecutionQueryMock.caseExecutionId(MockProvider.EXAMPLE_CASE_EXECUTION_ID)).thenReturn(caseExecutionQueryMock); + when(caseExecutionQueryMock.singleResult()).thenReturn(mockCaseExecution); + + when(caseServiceMock.getVariableTyped(anyString(), anyString(), eq(true))).thenReturn(EXAMPLE_VARIABLE_VALUE); + when(caseServiceMock.getVariablesTyped(anyString(), eq(true))).thenReturn(EXAMPLE_VARIABLES); + + when(caseServiceMock.getVariableLocalTyped(anyString(), eq(EXAMPLE_VARIABLE_KEY), anyBoolean())).thenReturn(EXAMPLE_VARIABLE_VALUE); + when(caseServiceMock.getVariableLocalTyped(anyString(), eq(EXAMPLE_BYTES_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE_BYTES); + when(caseServiceMock.getVariablesLocalTyped(anyString(), eq(true))).thenReturn(EXAMPLE_VARIABLES); + + when(caseServiceMock.getVariablesTyped(anyString(), Mockito.any(), eq(true))).thenReturn(EXAMPLE_VARIABLES); + when(caseServiceMock.getVariablesLocalTyped(anyString(), Mockito.any(), eq(true))).thenReturn(EXAMPLE_VARIABLES); + + caseExecutionCommandBuilderMock = mock(CaseExecutionCommandBuilder.class); + + when(caseServiceMock.withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID)).thenReturn(caseExecutionCommandBuilderMock); + + when(caseExecutionCommandBuilderMock.setVariable(anyString(), any())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.setVariableLocal(anyString(), any())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.setVariables(Mockito.any())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.setVariablesLocal(Mockito.any())).thenReturn(caseExecutionCommandBuilderMock); + + when(caseExecutionCommandBuilderMock.removeVariable(anyString())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.removeVariableLocal(anyString())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.removeVariables(Mockito.any())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.removeVariablesLocal(Mockito.any())).thenReturn(caseExecutionCommandBuilderMock); + + } + + @Test + public void testCaseExecutionRetrieval() { + Map params = new HashMap(); + params.put("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID); + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_CASE_INSTANCE_ID)) + .body("parentId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_PARENT_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_CASE_DEFINITION_ID)) + .body("activityId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_ID)) + .body("activityName", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_NAME)) + .body("activityType", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_TYPE)) + .body("activityDescription", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_DESCRIPTION)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("required", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_REQUIRED)) + .body("active", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_ACTIVE)) + .body("enabled", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_ENABLED)) + .body("disabled", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_DISABLED)) + .when() + .get(SINGLE_CASE_EXECUTION_URL); + + verify(caseServiceMock).createCaseExecutionQuery(); + verify(caseExecutionQueryMock).caseExecutionId(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionQueryMock).singleResult(); + } + + @Test + public void testManualStart() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testUnsuccessfulManualStart() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).manualStart(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot manualStart case execution " + MockProvider.EXAMPLE_CASE_EXECUTION_ID + ": expected exception")) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testManualStartWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_MANUAL_START_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).manualStart(); + } + + @Test + public void testDisable() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testUnsuccessfulDisable() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).disable(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot disable case execution " + MockProvider.EXAMPLE_CASE_EXECUTION_ID + ": expected exception")) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testDisableWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_DISABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).disable(); + } + + @Test + public void testReenable() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testUnsuccessfulReenable() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).reenable(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot reenable case execution " + MockProvider.EXAMPLE_CASE_EXECUTION_ID + ": expected exception")) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testReenableWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_REENABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).reenable(); + } + + @Test + public void testGetLocalVariables() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body(EXAMPLE_VARIABLE_KEY + ".type", equalTo("String")) + .when() + .get(CASE_EXECUTION_LOCAL_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + + verify(caseServiceMock).getVariablesLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, true); + } + + @Test + public void testGetVariables() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body(EXAMPLE_VARIABLE_KEY + ".type", + equalTo(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) + .when() + .get(CASE_EXECUTION_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + + verify(caseServiceMock).getVariablesTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, true); + } + + @Test + public void testGetLocalObjectVariables() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(caseServiceMock.getVariablesLocalTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given().pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo(payload)) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(CASE_EXECUTION_LOCAL_VARIABLES_URL); + + // then + verify(caseServiceMock).getVariablesLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, true); + } + + @Test + public void testGetLocalObjectVariablesSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(caseServiceMock.getVariablesLocalTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .queryParam("deserializeValues", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo("a serialized value")) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(CASE_EXECUTION_LOCAL_VARIABLES_URL); + + // then + verify(caseServiceMock).getVariablesLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, false); + } + + @Test + public void testGetLocalVariablesForNonExistingExecution() { + when(caseServiceMock.getVariablesLocalTyped(anyString(), anyBoolean())).thenThrow(new ProcessEngineException("expected exception")); + + given() + .pathParam("id", "aNonExistingExecutionId") + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when() + .get(CASE_EXECUTION_LOCAL_VARIABLES_URL); + + verify(caseServiceMock).getVariablesLocalTyped("aNonExistingExecutionId", true); + } + + @Test + public void testGetVariablesForNonExistingExecution() { + when(caseServiceMock.getVariablesTyped(anyString(), anyBoolean())).thenThrow(new ProcessEngineException("expected exception")); + + given() + .pathParam("id", "aNonExistingExecutionId") + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when() + .get(CASE_EXECUTION_VARIABLES_URL); + + verify(caseServiceMock).getVariablesTyped("aNonExistingExecutionId", true); + } + + @Test + public void testGetFileVariable() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(mimeType).create(); + + when(caseServiceMock.getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, variableKey, true)) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON.toString()) + .and() + .body("valueInfo.mimeType", equalTo(mimeType)) + .body("valueInfo.filename", equalTo(filename)) + .body("value", nullValue()) + .when().get(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testGetNullFileVariable() { + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).mimeType(mimeType).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(""))) + .when().get(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithTypeAndEncoding() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + + String contentType = response.contentType().replaceAll(" ", ""); + assertThat(contentType, is(ContentType.TEXT + ";charset=" + encoding)); + } + + @Test + public void testGetFileVariableDownloadWithoutType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .and() + .body(is(equalTo(new String(byteContent)))) + .header("Content-Disposition", containsString(filename)) + .when().get(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + } + + @Test + public void testCannotDownloadVariableOtherThanFile() { + String variableKey = "aVariableKey"; + BooleanValue variableValue = Variables.booleanValue(true); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(MediaType.APPLICATION_JSON) + .when().get(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testLocalVariableModification() { + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + List deletions = new ArrayList(); + deletions.add("deleteKey"); + messageBodyJson.put("deletions", deletions); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_LOCAL_VARIABLES_URL); + + Map expectedMap = new HashMap(); + expectedMap.put(variableKey, variableValue); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariablesLocal(eq(deletions)); + verify(caseExecutionCommandBuilderMock).setVariablesLocal(eq(expectedMap)); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testVariableModification() { + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + List deletions = new ArrayList(); + deletions.add("deleteKey"); + messageBodyJson.put("deletions", deletions); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_VARIABLES_URL); + + Map expectedMap = new HashMap(); + expectedMap.put(variableKey, variableValue); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariables(eq(deletions)); + verify(caseExecutionCommandBuilderMock).setVariables(eq(expectedMap)); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testLocalVariableModificationForNonExistingExecution() { + when(caseServiceMock.withCaseExecution("aNonExistingExecutionId")).thenReturn(caseExecutionCommandBuilderMock); + + doThrow(new ProcessEngineException("expected exception")) + .when(caseExecutionCommandBuilderMock) + .execute(); + + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + Map modifications = VariablesBuilder + .create() + .variable(variableKey, variableValue) + .getVariables(); + + messageBodyJson.put("modifications", modifications); + + given() + .pathParam("id", "aNonExistingExecutionId") + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution " + "aNonExistingExecutionId" + ": expected exception")) + .when() + .post(CASE_EXECUTION_LOCAL_VARIABLES_URL); + + Map expectedMap = new HashMap(); + expectedMap.put(variableKey, variableValue); + + verify(caseServiceMock).withCaseExecution("aNonExistingExecutionId"); + verify(caseExecutionCommandBuilderMock).removeVariablesLocal(null); + verify(caseExecutionCommandBuilderMock).setVariablesLocal(eq(expectedMap)); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testVariableModificationForNonExistingExecution() { + when(caseServiceMock.withCaseExecution("aNonExistingExecutionId")).thenReturn(caseExecutionCommandBuilderMock); + + doThrow(new ProcessEngineException("expected exception")) + .when(caseExecutionCommandBuilderMock) + .execute(); + + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + Map modifications = VariablesBuilder + .create() + .variable(variableKey, variableValue) + .getVariables(); + + messageBodyJson.put("modifications", modifications); + + given() + .pathParam("id", "aNonExistingExecutionId") + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution " + "aNonExistingExecutionId" + ": expected exception")) + .when() + .post(CASE_EXECUTION_VARIABLES_URL); + + Map expectedMap = new HashMap(); + expectedMap.put(variableKey, variableValue); + + verify(caseServiceMock).withCaseExecution("aNonExistingExecutionId"); + verify(caseExecutionCommandBuilderMock).removeVariables(null); + verify(caseExecutionCommandBuilderMock).setVariables(eq(expectedMap)); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testEmptyLocalVariableModification() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_LOCAL_VARIABLES_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariablesLocal(null); + verify(caseExecutionCommandBuilderMock).setVariablesLocal(null); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testEmptyVariableModification() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_VARIABLES_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariables(null); + verify(caseExecutionCommandBuilderMock).setVariables(null); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testGetSingleLocalVariable() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("value", is(EXAMPLE_VARIABLE_VALUE.getValue())) + .body("type", is(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) + .when() + .get(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, EXAMPLE_VARIABLE_KEY, true); + } + + @Test + public void testGetSingleLocalVariableData() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_BYTES_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .when() + .get(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, EXAMPLE_BYTES_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalVariableDataNonExisting() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", "nonExisting") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("case execution variable with name " + "nonExisting" + " does not exist")) + .when() + .get(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, "nonExisting", false); + } + + @Test + public void testGetSingleLocalVariabledataNotBinary() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, EXAMPLE_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleVariable() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("value", is(EXAMPLE_VARIABLE_VALUE.getValue())) + .body("type", is(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) + .when() + .get(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).getVariableTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, EXAMPLE_VARIABLE_KEY, true); + } + + @Test + public void testGetSingleLocalObjectVariable() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(caseServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given().pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo(payload)) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + // then + verify(caseServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, variableKey, true); + } + + @Test + public void testGetSingleLocalObjectVariableSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(caseServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo("a serialized value")) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + // then + verify(caseServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_CASE_EXECUTION_ID, variableKey, false); + } + + @Test + public void testNonExistingLocalVariable() { + when(caseServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), eq(EXAMPLE_VARIABLE_KEY), eq(true))) + .thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("case execution variable with name " + EXAMPLE_VARIABLE_KEY + " does not exist")) + .when() + .get(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testNonExistingVariable() { + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), eq(EXAMPLE_VARIABLE_KEY), eq(true))) + .thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("case execution variable with name " + EXAMPLE_VARIABLE_KEY + " does not exist")) + .when() + .get(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testGetLocalVariableForNonExistingExecution() { + when(caseServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), + eq(EXAMPLE_VARIABLE_KEY), eq(true))) + .thenThrow(new ProcessEngineException("expected exception")); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot get case execution variable " + EXAMPLE_VARIABLE_KEY + ": expected exception")) + .when() + .get(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testGetVariableForNonExistingExecution() { + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_EXECUTION_ID), eq(EXAMPLE_VARIABLE_KEY), eq(true))) + .thenThrow(new ProcessEngineException("expected exception")); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot get case execution variable " + EXAMPLE_VARIABLE_KEY + ": expected exception")) + .when() + .get(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariable() { + Map variableJson = VariablesBuilder.getVariableValueMap(EXAMPLE_VARIABLE_VALUE.getValue(), + EXAMPLE_VARIABLE_VALUE.getType().getName()); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(EXAMPLE_VARIABLE_KEY, EXAMPLE_VARIABLE_VALUE); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariable() { + Map variableJson = VariablesBuilder.getVariableValueMap(EXAMPLE_VARIABLE_VALUE.getValue(), + EXAMPLE_VARIABLE_VALUE.getType().getName()); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(EXAMPLE_VARIABLE_KEY, EXAMPLE_VARIABLE_VALUE); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalVariableWithTypeInteger() { + String variableKey = "aVariableKey"; + Integer variableValue = 123; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.integerValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeInteger() { + String variableKey = "aVariableKey"; + Integer variableValue = 123; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.integerValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalVariableWithUnparseableInteger() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class))) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithUnparseableInteger() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class))) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableWithTypeShort() { + String variableKey = "aVariableKey"; + Short variableValue = 123; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.shortValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeShort() { + String variableKey = "aVariableKey"; + Short variableValue = 123; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.shortValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalVariableWithUnparseableShort() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class))) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithUnparseableShort() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON). + body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class))) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableWithTypeLong() { + String variableKey = "aVariableKey"; + Long variableValue = 123L; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.longValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeLong() { + String variableKey = "aVariableKey"; + Long variableValue = 123L; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.longValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalVariableWithUnparseableLong() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class))) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithUnparseableLong() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class))) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableWithTypeDouble() { + String variableKey = "aVariableKey"; + Double variableValue = 123.456; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.doubleValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeDouble() { + String variableKey = "aVariableKey"; + Double variableValue = 123.456; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.doubleValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalVariableWithUnparseableDouble() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class))) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithUnparseableDouble() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class))) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableWithTypeBoolean() { + String variableKey = "aVariableKey"; + Boolean variableValue = true; + String type = "Boolean"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.booleanValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeBoolean() { + String variableKey = "aVariableKey"; + Boolean variableValue = true; + String type = "Boolean"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.booleanValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalVariableWithTypeDate() throws Exception { + Date now = new Date(); + + String variableKey = "aVariableKey"; + String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now); + String type = "Date"; + + Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.dateValue(expectedValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeDate() throws Exception { + Date now = new Date(); + + String variableKey = "aVariableKey"; + String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now); + String type = "Date"; + + Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.dateValue(expectedValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalVariableWithUnparseableDate() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Date"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class))) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithUnparseableDate() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Date"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class))) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "X"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: Unsupported value type 'X'")) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "X"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: Unsupported value type 'X'")) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalBinaryVariable() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleBinaryVariable() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes, MediaType.APPLICATION_OCTET_STREAM) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalBinaryVariableWithValueType() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "Bytes", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleBinaryVariableWithValueType() { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "Bytes", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalBinaryVariableWithNoValue() throws Exception { + byte[] bytes = new byte[0]; + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleBinaryVariableWithNoValue() throws Exception { + byte[] bytes = new byte[0]; + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalSerializableVariableFromJson() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleSerializableVariableFormJson() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleLocalSerializableVariableUnsupportedMediaType() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .multiPart("data", jsonBytes, "unsupported") + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Unrecognized content type for serialized java type: unsupported")) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(caseServiceMock, never()).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + } + + @Test + public void testPutSingleSerializableVariableUnsupportedMediaType() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .multiPart("data", jsonBytes, "unsupported") + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Unrecognized content type for serialized java type: unsupported")) + .when() + .post(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + + verify(caseServiceMock, never()).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + } + + @Test + public void testPutSingleLocalVariableWithNoValue() { + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + argThat(EqualsNullValue.matcher())); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithNoValue() { + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsNullValue.matcher())); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutLocalVariableForNonExistingExecution() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new ProcessEngineException("expected exception")).when(caseExecutionCommandBuilderMock).execute(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot put case execution variable " + variableKey + ": expected exception")) + .when() + .put(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPostSingleLocalFileVariableWithEncodingAndMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype + "; encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(encoding)); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleLocalFileVariableWithMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleLocalFileVariableWithEncoding() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, "encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + //when the user passes an encoding, he has to provide the type, too + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleLocalFileVariableOnlyFilename() throws Exception { + + String variableKey = "aVariableKey"; + String filename = "test.txt"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, new byte[0]) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(MediaType.APPLICATION_OCTET_STREAM)); + assertThat(captured.getValue().available(), is(0)); + } + + @Test + public void testPostSingleFileVariable() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype + "; encoding="+encoding) + .header("accept", MediaType.APPLICATION_JSON) + .multiPart("valueType", "File", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_EXECUTION_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(encoding)); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPutVariableForNonExistingExecution() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new ProcessEngineException("expected exception")).when(caseExecutionCommandBuilderMock).execute(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot put case execution variable " + variableKey + ": expected exception")) + .when() + .put(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testDeleteSingleLocalVariable() { + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(variableKey); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testDeleteSingleVariable() { + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_CASE_EXECUTION_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(variableKey); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testDeleteLocalVariableForNonExistingExecution() { + String variableKey = "aVariableKey"; + + doThrow(new ProcessEngineException("expected exception")) + .when(caseExecutionCommandBuilderMock).execute(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot delete case execution variable " + variableKey + ": expected exception")) + .when() + .delete(SINGLE_CASE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testDeleteVariableForNonExistingExecution() { + String variableKey = "aVariableKey"; + + doThrow(new ProcessEngineException("expected exception")) + .when(caseExecutionCommandBuilderMock).execute(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot delete case execution variable " + variableKey + ": expected exception")) + .when() + .delete(SINGLE_CASE_EXECUTION_VARIABLE_URL); + } + + @Test + public void testComplete() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testUnsuccessfulComplete() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).complete(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete case execution " + MockProvider.EXAMPLE_CASE_EXECUTION_ID + ": expected exception")) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + /////////////////////////////////////////////////////////////// + @Test + public void testTerminate() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testUnsuccessfulTerminate() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).terminate(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot terminate case execution " + MockProvider.EXAMPLE_CASE_EXECUTION_ID + ": expected exception")) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_EXECUTION_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseExecutionRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseExecutionRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..077dcaa754c99960d57fb5b13b5440edc677d068 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseExecutionRestServiceQueryTest.java @@ -0,0 +1,1665 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.CaseExecution; +import org.camunda.bpm.engine.runtime.CaseExecutionQuery; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.response.Response; + + +/** +* +* @author Roman Smirnov +* +*/ +public class CaseExecutionRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String CASE_EXECUTION_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/case-execution"; + protected static final String CASE_EXECUTION_COUNT_QUERY_URL = CASE_EXECUTION_QUERY_URL + "/count"; + + private CaseExecutionQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockCaseExecutionQuery(MockProvider.createMockCaseExecutions()); + } + + private CaseExecutionQuery setUpMockCaseExecutionQuery(List mockedCaseExecutions) { + CaseExecutionQuery query = mock(CaseExecutionQuery.class); + + when(processEngine.getCaseService().createCaseExecutionQuery()).thenReturn(query); + + when(query.list()).thenReturn(mockedCaseExecutions); + when(query.count()).thenReturn((long) mockedCaseExecutions.size()); + + return query; + } + + @Test + public void testEmptyQuery() { + String queryCaseExecutionId = ""; + + given() + .queryParam("caseExecutionId", queryCaseExecutionId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testEmptyQueryAsPost() { + Map params = new HashMap(); + params.put("caseExecutionId", ""); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("caseExecutionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "caseExecutionId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + } + + @Test + public void testSortingParameters() { + // asc + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseExecutionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + // desc + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseExecutionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("caseExecutionId").desc() + .orderBy("caseDefinitionId").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(CASE_EXECUTION_QUERY_URL); + + inOrder.verify(mockedQuery).orderByCaseExecutionId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testCaseExecutionRetrieval() { + String queryCaseExecutionId = "aCaseExecutionId"; + + Response response = given() + .queryParam("caseExecutionId", queryCaseExecutionId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).caseExecutionId(queryCaseExecutionId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> caseExecutions = from(content).getList(""); + + assertThat(caseExecutions).hasSize(1); + assertThat(caseExecutions.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedParentId = from(content).getString("[0].parentId"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedActivityName = from(content).getString("[0].activityName"); + String returnedActivityType = from(content).getString("[0].activityType"); + String returnedActivityDescription = from(content).getString("[0].activityDescription"); + String returnedTenantId = from(content).getString("[0].tenantId"); + boolean returnedRequired = from(content).getBoolean("[0].required"); + boolean returnedActiveState = from(content).getBoolean("[0].active"); + boolean returnedEnabledState = from(content).getBoolean("[0].enabled"); + boolean returnedDisabledState = from(content).getBoolean("[0].disabled"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + assertThat(returnedCaseInstanceId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_CASE_INSTANCE_ID); + assertThat(returnedParentId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_PARENT_ID); + assertThat(returnedCaseDefinitionId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_CASE_DEFINITION_ID); + assertThat(returnedActivityId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_ID); + assertThat(returnedActivityName).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_NAME); + assertThat(returnedActivityType).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_TYPE); + assertThat(returnedActivityDescription).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_DESCRIPTION); + assertThat(returnedTenantId).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedRequired).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_REQUIRED); + assertThat(returnedEnabledState).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_ENABLED); + assertThat(returnedActiveState).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_ACTIVE); + assertThat(returnedDisabledState).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_DISABLED); + } + + @Test + public void testCaseExecutionRetrievalAsPost() { + String queryCaseExecutionId = "aCaseExecutionId"; + + Map queryParameter = new HashMap(); + queryParameter.put("caseExecutionId", queryCaseExecutionId); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameter) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).caseExecutionId(queryCaseExecutionId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> caseExecutions = from(content).getList(""); + + assertThat(caseExecutions).hasSize(1); + assertThat(caseExecutions.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedParentId = from(content).getString("[0].parentId"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedActivityName = from(content).getString("[0].activityName"); + String returnedActivityType = from(content).getString("[0].activityType"); + String returnedActivityDescription = from(content).getString("[0].activityDescription"); + String returnedTenantId = from(content).getString("[0].tenantId"); + boolean returnedRequired = from(content).getBoolean("[0].required"); + boolean returnedActiveState = from(content).getBoolean("[0].active"); + boolean returnedEnabledState = from(content).getBoolean("[0].enabled"); + boolean returnedDisabledState = from(content).getBoolean("[0].disabled"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + assertThat(returnedCaseInstanceId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_CASE_INSTANCE_ID); + assertThat(returnedParentId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_PARENT_ID); + assertThat(returnedCaseDefinitionId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_CASE_DEFINITION_ID); + assertThat(returnedActivityId).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_ID); + assertThat(returnedActivityName).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_NAME); + assertThat(returnedActivityType).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_TYPE); + assertThat(returnedActivityDescription).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_ACTIVITY_DESCRIPTION); + assertThat(returnedTenantId).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedRequired).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_REQUIRED); + assertThat(returnedEnabledState).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_ENABLED); + assertThat(returnedActiveState).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_ACTIVE); + assertThat(returnedDisabledState).isEqualTo(MockProvider.EXAMPLE_CASE_EXECUTION_IS_DISABLED); + } + + @Test + public void testMultipleParameters() { + Map queryParameters = new HashMap(); + + queryParameters.put("caseExecutionId", "aCaseExecutionId"); + queryParameters.put("caseDefinitionKey", "aCaseDefId"); + queryParameters.put("caseDefinitionId", "aCaseDefId"); + queryParameters.put("caseInstanceId", "aCaseInstanceId"); + queryParameters.put("businessKey", "aBusinessKey"); + queryParameters.put("activityId", "anActivityId"); + queryParameters.put("tenantIdIn", "aTenantId"); + queryParameters.put("required", "true"); + queryParameters.put("active", "true"); + queryParameters.put("enabled", "true"); + queryParameters.put("disabled", "true"); + + given() + .queryParams(queryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseExecutionId(queryParameters.get("caseExecutionId")); + verify(mockedQuery).caseDefinitionKey(queryParameters.get("caseDefinitionKey")); + verify(mockedQuery).caseDefinitionId(queryParameters.get("caseDefinitionId")); + verify(mockedQuery).caseInstanceId(queryParameters.get("caseInstanceId")); + verify(mockedQuery).caseInstanceBusinessKey(queryParameters.get("businessKey")); + verify(mockedQuery).activityId(queryParameters.get("activityId")); + verify(mockedQuery).tenantIdIn(queryParameters.get("tenantIdIn")); + verify(mockedQuery).required(); + verify(mockedQuery).active(); + verify(mockedQuery).enabled(); + verify(mockedQuery).disabled(); + verify(mockedQuery).list(); + } + + @Test + public void testMultipleParametersAsPost() { + String aCaseExecutionId = "aCaseExecutionId"; + String aCaseDefKey = "aCaseDefKey"; + String aCaseDefId = "aCaseDefId"; + String aCaseInstanceId = "aCaseInstanceId"; + String aBusinessKey = "aBusinessKey"; + String anActivityId = "anActivityId"; + + Map queryParameters = new HashMap(); + + queryParameters.put("caseExecutionId", aCaseExecutionId); + queryParameters.put("caseDefinitionKey", aCaseDefKey); + queryParameters.put("caseDefinitionId", aCaseDefId); + queryParameters.put("caseInstanceId", aCaseInstanceId); + queryParameters.put("businessKey", aBusinessKey); + queryParameters.put("activityId", anActivityId); + queryParameters.put("required", "true"); + queryParameters.put("repeatable", "true"); + queryParameters.put("repetition", "true"); + queryParameters.put("active", "true"); + queryParameters.put("enabled", "true"); + queryParameters.put("disabled", "true"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseExecutionId(aCaseExecutionId); + verify(mockedQuery).caseDefinitionKey(aCaseDefKey); + verify(mockedQuery).caseDefinitionId(aCaseDefId); + verify(mockedQuery).caseInstanceId(aCaseInstanceId); + verify(mockedQuery).caseInstanceBusinessKey(aBusinessKey); + verify(mockedQuery).activityId(anActivityId); + verify(mockedQuery).required(); + verify(mockedQuery).active(); + verify(mockedQuery).enabled(); + verify(mockedQuery).disabled(); + verify(mockedQuery).list(); + } + + @Test + public void testCaseInstanceVariableParameters() { + // equals + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueEquals(variableName, variableValue); + + // greater then + queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueGreaterThan(variableName, variableValue); + + // greater then equals + queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueGreaterThanOrEqual(variableName, variableValue); + + // lower then + queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueLessThan(variableName, variableValue); + + // lower then equals + queryValue = variableName + "_lteq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueLessThanOrEqual(variableName, variableValue); + + // like + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueLike(variableName, variableValue); + + // not equals + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testCaseInstanceVariableParametersAsPost() { + // equals + String variableName = "varName"; + String variableValue = "varValue"; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("caseInstanceVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueEquals(variableName, variableValue); + + // greater then + variableJson.put("operator", "gt"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueGreaterThan(variableName, variableValue); + + // greater then equals + variableJson.put("operator", "gteq"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueGreaterThanOrEqual(variableName, variableValue); + + // lower then + variableJson.put("operator", "lt"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueLessThan(variableName, variableValue); + + // lower then equals + variableJson.put("operator", "lteq"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueLessThanOrEqual(variableName, variableValue); + + // like + variableJson.put("operator", "like"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueLike(variableName, variableValue); + + // not equals + variableJson.put("operator", "neq"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testMultipleCaseInstanceVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given() + .queryParam("caseInstanceVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueEquals(variableName1, variableValue1); + verify(mockedQuery).caseInstanceVariableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleCaseInstanceVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("caseInstanceVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).caseInstanceVariableValueEquals(variableName, variableValue); + verify(mockedQuery).caseInstanceVariableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testVariableValueEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLessThan(variableName, variableValue); + } + + @Test + public void testVariableValueLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lteq_" + variableValue; + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testCaseInstanceVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueEquals(variableName, variableValue); + } + + @Test + public void testCaseInstanceVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueEquals(variableName, variableValue); + } + + @Test + public void testCaseInstanceVariablesNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testCaseInstanceVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testCaseInstanceVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLessThan("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLikeAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + @Test + public void testVariableValueNotEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + + @Test + public void testVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testCaseInstanceVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("caseInstanceVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueEquals("varName", "varValue"); + } + + @Test + public void testCaseInstanceVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("caseInstanceVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueNotEquals("varName", "varValue"); + } + + @Test + public void testCaseInstanceVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("caseInstanceVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueLike("varName", "varValue"); + } + + + @Test + public void testCaseInstanceVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("caseInstanceVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueEquals("varName", "varValue"); + } + + @Test + public void testCaseInstanceVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("caseInstanceVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).caseInstanceVariableValueNotEquals("varName", "varValue"); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName1, variableValue1); + verify(mockedQuery).variableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).variableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(CASE_EXECUTION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .post(CASE_EXECUTION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockCaseExecutionQuery(createMockCaseExecutionsTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List caseExecutions = from(content).getList(""); + assertThat(caseExecutions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockCaseExecutionQuery(createMockCaseExecutionsTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_EXECUTION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List caseExecutions = from(content).getList(""); + assertThat(caseExecutions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + private List createMockCaseExecutionsTwoTenants() { + return Arrays.asList( + MockProvider.createMockCaseExecution(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockCaseExecution(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..edfd33e451220e70962fe15c7d3af9d6a53b0dc7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseInstanceRestServiceInteractionTest.java @@ -0,0 +1,2416 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ID; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.rest.dto.runtime.VariableNameDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.ExampleVariableObject; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.helper.variable.EqualsNullValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.CaseExecutionCommandBuilder; +import org.camunda.bpm.engine.runtime.CaseInstance; +import org.camunda.bpm.engine.runtime.CaseInstanceQuery; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.BooleanValue; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** +* +* @author Roman Smirnov +* +*/ +public class CaseInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String CASE_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/case-instance"; + protected static final String SINGLE_CASE_INSTANCE_URL = CASE_INSTANCE_URL + "/{id}"; + + protected static final String CASE_INSTANCE_COMPLETE_URL = SINGLE_CASE_INSTANCE_URL + "/complete"; + protected static final String CASE_INSTANCE_TERMINATE_URL = SINGLE_CASE_INSTANCE_URL + "/terminate"; + protected static final String CASE_INSTANCE_CLOSE_URL = SINGLE_CASE_INSTANCE_URL + "/close"; + + protected static final String CASE_INSTANCE_VARIABLES_URL = SINGLE_CASE_INSTANCE_URL + "/variables"; + protected static final String SINGLE_CASE_INSTANCE_VARIABLE_URL = CASE_INSTANCE_VARIABLES_URL + "/{varId}"; + protected static final String SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL = SINGLE_CASE_INSTANCE_VARIABLE_URL + "/data"; + + protected static final VariableMap EXAMPLE_OBJECT_VARIABLES = Variables.createVariables(); + static { + ExampleVariableObject variableValue = new ExampleVariableObject(); + variableValue.setProperty1("aPropertyValue"); + variableValue.setProperty2(true); + + EXAMPLE_OBJECT_VARIABLES.putValueTyped(EXAMPLE_VARIABLE_KEY, + MockObjectValue.fromObjectValue(Variables.objectValue(variableValue).serializationDataFormat("application/json").create()) + .objectTypeName(ExampleVariableObject.class.getName())); + } + + private CaseService caseServiceMock; + private CaseInstanceQuery caseInstanceQueryMock; + private CaseExecutionCommandBuilder caseExecutionCommandBuilderMock; + + @Before + public void setUpRuntime() { + CaseInstance mockCaseInstance = MockProvider.createMockCaseInstance(); + + caseServiceMock = mock(CaseService.class); + + when(processEngine.getCaseService()).thenReturn(caseServiceMock); + + caseInstanceQueryMock = mock(CaseInstanceQuery.class); + + when(caseServiceMock.createCaseInstanceQuery()).thenReturn(caseInstanceQueryMock); + when(caseInstanceQueryMock.caseInstanceId(MockProvider.EXAMPLE_CASE_INSTANCE_ID)).thenReturn(caseInstanceQueryMock); + when(caseInstanceQueryMock.singleResult()).thenReturn(mockCaseInstance); + + when(caseServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_VARIABLE_KEY), anyBoolean())).thenReturn(EXAMPLE_VARIABLE_VALUE); + when(caseServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_BYTES_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE_BYTES); + + when(caseServiceMock.getVariablesTyped(anyString(), eq(true))).thenReturn(EXAMPLE_VARIABLES); + when(caseServiceMock.getVariablesTyped(anyString(), Mockito.any(), eq(true))).thenReturn(EXAMPLE_VARIABLES); + + caseExecutionCommandBuilderMock = mock(CaseExecutionCommandBuilder.class); + + when(caseServiceMock.withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID)).thenReturn(caseExecutionCommandBuilderMock); + + when(caseExecutionCommandBuilderMock.setVariable(anyString(), any())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.setVariables(Mockito.any())).thenReturn(caseExecutionCommandBuilderMock); + + when(caseExecutionCommandBuilderMock.removeVariable(anyString())).thenReturn(caseExecutionCommandBuilderMock); + when(caseExecutionCommandBuilderMock.removeVariables(Mockito.any())).thenReturn(caseExecutionCommandBuilderMock); + } + + @Test + public void testCaseInstanceRetrieval() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("active", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_ACTIVE)) + .body("completed", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_COMPLETED)) + .body("terminated", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_TERMINATED)) + .when() + .get(SINGLE_CASE_INSTANCE_URL); + + verify(caseServiceMock).createCaseInstanceQuery(); + verify(caseInstanceQueryMock).caseInstanceId(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseInstanceQueryMock).singleResult(); + } + + + @Test + public void testGetVariables() { + Response response = given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(String.class.getSimpleName())) + .when().get(CASE_INSTANCE_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + + verify(caseServiceMock).getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, true); + } + + @Test + public void testGetVariablesWithNullValue() { + when(caseServiceMock.getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, true)).thenReturn(EXAMPLE_VARIABLES_WITH_NULL_VALUE); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_ANOTHER_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".value", nullValue()) + .body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".type", equalTo("Null")) + .when().get(CASE_INSTANCE_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + + verify(caseServiceMock).getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, true); + } + + + @Test + public void testJavaObjectVariableSerialization() { + when(caseServiceMock.getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, true)).thenReturn(EXAMPLE_OBJECT_VARIABLES); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value.property1", equalTo("aPropertyValue")) + .body(EXAMPLE_VARIABLE_KEY + ".value.property2", equalTo(true)) + .body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT))) + .body(EXAMPLE_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ExampleVariableObject.class.getName())) + .body(EXAMPLE_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .when().get(CASE_INSTANCE_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + + verify(caseServiceMock).getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, true); + } + + @Test + public void testGetObjectVariablesSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(caseServiceMock.getVariablesTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .queryParam("deserializeValues", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo("a serialized value")) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(CASE_INSTANCE_VARIABLES_URL); + + // then + verify(caseServiceMock).getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, false); + } + + @Test + public void testGetVariablesForNonExistingCaseInstance() { + when(caseServiceMock.getVariablesTyped(anyString(), eq(true))).thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", "aNonExistingCaseInstanceId") + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when().get(CASE_INSTANCE_VARIABLES_URL); + + verify(caseServiceMock).getVariablesTyped("aNonExistingCaseInstanceId", true); + } + + @Test + public void testVariableModification() { + String variableKey = "aKey"; + int variableValue = 123; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + List deletions = new ArrayList(); + deletions.add("deleteKey"); + messageBodyJson.put("deletions", deletions); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(CASE_INSTANCE_VARIABLES_URL); + + Map expectedModifications = new HashMap(); + expectedModifications.put(variableKey, variableValue); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariables(eq(expectedModifications)); + verify(caseExecutionCommandBuilderMock).removeVariables(eq(deletions)); + verify(caseExecutionCommandBuilderMock).execute(); + + } + + @Test + public void testVariableModificationWithUnparseableInteger() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableShort() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableLong() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableDouble() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableDate() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution: Unsupported value type 'X'")) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationForNonExistingCaseInstance() { + doThrow(new ProcessEngineException("expected exception")).when(caseExecutionCommandBuilderMock).execute(); + + String variableKey = "aKey"; + int variableValue = 123; + + Map messageBodyJson = new HashMap(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for case execution " + MockProvider.EXAMPLE_CASE_INSTANCE_ID + ": expected exception")) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testEmptyVariableModification() { + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(CASE_INSTANCE_VARIABLES_URL); + } + + @Test + public void testGetSingleVariable() { + String variableKey = "aVariableKey"; + int variableValue = 123; + + when(caseServiceMock.getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, variableKey, true)) + .thenReturn(Variables.integerValue(variableValue)); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", is(123)) + .body("type", is("Integer")) + .when().get(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, variableKey, true); + } + + @Test + public void testNonExistingVariable() { + String variableKey = "aVariableKey"; + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), eq(true))).thenReturn(null); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("case execution variable with name " + variableKey + " does not exist")) + .when().get(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + + @Test + public void testGetSingleLocalVariableData() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", EXAMPLE_BYTES_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .when() + .get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + verify(caseServiceMock).getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, EXAMPLE_BYTES_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalVariableDataNonExisting() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", "nonExisting") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("case execution variable with name " + "nonExisting" + " does not exist")) + .when() + .get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + verify(caseServiceMock).getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, "nonExisting", false); + } + + @Test + public void testGetSingleLocalVariabledataNotBinary() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + verify(caseServiceMock).getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, EXAMPLE_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleObjectVariable() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo(payload)) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + // then + verify(caseServiceMock).getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, variableKey, true); + } + + @Test + public void testGetSingleObjectVariableSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo("a serialized value")) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + // then + verify(caseServiceMock).getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, variableKey, false); + } + + @Test + public void testGetVariableForNonExistingInstance() { + String variableKey = "aVariableKey"; + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), eq(true))) + .thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot get case execution variable " + variableKey + ": expected exception")) + .when().get(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testGetFileVariable() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(mimeType).create(); + + when(caseServiceMock.getVariableTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, variableKey, true)) + .thenReturn(variableValue); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON.toString()) + .and() + .body("valueInfo.mimeType", equalTo(mimeType)) + .body("valueInfo.filename", equalTo(filename)) + .body("value", nullValue()) + .when().get(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testGetNullFileVariable() { + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).mimeType(mimeType).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(""))) + .when().get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithTypeAndEncoding() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + String contentType = response.contentType().replaceAll(" ", ""); + assertThat(contentType, is(ContentType.TEXT + ";charset=" + encoding)); + } + + @Test + public void testGetFileVariableDownloadWithoutType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).create(); + + when(caseServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_CASE_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .and() + .body(is(equalTo(new String(byteContent)))) + .header("Content-Disposition", containsString(filename)) + .when().get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testCannotDownloadVariableOtherThanFile() { + String variableKey = "aVariableKey"; + BooleanValue variableValue = Variables.booleanValue(true); + + when(caseServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testPutSingleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsUntypedValue.matcher().value(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeString() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + String type = "String"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.stringValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeInteger() { + String variableKey = "aVariableKey"; + Integer variableValue = 123; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.integerValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithUnparseableInteger() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class))) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeShort() { + String variableKey = "aVariableKey"; + Short variableValue = 123; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.shortValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithUnparseableShort() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class))) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeLong() { + String variableKey = "aVariableKey"; + Long variableValue = 123L; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.longValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithUnparseableLong() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class))) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeDouble() { + String variableKey = "aVariableKey"; + Double variableValue = 123.456; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.doubleValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithUnparseableDouble() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class))) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeBoolean() { + String variableKey = "aVariableKey"; + Boolean variableValue = true; + String type = "Boolean"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.booleanValue(variableValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithTypeDate() throws Exception { + Date now = new Date(); + + String variableKey = "aVariableKey"; + String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now); + String type = "Date"; + + Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.dateValue(expectedValue))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleVariableWithUnparseableDate() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Date"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class))) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "X"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put case execution variable aVariableKey: Unsupported value type 'X'")) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleBinaryVariable() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleBinaryVariableWithValueType() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "Bytes", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleBinaryVariableWithNoValue() throws Exception { + byte[] bytes = new byte[0]; + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleSerializableVariable() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable))); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutSingleSerializableVariableUnsupportedMediaType() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, "unsupported") + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Unrecognized content type for serialized java type: unsupported")) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNoValue() { + String variableKey = "aVariableKey"; + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), + argThat(EqualsNullValue.matcher())); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testPutVariableForNonExistingInstance() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new ProcessEngineException("expected exception")).when(caseExecutionCommandBuilderMock).execute(); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot put case execution variable " + variableKey + ": expected exception")) + .when().put(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPostSingleFileVariableWithEncodingAndMimeType() throws Exception { + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype + "; encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(encoding)); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleFileVariableWithMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleFileVariableWithEncoding() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, "encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + //when the user passes an encoding, he has to provide the type, too + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleFileVariableOnlyFilename() throws Exception { + + String variableKey = "aVariableKey"; + String filename = "test.txt"; + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", filename, new byte[0]) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_CASE_INSTANCE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(variableKey), captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(MediaType.APPLICATION_OCTET_STREAM)); + assertThat(captured.getValue().available(), is(0)); + } + + @Test + public void testDeleteSingleVariable() { + String variableKey = "aVariableKey"; + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_CASE_INSTANCE_VARIABLE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(variableKey); + verify(caseExecutionCommandBuilderMock).execute(); + } + + @Test + public void testDeleteVariableForNonExistingInstance() { + String variableKey = "aVariableKey"; + + doThrow(new ProcessEngineException("expected exception")).when(caseExecutionCommandBuilderMock).execute(); + + given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot delete case execution variable " + variableKey + ": expected exception")) + .when().delete(SINGLE_CASE_INSTANCE_VARIABLE_URL); + } + + @Test + public void testComplete() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testUnsuccessfulComplete() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).complete(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete case instance " + MockProvider.EXAMPLE_CASE_INSTANCE_ID + ": expected exception")) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + @Test + public void testCompleteWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_COMPLETE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).complete(); + } + + + @Test + public void testClose() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testUnsuccessfulClose() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).close(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot close case instance " + MockProvider.EXAMPLE_CASE_INSTANCE_ID + ": expected exception")) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testCloseWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_CLOSE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).close(); + } + + @Test + public void testTerminate() { + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testUnsuccessfulTerminate() { + doThrow(new NotValidException("expected exception")).when(caseExecutionCommandBuilderMock).terminate(); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot terminate case instance " + MockProvider.EXAMPLE_CASE_INSTANCE_ID + ": expected exception")) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariable() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer", true) + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableAndVariableLocal() { + String aVariableKey = "aKey"; + int aVariableValue = 123; + + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variablesJson = new HashMap(); + + Map variables = VariablesBuilder + .create() + .variable(aVariableKey, aVariableValue, "Integer") + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + variablesJson.put("variables", variables); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).setVariable(eq(aVariableKey), + argThat(EqualsPrimitiveValue.integerValue(aVariableValue))); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey, true); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithRemoveVariableAndVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + VariableNameDto secondVariableName = new VariableNameDto(anotherVariableKey); + variableNames.add(secondVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).removeVariable(anotherVariableKey); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String") + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariable(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableLocalAndRemoveVariable() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariable(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } + + @Test + public void testTerminateWithSetVariableLocalAndRemoveVariableLocal() { + String aVariableKey = "aKey"; + String anotherVariableKey = "anotherKey"; + String anotherVariableValue = "abc"; + + Map variables = VariablesBuilder + .create() + .variable(anotherVariableKey, anotherVariableValue, "String", true) + .getVariables(); + + List variableNames = new ArrayList(); + + VariableNameDto firstVariableName = new VariableNameDto(aVariableKey, true); + variableNames.add(firstVariableName); + + Map variablesJson = new HashMap(); + + variablesJson.put("variables", variables); + variablesJson.put("deletions", variableNames); + + given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(variablesJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(CASE_INSTANCE_TERMINATE_URL); + + verify(caseServiceMock).withCaseExecution(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + verify(caseExecutionCommandBuilderMock).removeVariableLocal(aVariableKey); + verify(caseExecutionCommandBuilderMock).setVariableLocal(eq(anotherVariableKey), + argThat(EqualsPrimitiveValue.stringValue(anotherVariableValue))); + verify(caseExecutionCommandBuilderMock).terminate(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e168463da6402f752f111cb18afcb4262ffdc92b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CaseInstanceRestServiceQueryTest.java @@ -0,0 +1,1194 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.CaseInstance; +import org.camunda.bpm.engine.runtime.CaseInstanceQuery; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.response.Response; + +/** + * + * @author Roman Smirnov + * + */ +public class CaseInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String CASE_INSTANCE_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/case-instance"; + protected static final String CASE_INSTANCE_COUNT_QUERY_URL = CASE_INSTANCE_QUERY_URL + "/count"; + + private CaseInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockCaseInstanceQuery(MockProvider.createMockCaseInstances()); + } + + private CaseInstanceQuery setUpMockCaseInstanceQuery(List mockedCaseInstances) { + CaseInstanceQuery query = mock(CaseInstanceQuery.class); + + when(query.list()).thenReturn(mockedCaseInstances); + when(query.count()).thenReturn((long) mockedCaseInstances.size()); + when(processEngine.getCaseService().createCaseInstanceQuery()).thenReturn(query); + + return query; + } + + @Test + public void testEmptyQuery() { + String queryCaseInstanceId = ""; + + given() + .queryParam("caseInstanceId", queryCaseInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testEmptyQueryAsPost() { + Map params = new HashMap(); + params.put("caseInstanceId", ""); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("caseInstanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "caseInstanceId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + } + + @Test + public void testSortingParameters() { + // asc + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + // desc + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("caseInstanceId").desc() + .orderBy("caseDefinitionId").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(CASE_INSTANCE_QUERY_URL); + + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testCaseInstanceRetrieval() { + String queryCaseInstanceId = "aCaseInstanceId"; + + Response response = given() + .queryParam("caseInstanceId", queryCaseInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).caseInstanceId(queryCaseInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> caseInstances = from(content).getList(""); + + assertThat(caseInstances).hasSize(1); + assertThat(caseInstances.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedBusinessKeyKey = from(content).getString("[0].businessKey"); + String returnedTenantId = from(content).getString("[0].tenantId"); + boolean returnedActiveState = from(content).getBoolean("[0].active"); + boolean returnedCompletedState = from(content).getBoolean("[0].completed"); + boolean returnedTerminatedState = from(content).getBoolean("[0].terminated"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + assertThat(returnedCaseDefinitionId).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_CASE_DEFINITION_ID); + assertThat(returnedBusinessKeyKey).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + assertThat(returnedTenantId).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedActiveState).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_ACTIVE); + assertThat(returnedCompletedState).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_COMPLETED); + assertThat(returnedTerminatedState).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_TERMINATED); + } + + @Test + public void testCaseInstanceRetrievalAsPost() { + String queryCaseInstanceId = "aCaseInstanceId"; + + Map queryParameter = new HashMap(); + queryParameter.put("caseInstanceId", queryCaseInstanceId); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameter) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).caseInstanceId(queryCaseInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> caseInstances = from(content).getList(""); + + assertThat(caseInstances).hasSize(1); + assertThat(caseInstances.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedBusinessKeyKey = from(content).getString("[0].businessKey"); + String returnedTenantId = from(content).getString("[0].tenantId"); + boolean returnedActiveState = from(content).getBoolean("[0].active"); + boolean returnedCompletedState = from(content).getBoolean("[0].completed"); + boolean returnedTerminatedState = from(content).getBoolean("[0].terminated"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + assertThat(returnedCaseDefinitionId).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_CASE_DEFINITION_ID); + assertThat(returnedBusinessKeyKey).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + assertThat(returnedTenantId).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedActiveState).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_ACTIVE); + assertThat(returnedCompletedState).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_COMPLETED); + assertThat(returnedTerminatedState).isEqualTo(MockProvider.EXAMPLE_CASE_INSTANCE_IS_TERMINATED); + } + + @Test + public void testMultipleParameters() { + Map queryParameters = new HashMap(); + + queryParameters.put("caseInstanceId", "aCaseInstanceId"); + queryParameters.put("caseDefinitionId", "aCaseDefId"); + queryParameters.put("caseDefinitionKey", "aCaseDefKey"); + queryParameters.put("deploymentId", "aDeploymentId"); + queryParameters.put("businessKey", "aBusinessKey"); + queryParameters.put("superProcessInstance", "aSuperProcInstId"); + queryParameters.put("subProcessInstance", "aSubProcInstId"); + queryParameters.put("superCaseInstance", "aSuperCaseInstId"); + queryParameters.put("subCaseInstance", "aSubCaseInstId"); + queryParameters.put("tenantIdIn", "aTenantId"); + queryParameters.put("active", "true"); + queryParameters.put("completed", "true"); + queryParameters.put("terminated", "true"); + + given() + .queryParams(queryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).caseInstanceId(queryParameters.get("caseInstanceId")); + verify(mockedQuery).caseDefinitionId(queryParameters.get("caseDefinitionId")); + verify(mockedQuery).caseDefinitionKey(queryParameters.get("caseDefinitionKey")); + verify(mockedQuery).deploymentId(queryParameters.get("deploymentId")); + verify(mockedQuery).caseInstanceBusinessKey(queryParameters.get("businessKey")); + verify(mockedQuery).superProcessInstanceId(queryParameters.get("superProcessInstance")); + verify(mockedQuery).subProcessInstanceId(queryParameters.get("subProcessInstance")); + verify(mockedQuery).superCaseInstanceId(queryParameters.get("superCaseInstance")); + verify(mockedQuery).subCaseInstanceId(queryParameters.get("subCaseInstance")); + verify(mockedQuery).tenantIdIn(queryParameters.get("tenantIdIn")); + verify(mockedQuery).active(); + verify(mockedQuery).completed(); + verify(mockedQuery).terminated(); + verify(mockedQuery).list(); + } + + @Test + public void testMultipleParametersAsPost() { + String aCaseInstanceId = "aCaseInstanceId"; + String aCaseDefId = "aCaseDefId"; + String aCaseDefKey = "aCaseDefKey"; + String aDeploymentId = "aDeploymentId"; + String aBusinessKey = "aBusinessKey"; + String aSuperProcInstId = "aSuperProcInstId"; + String aSubProcInstId = "aSubProcInstId"; + String aSuperCaseInstId = "aSuperCaseInstId"; + String aSubCaseInstId = "aSubCaseInstId"; + + Map queryParameters = new HashMap(); + + queryParameters.put("caseInstanceId", aCaseInstanceId); + queryParameters.put("caseDefinitionId", aCaseDefId); + queryParameters.put("caseDefinitionKey", aCaseDefKey); + queryParameters.put("deploymentId", aDeploymentId); + queryParameters.put("businessKey", aBusinessKey); + queryParameters.put("superProcessInstance", aSuperProcInstId); + queryParameters.put("subProcessInstance", aSubProcInstId); + queryParameters.put("superCaseInstance", aSuperCaseInstId); + queryParameters.put("subCaseInstance", aSubCaseInstId); + queryParameters.put("active", "true"); + queryParameters.put("completed", "true"); + queryParameters.put("terminated", "true"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).caseInstanceId(aCaseInstanceId); + verify(mockedQuery).caseDefinitionId(aCaseDefId); + verify(mockedQuery).caseDefinitionKey(aCaseDefKey); + verify(mockedQuery).deploymentId(aDeploymentId); + verify(mockedQuery).caseInstanceBusinessKey(aBusinessKey); + verify(mockedQuery).superProcessInstanceId(aSuperProcInstId); + verify(mockedQuery).subProcessInstanceId(aSubProcInstId); + verify(mockedQuery).superCaseInstanceId(aSuperCaseInstId); + verify(mockedQuery).subCaseInstanceId(aSubCaseInstId); + verify(mockedQuery).active(); + verify(mockedQuery).completed(); + verify(mockedQuery).terminated(); + verify(mockedQuery).list(); + } + + @Test + public void testVariableValueEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThan(variableName, variableValue); + } + + @Test + public void testVariableValueLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lteq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLike(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableValueEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableGreaterThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThan("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLikeAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + @Test + public void testVariableValueNotEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName1, variableValue1); + verify(mockedQuery).variableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).variableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(CASE_INSTANCE_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .post(CASE_INSTANCE_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockCaseInstanceQuery(createMockCaseInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List caseInstances = from(content).getList(""); + assertThat(caseInstances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdParameter() { + mockedQuery = setUpMockCaseInstanceQuery(Arrays.asList(MockProvider.createMockCaseInstance(null))); + + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List caseInstances = from(content).getList(""); + assertThat(caseInstances).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockCaseInstanceQuery(createMockCaseInstancesTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List caseInstances = from(content).getList(""); + assertThat(caseInstances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdPostParameter() { + mockedQuery = setUpMockCaseInstanceQuery(Arrays.asList(MockProvider.createMockCaseInstance(null))); + + Map queryParameters = new HashMap(); + queryParameters.put("withoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CASE_INSTANCE_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List caseInstances = from(content).getList(""); + assertThat(caseInstances).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + private List createMockCaseInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockCaseInstance(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockCaseInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ConditionRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ConditionRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f79ac931f54c6a188d515ca286fee87f3c4fc0db --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ConditionRestServiceTest.java @@ -0,0 +1,286 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.impl.ConditionEvaluationBuilderImpl; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.ConditionEvaluationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +import io.restassured.response.Response; + +public class ConditionRestServiceTest extends AbstractRestServiceTest { + + protected static final String CONDITION_URL = TEST_RESOURCE_ROOT_PATH + ConditionRestService.PATH; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + private RuntimeService runtimeServiceMock; + private ConditionEvaluationBuilder conditionEvaluationBuilderMock; + private List processInstancesMock; + + @Before + public void setupMocks() { + runtimeServiceMock = mock(RuntimeService.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + + conditionEvaluationBuilderMock = mock(ConditionEvaluationBuilderImpl.class); + + when(runtimeServiceMock.createConditionEvaluation()).thenReturn(conditionEvaluationBuilderMock); + when(conditionEvaluationBuilderMock.processDefinitionId(anyString())).thenReturn(conditionEvaluationBuilderMock); + when(conditionEvaluationBuilderMock.processInstanceBusinessKey(anyString())).thenReturn(conditionEvaluationBuilderMock); + when(conditionEvaluationBuilderMock.setVariables(Mockito.any())).thenReturn(conditionEvaluationBuilderMock); + when(conditionEvaluationBuilderMock.setVariable(anyString(), any())).thenReturn(conditionEvaluationBuilderMock); + + processInstancesMock = MockProvider.createAnotherMockProcessInstanceList(); + when(conditionEvaluationBuilderMock.evaluateStartConditions()).thenReturn(processInstancesMock); + } + + @Test + public void testConditionEvaluationOnlyVariables() { + Map parameters = new HashMap(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CONDITION_URL); + + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + checkResult(content); + + verify(runtimeServiceMock).createConditionEvaluation(); + Map expectedVariables = new HashMap(); + expectedVariables.put("foo", "bar"); + verify(conditionEvaluationBuilderMock).setVariables(expectedVariables); + verify(conditionEvaluationBuilderMock).evaluateStartConditions(); + verifyNoMoreInteractions(conditionEvaluationBuilderMock); + } + + @Test + public void testConditionEvaluationWithProcessDefinition() { + Map parameters = new HashMap(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CONDITION_URL); + + verify(runtimeServiceMock).createConditionEvaluation(); + verify(conditionEvaluationBuilderMock).processDefinitionId(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(conditionEvaluationBuilderMock).evaluateStartConditions(); + } + + @Test + public void testConditionEvaluationWithBusinessKey() { + Map parameters = new HashMap(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + parameters.put("businessKey", MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CONDITION_URL); + + verify(runtimeServiceMock).createConditionEvaluation(); + verify(conditionEvaluationBuilderMock).processInstanceBusinessKey(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)); + } + + @Test + public void testConditionEvaluationWithTenantId() { + Map parameters = new HashMap(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + parameters.put("tenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CONDITION_URL); + + verify(runtimeServiceMock).createConditionEvaluation(); + verify(conditionEvaluationBuilderMock).tenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(conditionEvaluationBuilderMock).evaluateStartConditions(); + } + + @Test + public void testConditionEvaluationWithoutTenantId() { + Map parameters = new HashMap(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + parameters.put("withoutTenantId", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CONDITION_URL); + + verify(runtimeServiceMock).createConditionEvaluation(); + verify(conditionEvaluationBuilderMock).withoutTenantId(); + verify(conditionEvaluationBuilderMock).evaluateStartConditions(); + } + + @Test + public void testConditionEvaluationFailingInvalidTenantParameters() { + Map parameters = new HashMap(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + parameters.put("tenantId", MockProvider.EXAMPLE_TENANT_ID); + parameters.put("withoutTenantId", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Parameter 'tenantId' cannot be used together with parameter 'withoutTenantId'.")) + .when() + .post(CONDITION_URL); + } + + @Test + public void testConditionEvaluationThrowsAuthorizationException() { + Map parameters = new HashMap(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(conditionEvaluationBuilderMock).evaluateStartConditions(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(CONDITION_URL); + } + + @Test + public void shouldReturnErrorCode() { + Map parameters = new HashMap<>(); + Map variables = VariablesBuilder + .create() + .variable("foo", "bar") + .getVariables(); + parameters.put("variables", variables); + + doThrow(new ProcessEngineException("foo", 123)) + .when(conditionEvaluationBuilderMock).evaluateStartConditions(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("foo")) + .body("code", equalTo(123)) + .when() + .post(CONDITION_URL); + } + + protected void checkResult(String content) { + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, from(content).get("[" + 0 + "].id")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, from(content).get("[" + 0+ "].definitionId")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, from(content).get("[" + 0+ "].definitionKey")); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, from(content).get("[" + 1 + "].id")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, from(content).get("[" + 1+ "].definitionId")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, from(content).get("[" + 1+ "].definitionKey")); + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CustomJacksonDateFormatTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CustomJacksonDateFormatTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8ea771225de1ede4ba81e503b015918fb5ccce76 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/CustomJacksonDateFormatTest.java @@ -0,0 +1,110 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.mapper.JacksonConfigurator.DEFAULT_DATE_FORMAT; +import static org.hamcrest.Matchers.is; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.mapper.JacksonConfigurator; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; + +public class CustomJacksonDateFormatTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/process-instance"; + protected static final String SINGLE_PROCESS_INSTANCE_URL = PROCESS_INSTANCE_URL + "/{id}"; + protected static final String PROCESS_INSTANCE_VARIABLES_URL = SINGLE_PROCESS_INSTANCE_URL + "/variables"; + protected static final String SINGLE_PROCESS_INSTANCE_VARIABLE_URL = PROCESS_INSTANCE_VARIABLES_URL + "/{varId}"; + + protected static final SimpleDateFormat testDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + protected static final Date testDate = new Date(1450282812000L); + protected static final String testDateFormatted = testDateFormat.format(testDate); + + protected RuntimeServiceImpl runtimeServiceMock; + + @Before + public void setUpRuntimeData() { + runtimeServiceMock = mock(RuntimeServiceImpl.class); + + when(runtimeServiceMock.getVariableTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), eq(EXAMPLE_VARIABLE_KEY), eq(true))) + .thenReturn(Variables.dateValue(testDate)); + + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + } + + @AfterClass + public static void reset() { + JacksonConfigurator.setDateFormatString(DEFAULT_DATE_FORMAT); + } + + @Test + public void testGetDateVariable() { + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("value", is(testDateFormatted)) + .body("type", is("Date")) + .when() + .get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testSetDateVariable() throws Exception { + String variableValue = testDateFormat.format(testDate); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, "Date"); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .contentType(ContentType.JSON) + .body(variableJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(EXAMPLE_PROCESS_INSTANCE_ID), eq(EXAMPLE_VARIABLE_KEY), + argThat(EqualsPrimitiveValue.dateValue(testDate))); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..096561f343e3c055590c4abfd3fc64a30459a9eb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestServiceInteractionTest.java @@ -0,0 +1,790 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.anyMap; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.dmn.engine.DmnDecisionResult; +import org.camunda.bpm.dmn.engine.DmnEngineException; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.DecisionService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.dmn.DecisionsEvaluationBuilder; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.impl.util.ReflectUtil; +import org.camunda.bpm.engine.repository.DecisionDefinition; +import org.camunda.bpm.engine.repository.DecisionDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.MockDecisionResultBuilder; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.sub.repository.impl.ProcessDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class DecisionDefinitionRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String DECISION_DEFINITION_URL = TEST_RESOURCE_ROOT_PATH + "/decision-definition"; + protected static final String SINGLE_DECISION_DEFINITION_URL = DECISION_DEFINITION_URL + "/{id}"; + protected static final String SINGLE_DECISION_DEFINITION_BY_KEY_URL = DECISION_DEFINITION_URL + "/key/{key}"; + protected static final String SINGLE_DECISION_DEFINITION_BY_KEY_AND_TENANT_ID_URL = DECISION_DEFINITION_URL + "/key/{key}/tenant-id/{tenant-id}"; + + protected static final String XML_DEFINITION_URL = SINGLE_DECISION_DEFINITION_URL + "/xml"; + protected static final String XML_DEFINITION_BY_KEY_URL = SINGLE_DECISION_DEFINITION_BY_KEY_URL + "/xml"; + + protected static final String DIAGRAM_DEFINITION_URL = SINGLE_DECISION_DEFINITION_URL + "/diagram"; + + protected static final String EVALUATE_DECISION_URL = SINGLE_DECISION_DEFINITION_URL + "/evaluate"; + protected static final String EVALUATE_DECISION_BY_KEY_URL = SINGLE_DECISION_DEFINITION_BY_KEY_URL + "/evaluate"; + protected static final String EVALUATE_DECISION_BY_KEY_AND_TENANT_ID_URL = SINGLE_DECISION_DEFINITION_BY_KEY_AND_TENANT_ID_URL + "/evaluate"; + protected static final String UPDATE_HISTORY_TIME_TO_LIVE_URL = SINGLE_DECISION_DEFINITION_URL + "/history-time-to-live"; + + private RepositoryService repositoryServiceMock; + private DecisionDefinitionQuery decisionDefinitionQueryMock; + private DecisionService decisionServiceMock; + private DecisionsEvaluationBuilder decisionEvaluationBuilderMock; + + @Before + public void setUpRuntime() { + DecisionDefinition mockDecisionDefinition = MockProvider.createMockDecisionDefinition(); + + setUpRuntimeData(mockDecisionDefinition); + setUpDecisionService(); + } + + private void setUpRuntimeData(DecisionDefinition mockDecisionDefinition) { + repositoryServiceMock = mock(RepositoryService.class); + + when(processEngine.getRepositoryService()).thenReturn(repositoryServiceMock); + when(repositoryServiceMock.getDecisionDefinition(eq(MockProvider.EXAMPLE_DECISION_DEFINITION_ID))).thenReturn(mockDecisionDefinition); + when(repositoryServiceMock.getDecisionModel(eq(MockProvider.EXAMPLE_DECISION_DEFINITION_ID))).thenReturn(createMockDecisionDefinitionDmnXml()); + + decisionDefinitionQueryMock = mock(DecisionDefinitionQuery.class); + when(decisionDefinitionQueryMock.decisionDefinitionKey(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY)).thenReturn(decisionDefinitionQueryMock); + when(decisionDefinitionQueryMock.tenantIdIn(anyString())).thenReturn(decisionDefinitionQueryMock); + when(decisionDefinitionQueryMock.withoutTenantId()).thenReturn(decisionDefinitionQueryMock); + when(decisionDefinitionQueryMock.latestVersion()).thenReturn(decisionDefinitionQueryMock); + when(decisionDefinitionQueryMock.singleResult()).thenReturn(mockDecisionDefinition); + when(decisionDefinitionQueryMock.list()).thenReturn(Collections.singletonList(mockDecisionDefinition)); + when(repositoryServiceMock.createDecisionDefinitionQuery()).thenReturn(decisionDefinitionQueryMock); + } + + private InputStream createMockDecisionDefinitionDmnXml() { + // do not close the input stream, will be done in implementation + InputStream dmnXmlInputStream = ReflectUtil.getResourceAsStream("decisions/decision-model.dmn"); + Assert.assertNotNull(dmnXmlInputStream); + return dmnXmlInputStream; + } + + private void setUpDecisionService() { + decisionEvaluationBuilderMock = mock(DecisionsEvaluationBuilder.class); + when(decisionEvaluationBuilderMock.variables(anyMap())).thenReturn(decisionEvaluationBuilderMock); + + decisionServiceMock = mock(DecisionService.class); + when(decisionServiceMock.evaluateDecisionById(MockProvider.EXAMPLE_DECISION_DEFINITION_ID)).thenReturn(decisionEvaluationBuilderMock); + when(decisionServiceMock.evaluateDecisionByKey(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY)).thenReturn(decisionEvaluationBuilderMock); + + when(processEngine.getDecisionService()).thenReturn(decisionServiceMock); + } + + @Test + public void testDecisionDefinitionDmnXmlRetrieval() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(XML_DEFINITION_URL); + + String responseContent = response.asString(); + Assert.assertTrue(responseContent.contains(MockProvider.EXAMPLE_DECISION_DEFINITION_ID)); + Assert.assertTrue(responseContent.contains(" emptyList()); + + given() + .pathParam("key", nonExistingKey) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching decision definition with key: " + nonExistingKey)) + .when() + .get(SINGLE_DECISION_DEFINITION_BY_KEY_URL); + } + + @Test + public void testDefinitionRetrieval_ByKeyAndTenantId() { + DecisionDefinition mockDefinition = MockProvider.mockDecisionDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(); + setUpRuntimeData(mockDefinition); + + given() + .pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_DECISION_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_DECISION_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_DECISION_DEFINITION_NAME)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_DECISION_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_DECISION_DEFINITION_RESOURCE_NAME)) + .body("decisionRequirementsDefinitionId", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)) + .body("decisionRequirementsDefinitionKey", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .when() + .get(SINGLE_DECISION_DEFINITION_BY_KEY_AND_TENANT_ID_URL); + + verify(decisionDefinitionQueryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(repositoryServiceMock).getDecisionDefinition(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + } + + @Test + public void testNonExistingDecisionDefinitionRetrieval_ByKeyAndTenantId() { + String nonExistingKey = "aNonExistingDefinitionKey"; + String nonExistingTenantId = "aNonExistingTenantId"; + + when(repositoryServiceMock.createDecisionDefinitionQuery().decisionDefinitionKey(nonExistingKey)).thenReturn(decisionDefinitionQueryMock); + when(decisionDefinitionQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("key", nonExistingKey) + .pathParam("tenant-id", nonExistingTenantId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching decision definition with key: " + nonExistingKey + " and tenant-id: " + nonExistingTenantId)) + .when().get(SINGLE_DECISION_DEFINITION_BY_KEY_AND_TENANT_ID_URL); + } + + @Test + public void testEvaluateDecisionByKeyAndTenantId() { + DecisionDefinition mockDefinition = MockProvider.mockDecisionDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(); + setUpRuntimeData(mockDefinition); + + DmnDecisionResult decisionResult = MockProvider.createMockDecisionResult(); + when(decisionEvaluationBuilderMock.evaluate()).thenReturn(decisionResult); + + Map json = new HashMap(); + json.put("variables", + VariablesBuilder.create() + .variable("amount", 420) + .variable("invoiceCategory", "MISC") + .getVariables() + ); + + given() + .pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(EVALUATE_DECISION_BY_KEY_AND_TENANT_ID_URL); + + Map expectedVariables = new HashMap(); + expectedVariables.put("amount", 420); + expectedVariables.put("invoiceCategory", "MISC"); + + verify(decisionDefinitionQueryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(decisionEvaluationBuilderMock).variables(expectedVariables); + verify(decisionEvaluationBuilderMock).evaluate(); + } + + @Test + public void testDecisionDiagramRetrieval() throws FileNotFoundException, URISyntaxException { + // setup additional mock behavior + File file = getFile("/processes/todo-process.png"); + when(repositoryServiceMock.getDecisionDiagram(MockProvider.EXAMPLE_DECISION_DEFINITION_ID)) + .thenReturn(new FileInputStream(file)); + + // call method + byte[] actual = given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/png") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DECISION_DEFINITION_DIAGRAM_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DECISION_DEFINITION_DIAGRAM_RESOURCE_NAME) + .when().get(DIAGRAM_DEFINITION_URL).getBody().asByteArray(); + + // verify service interaction + verify(repositoryServiceMock).getDecisionDefinition(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + verify(repositoryServiceMock).getDecisionDiagram(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + + // compare input stream with response body bytes + byte[] expected = IoUtil.readInputStream(new FileInputStream(file), "decision diagram"); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void testDecisionDiagramNullFilename() throws FileNotFoundException, URISyntaxException { + // setup additional mock behavior + File file = getFile("/processes/todo-process.png"); + when(repositoryServiceMock.getDecisionDefinition(MockProvider.EXAMPLE_DECISION_DEFINITION_ID).getDiagramResourceName()) + .thenReturn(null); + when(repositoryServiceMock.getDecisionDiagram(MockProvider.EXAMPLE_DECISION_DEFINITION_ID)) + .thenReturn(new FileInputStream(file)); + + // call method + byte[] actual = given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("application/octet-stream") + .header("Content-Disposition", "attachment; " + + "filename=\"" + null + "\"; "+ + "filename*=UTF-8''" + null) + .when().get(DIAGRAM_DEFINITION_URL).getBody().asByteArray(); + + // verify service interaction + verify(repositoryServiceMock).getDecisionDiagram(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + + // compare input stream with response body bytes + byte[] expected = IoUtil.readInputStream(new FileInputStream(file), "decision diagram"); + Assert.assertArrayEquals(expected, actual); + } + + @Test + public void testDecisionDiagramNotExist() { + // setup additional mock behavior + when(repositoryServiceMock.getDecisionDiagram(MockProvider.EXAMPLE_DECISION_DEFINITION_ID)).thenReturn(null); + + // call method + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().get(DIAGRAM_DEFINITION_URL); + + // verify service interaction + verify(repositoryServiceMock).getDecisionDefinition(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + verify(repositoryServiceMock).getDecisionDiagram(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + } + + @Test + public void testDecisionDiagramMediaType() { + Assert.assertEquals("image/png", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.png")); + Assert.assertEquals("image/png", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.PNG")); + Assert.assertEquals("image/svg+xml", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.svg")); + Assert.assertEquals("image/jpeg", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.jpeg")); + Assert.assertEquals("image/jpeg", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.jpg")); + Assert.assertEquals("image/gif", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.gif")); + Assert.assertEquals("image/bmp", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.bmp")); + Assert.assertEquals("application/octet-stream", ProcessDefinitionResourceImpl.getMediaTypeForFileSuffix("decision.UNKNOWN")); + } + + @Test + public void testEvaluateDecisionByKey() { + DmnDecisionResult decisionResult = MockProvider.createMockDecisionResult(); + + when(decisionEvaluationBuilderMock.evaluate()).thenReturn(decisionResult); + + Map json = new HashMap(); + json.put("variables", + VariablesBuilder.create() + .variable("amount", 420) + .variable("invoiceCategory", "MISC") + .getVariables() + ); + + given().pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(EVALUATE_DECISION_BY_KEY_URL); + + Map expectedVariables = new HashMap(); + expectedVariables.put("amount", 420); + expectedVariables.put("invoiceCategory", "MISC"); + + verify(decisionEvaluationBuilderMock).variables(expectedVariables); + verify(decisionEvaluationBuilderMock).evaluate(); + } + + @Test + public void testEvaluateDecisionById() { + DmnDecisionResult decisionResult = MockProvider.createMockDecisionResult(); + + when(decisionEvaluationBuilderMock.evaluate()).thenReturn(decisionResult); + + Map json = new HashMap(); + json.put("variables", + VariablesBuilder.create() + .variable("amount", 420) + .variable("invoiceCategory", "MISC") + .getVariables() + ); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(EVALUATE_DECISION_URL); + + Map expectedVariables = new HashMap(); + expectedVariables.put("amount", 420); + expectedVariables.put("invoiceCategory", "MISC"); + + verify(decisionEvaluationBuilderMock).variables(expectedVariables); + verify(decisionEvaluationBuilderMock).evaluate(); + } + + @Test + public void testEvaluateDecisionSingleDecisionOutput() { + DmnDecisionResult decisionResult = new MockDecisionResultBuilder() + .resultEntries() + .entry("status", Variables.stringValue("gold")) + .build(); + + when(decisionEvaluationBuilderMock.evaluate()).thenReturn(decisionResult); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("size()", is(1)) + .body("[0].size()", is(1)) + .body("[0].status", is(notNullValue())) + .body("[0].status.value", is("gold")) + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecisionMultipleDecisionOutputs() { + DmnDecisionResult decisionResult = new MockDecisionResultBuilder() + .resultEntries() + .entry("status", Variables.stringValue("gold")) + .resultEntries() + .entry("assignee", Variables.stringValue("manager")) + .build(); + + when(decisionEvaluationBuilderMock.evaluate()).thenReturn(decisionResult); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("size()", is(2)) + .body("[0].size()", is(1)) + .body("[0].status.value", is("gold")) + .body("[1].size()", is(1)) + .body("[1].assignee.value", is("manager")) + + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecisionMultipleDecisionValues() { + DmnDecisionResult decisionResult = new MockDecisionResultBuilder() + .resultEntries() + .entry("status", Variables.stringValue("gold")) + .entry("assignee", Variables.stringValue("manager")) + .build(); + + when(decisionEvaluationBuilderMock.evaluate()).thenReturn(decisionResult); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("size()", is(1)) + .body("[0].size()", is(2)) + .body("[0].status.value", is("gold")) + .body("[0].assignee.value", is("manager")) + + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecision_NotFound() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new NotFoundException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecisionByKey_NotFound() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new NotFoundException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_BY_KEY_URL); + } + + @Test + public void shouldReturnErrorCode() { + when(decisionEvaluationBuilderMock.evaluate()) + .thenThrow(new ProcessEngineException("foo", 123)); + + Map json = new HashMap<>(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("foo")) + .body("code", equalTo(123)) + .when().post(EVALUATE_DECISION_BY_KEY_URL); + } + + @Test + public void testEvaluateDecision_NotValid() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new NotValidException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecisionByKey_NotValid() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new NotValidException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_BY_KEY_URL); + } + + @Test + public void testEvaluateDecision_NotAuthorized() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new AuthorizationException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecisionByKey_NotAuthorized() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new AuthorizationException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_BY_KEY_URL); + } + + @Test + public void testEvaluateDecision_ProcessEngineException() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new ProcessEngineException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecisionByKey_ProcessEngineException() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new ProcessEngineException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_BY_KEY_URL); + } + + @Test + public void testEvaluateDecision_DmnEngineException() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new DmnEngineException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_URL); + } + + @Test + public void testEvaluateDecisionByKey_DmnEngineException() { + String message = "expected message"; + when(decisionEvaluationBuilderMock.evaluate()).thenThrow(new DmnEngineException(message)); + + Map json = new HashMap(); + json.put("variables", Collections.emptyMap()); + + given().pathParam("key", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString(message)) + .when().post(EVALUATE_DECISION_BY_KEY_URL); + } + + @Test + public void testUpdateHistoryTimeToLive() { + given() + .pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(5)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateDecisionDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_DECISION_DEFINITION_ID, 5); + } + + @Test + public void testUpdateHistoryTimeToLiveNullValue() { + given() + .pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .body(new HistoryTimeToLiveDto()) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateDecisionDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_DECISION_DEFINITION_ID, null); + } + + @Test + public void testUpdateHistoryTimeToLiveNegativeValue() { + String expectedMessage = "expectedMessage"; + + doThrow(new BadUserRequestException(expectedMessage)) + .when(repositoryServiceMock) + .updateDecisionDefinitionHistoryTimeToLive(eq(MockProvider.EXAMPLE_DECISION_DEFINITION_ID), eq(-1)); + + given() + .pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(-1)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(BadUserRequestException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateDecisionDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_DECISION_DEFINITION_ID, -1); + } + + @Test + public void testUpdateHistoryTimeToLiveAuthorizationException() { + String expectedMessage = "expectedMessage"; + + doThrow(new AuthorizationException(expectedMessage)) + .when(repositoryServiceMock) + .updateDecisionDefinitionHistoryTimeToLive(eq(MockProvider.EXAMPLE_DECISION_DEFINITION_ID), eq(5)); + + given() + .pathParam("id", MockProvider.EXAMPLE_DECISION_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(5)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(UPDATE_HISTORY_TIME_TO_LIVE_URL); + + verify(repositoryServiceMock).updateDecisionDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_DECISION_DEFINITION_ID, 5); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5f9f8487f5ecc2837581e2678ccc17e2c1e25d5b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionDefinitionRestServiceQueryTest.java @@ -0,0 +1,596 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.repository.DecisionDefinition; +import org.camunda.bpm.engine.repository.DecisionDefinitionQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class DecisionDefinitionRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String DECISION_DEFINITION_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/decision-definition"; + protected static final String DECISION_DEFINITION_COUNT_QUERY_URL = DECISION_DEFINITION_QUERY_URL + "/count"; + + private DecisionDefinitionQuery mockedQuery; + + @Before + public void setUpRuntime() { + mockedQuery = createMockDecisionDefinitionQuery(MockProvider.createMockDecisionDefinitions()); + } + + private DecisionDefinitionQuery createMockDecisionDefinitionQuery(List mockedDefinitions) { + DecisionDefinitionQuery sampleDefinitionsQuery = mock(DecisionDefinitionQuery.class); + + when(sampleDefinitionsQuery.list()).thenReturn(mockedDefinitions); + when(sampleDefinitionsQuery.count()).thenReturn((long) mockedDefinitions.size()); + when(processEngine.getRepositoryService().createDecisionDefinitionQuery()).thenReturn(sampleDefinitionsQuery); + + return sampleDefinitionsQuery; + } + + @Test + public void testEmptyQuery() { + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testInvalidNumericParameter() { + String anInvalidIntegerQueryParam = "aString"; + + given() + .queryParam("version", anInvalidIntegerQueryParam) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'version' to value 'aString': " + + "Cannot convert value aString to java type java.lang.Integer")) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + } + + /** + * We assume that boolean query parameters that are not "true" + * or "false" are evaluated to "false" and don't cause a 400 error. + */ + @Test + public void testInvalidBooleanParameter() { + String anInvalidBooleanQueryParam = "neitherTrueNorFalse"; + given() + .queryParam("active", anInvalidBooleanQueryParam) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("id", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "id") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + } + + @Test + public void testSortingParameters() { + // asc + InOrder inOrder = inOrder(mockedQuery); + executeAndVerifySorting("id", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("name", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("version", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionVersion(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("key", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("category", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionCategory(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("deployTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("decisionRequirementsDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + // desc + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("id", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("name", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("version", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionVersion(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("key", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("category", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionDefinitionCategory(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("deployTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("versionTag", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByVersionTag(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("versionTag", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByVersionTag(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySorting("decisionRequirementsDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testDecisionDefinitionRetrieval() { + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> decisionDefinitions = from(content).getList(""); + + assertThat(decisionDefinitions).hasSize(1); + assertThat(decisionDefinitions.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedKey = from(content).getString("[0].key"); + String returnedCategory = from(content).getString("[0].category"); + String returnedName = from(content).getString("[0].name"); + int returnedVersion = from(content).getInt("[0].version"); + String returnedResource = from(content).getString("[0].resource"); + String returnedDeploymentId = from(content).getString("[0].deploymentId"); + String returnedDecisionRequirementsDefinitionId = from(content).getString("[0].decisionRequirementsDefinitionId"); + String returnedDecisionRequirementsDefinitionKey = from(content).getString("[0].decisionRequirementsDefinitionKey"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + assertThat(returnedKey).isEqualTo(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY); + assertThat(returnedCategory).isEqualTo(MockProvider.EXAMPLE_DECISION_DEFINITION_CATEGORY); + assertThat(returnedName).isEqualTo(MockProvider.EXAMPLE_DECISION_DEFINITION_NAME); + assertThat(returnedVersion).isEqualTo(MockProvider.EXAMPLE_DECISION_DEFINITION_VERSION); + assertThat(returnedResource).isEqualTo(MockProvider.EXAMPLE_DECISION_DEFINITION_RESOURCE_NAME); + assertThat(returnedDeploymentId).isEqualTo(MockProvider.EXAMPLE_DEPLOYMENT_ID); + assertThat(returnedDecisionRequirementsDefinitionId).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + assertThat(returnedDecisionRequirementsDefinitionKey).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testDecisionDefinitionRetrievalByList() { + mockedQuery = createMockDecisionDefinitionQuery(MockProvider.createMockTwoDecisionDefinitions()); + + Response response = given() + .queryParam("decisionDefinitionIdIn", MockProvider.EXAMPLE_DECISION_DEFINITION_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionIdIn(MockProvider.EXAMPLE_DECISION_DEFINITION_ID, MockProvider.ANOTHER_EXAMPLE_DECISION_DEFINITION_ID); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedDefinitionId1 = from(content).getString("[0].id"); + String returnedDefinitionId2 = from(content).getString("[1].id"); + + assertThat(returnedDefinitionId1).isEqualTo(MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + assertThat(returnedDefinitionId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_DECISION_DEFINITION_ID); + } + + @Test + public void testDecisionDefinitionRetrievalByEmptyList() { + given() + .queryParam("decisionDefinitionIdIn", "") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery, never()).decisionDefinitionIdIn(Mockito.any()); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testAdditionalParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given() + .queryParams(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + // assert query invocation + verify(mockedQuery).decisionDefinitionId(queryParameters.get("decisionDefinitionId")); + verify(mockedQuery).decisionDefinitionCategory(queryParameters.get("category")); + verify(mockedQuery).decisionDefinitionCategoryLike(queryParameters.get("categoryLike")); + verify(mockedQuery).decisionDefinitionName(queryParameters.get("name")); + verify(mockedQuery).decisionDefinitionNameLike(queryParameters.get("nameLike")); + verify(mockedQuery).deploymentId(queryParameters.get("deploymentId")); + verify(mockedQuery).decisionDefinitionKey(queryParameters.get("key")); + verify(mockedQuery).decisionDefinitionKeyLike(queryParameters.get("keyLike")); + verify(mockedQuery).decisionDefinitionVersion(Integer.parseInt(queryParameters.get("version"))); + verify(mockedQuery).latestVersion(); + verify(mockedQuery).decisionDefinitionResourceName(queryParameters.get("resourceName")); + verify(mockedQuery).decisionDefinitionResourceNameLike(queryParameters.get("resourceNameLike")); + verify(mockedQuery).decisionRequirementsDefinitionId(queryParameters.get("decisionRequirementsDefinitionId")); + verify(mockedQuery).decisionRequirementsDefinitionKey(queryParameters.get("decisionRequirementsDefinitionKey")); + verify(mockedQuery).versionTag(queryParameters.get("versionTag")); + verify(mockedQuery).versionTagLike(queryParameters.get("versionTagLike")); + verify(mockedQuery).withoutDecisionRequirementsDefinition(); + verify(mockedQuery).deployedAfter(DateTimeUtil.parseDate(queryParameters.get("deployedAfter"))); + verify(mockedQuery).deployedAt(DateTimeUtil.parseDate(queryParameters.get("deployedAt"))); + verify(mockedQuery).list(); + } + + @Test + public void testDecisionDefinitionTenantIdList() { + List decisionDefinitions = Arrays.asList( + MockProvider.mockDecisionDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.mockDecisionDefinition().id(MockProvider.ANOTHER_EXAMPLE_CASE_DEFINITION_ID).tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build()); + mockedQuery = createMockDecisionDefinitionQuery(decisionDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testDecisionDefinitionWithoutTenantId() { + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testDecisionDefinitionTenantIdIncludeDefinitionsWithoutTenantid() { + List decisionDefinitions = Arrays.asList( + MockProvider.mockDecisionDefinition().tenantId(null).build(), + MockProvider.mockDecisionDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockedQuery = createMockDecisionDefinitionQuery(decisionDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("includeDecisionDefinitionsWithoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockedQuery).includeDecisionDefinitionsWithoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(DECISION_DEFINITION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testDecisionDefinitionVersionTag() { + List decisionDefinitions = Arrays.asList( + MockProvider.mockDecisionDefinition().versionTag(MockProvider.EXAMPLE_VERSION_TAG).build(), + MockProvider.mockDecisionDefinition().id(MockProvider.ANOTHER_EXAMPLE_DECISION_DEFINITION_ID).versionTag(MockProvider.ANOTHER_EXAMPLE_VERSION_TAG).build()); + mockedQuery = createMockDecisionDefinitionQuery(decisionDefinitions); + + given() + .queryParam("versionTag", MockProvider.EXAMPLE_VERSION_TAG) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).versionTag(MockProvider.EXAMPLE_VERSION_TAG); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByDeployTimeAfter() { + String deployTime = withTimezone("2020-03-27T00:00:00"); + Date date = DateTimeUtil.parseDate(deployTime); + + given().queryParam("deployedAfter", deployTime) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).deployedAfter(date); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByDeployTimeAt() { + String deployTime = withTimezone("2020-03-27T00:00:00"); + Date date = DateTimeUtil.parseDate(deployTime); + + given().queryParam("deployedAt", deployTime) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DECISION_DEFINITION_QUERY_URL); + + verify(mockedQuery).deployedAt(date); + verify(mockedQuery).list(); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("decisionDefinitionId", "anId"); + parameters.put("category", "cat"); + parameters.put("categoryLike", "catlike"); + parameters.put("name", "name"); + parameters.put("nameLike", "namelike"); + parameters.put("deploymentId", "depId"); + parameters.put("deployedAfter", withTimezone("2020-03-27T00:00:00")); + parameters.put("deployedAt", withTimezone("2020-03-27T00:00:00")); + parameters.put("key", "key"); + parameters.put("keyLike", "keylike"); + parameters.put("version", "1"); + parameters.put("latestVersion", "true"); + parameters.put("resourceName", "res"); + parameters.put("resourceNameLike", "resLike"); + parameters.put("decisionRequirementsDefinitionId", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + parameters.put("decisionRequirementsDefinitionKey", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + parameters.put("withoutDecisionRequirementsDefinition", "true"); + parameters.put("versionTag", "semVer"); + parameters.put("versionTagLike", "semVerLike"); + + return parameters; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionRequirementsDefinitionRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionRequirementsDefinitionRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ab36c1793394628f136542ffc96ba1dc4d5e39ca --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DecisionRequirementsDefinitionRestServiceInteractionTest.java @@ -0,0 +1,285 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.URISyntaxException; +import java.util.Collections; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.DecisionService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.impl.util.ReflectUtil; +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinition; +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinitionQuery; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +/** + * + * @author Deivarayan Azhagappan + * + */ + +public class DecisionRequirementsDefinitionRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String DECISION_REQUIREMENTS_DEFINITION_URL = TEST_RESOURCE_ROOT_PATH + "/decision-requirements-definition"; + protected static final String SINGLE_DECISION_REQUIREMENTS_DEFINITION_ID_URL = DECISION_REQUIREMENTS_DEFINITION_URL + "/{id}"; + protected static final String SINGLE_DECISION_REQUIREMENTS_DEFINITION_KEY_URL = DECISION_REQUIREMENTS_DEFINITION_URL + "/key/{key}"; + protected static final String SINGLE_DECISION_REQUIREMENTS_DEFINITION_KEY_AND_TENANT_ID_URL = DECISION_REQUIREMENTS_DEFINITION_URL + "/key/{key}/tenant-id/{tenant-id}"; + + protected static final String XML_DEFINITION_URL = SINGLE_DECISION_REQUIREMENTS_DEFINITION_ID_URL + "/xml"; + + protected static final String DIAGRAM_DEFINITION_URL = SINGLE_DECISION_REQUIREMENTS_DEFINITION_ID_URL + "/diagram"; + + protected RepositoryService repositoryServiceMock; + protected DecisionRequirementsDefinitionQuery decisionRequirementsDefinitionQueryMock; + protected DecisionService decisionServiceMock; + + @Before + public void setUpRuntime() throws FileNotFoundException, URISyntaxException { + DecisionRequirementsDefinition mockDecisionRequirementsDefinition = MockProvider.createMockDecisionRequirementsDefinition(); + + setUpRuntimeData(mockDecisionRequirementsDefinition); + decisionServiceMock = mock(DecisionService.class); + when(processEngine.getDecisionService()).thenReturn(decisionServiceMock); + } + + @Test + public void decisionRequirementsDefinitionRetrievalById() { + given() + .pathParam("id", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME)) + .body("tenantId", equalTo(null)) + .when() + .get(SINGLE_DECISION_REQUIREMENTS_DEFINITION_ID_URL); + + verify(repositoryServiceMock).getDecisionRequirementsDefinition(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + } + + @Test + public void nonExistingDecisionRequirementsDefinitionRetrieval() { + String nonExistingId = "aNonExistingDefinitionId"; + + when(repositoryServiceMock.getDecisionRequirementsDefinition(eq(nonExistingId))).thenThrow(new ProcessEngineException("No matching decision requirements definition")); + + given() + .pathParam("id", "aNonExistingDefinitionId") + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching decision requirements definition")) + .when().get(SINGLE_DECISION_REQUIREMENTS_DEFINITION_ID_URL); + } + + @Test + public void decisionRequirementsDefinitionRetrievalByKey() { + given() + .pathParam("key", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME)) + .body("tenantId", equalTo(null)) + .when() + .get(SINGLE_DECISION_REQUIREMENTS_DEFINITION_KEY_URL); + + verify(repositoryServiceMock).getDecisionRequirementsDefinition(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + } + + @Test + public void decisionRequirementsDefinitionRetrievalByNonExistingKey() { + + String nonExistingKey = "aNonExistingRequirementsDefinitionKey"; + + when(repositoryServiceMock.createDecisionRequirementsDefinitionQuery() + .decisionRequirementsDefinitionKey(nonExistingKey)) + .thenReturn(decisionRequirementsDefinitionQueryMock); + + when(decisionRequirementsDefinitionQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("key", nonExistingKey) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching decision requirements definition with key: " + nonExistingKey)) + .when() + .get(SINGLE_DECISION_REQUIREMENTS_DEFINITION_KEY_URL); + + } + + @Test + public void decisionRequirementsDefinitionRetrievalByKeyAndTenantId() throws FileNotFoundException, URISyntaxException { + DecisionRequirementsDefinition mockDefinition = MockProvider.mockDecisionRequirementsDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(); + setUpRuntimeData(mockDefinition); + + given() + .pathParam("key", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .when() + .get(SINGLE_DECISION_REQUIREMENTS_DEFINITION_KEY_AND_TENANT_ID_URL); + + verify(decisionRequirementsDefinitionQueryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(repositoryServiceMock).getDecisionRequirementsDefinition(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + } + + @Test + public void nonExistingDecisionRequirementsDefinitionRetrievalByKeyAndTenantId() { + String nonExistingKey = "aNonExistingDecisionDefinitionRequirementsDefinitionKey"; + String nonExistingTenantId = "aNonExistingTenantId"; + + when(repositoryServiceMock.createDecisionRequirementsDefinitionQuery() + .decisionRequirementsDefinitionKey(nonExistingKey)) + .thenReturn(decisionRequirementsDefinitionQueryMock); + when(decisionRequirementsDefinitionQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("key", nonExistingKey) + .pathParam("tenant-id", nonExistingTenantId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching decision requirements definition with key: " + nonExistingKey + " and tenant-id: " + nonExistingTenantId)) + .when().get(SINGLE_DECISION_REQUIREMENTS_DEFINITION_KEY_AND_TENANT_ID_URL); + } + + // dmn xml retrieval + @Test + public void decisionRequirementsDefinitionDmnXmlRetrieval() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(XML_DEFINITION_URL); + + String responseContent = response.asString(); + Assert.assertTrue(responseContent.contains(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)); + Assert.assertTrue(responseContent.contains(" mockedDefinitions) { + DecisionRequirementsDefinitionQuery query = mock(DecisionRequirementsDefinitionQuery.class); + + when(query.list()).thenReturn(mockedDefinitions); + when(query.count()).thenReturn((long) mockedDefinitions.size()); + when(processEngine.getRepositoryService().createDecisionRequirementsDefinitionQuery()).thenReturn(query); + + return query; + } + + @Test + public void testEmptyQuery() { + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testInvalidNumericParameter() { + String anInvalidIntegerQueryParam = "aString"; + + given() + .queryParam("version", anInvalidIntegerQueryParam) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'version' to value 'aString': " + + "Cannot convert value aString to java type java.lang.Integer")) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + } + + @Test + public void testInvalidBooleanParameter() { + String anInvalidBooleanQueryParam = "neitherTrueNorFalse"; + + given().queryParam("latestVersion", anInvalidBooleanQueryParam) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'latestVersion' to value 'neitherTrueNorFalse': " + + "Cannot convert value neitherTrueNorFalse to java type java.lang.Boolean")) + .when().get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("id", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "id") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + } + + @Test + public void testSortingParameters() { + // asc + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("id", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("name", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("version", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionVersion(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("key", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("category", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionCategory(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + // desc + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("id", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("name", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("version", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionVersion(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("key", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("category", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDecisionRequirementsDefinitionCategory(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testDecisionRequirementsDefinitionRetrieval() { + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> decisionRequirementsDefinitions = from(content).getList(""); + + assertThat(decisionRequirementsDefinitions).hasSize(1); + assertThat(decisionRequirementsDefinitions.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedKey = from(content).getString("[0].key"); + String returnedCategory = from(content).getString("[0].category"); + String returnedName = from(content).getString("[0].name"); + int returnedVersion = from(content).getInt("[0].version"); + String returnedResource = from(content).getString("[0].resource"); + String returnedDeploymentId = from(content).getString("[0].deploymentId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + assertThat(returnedKey).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + assertThat(returnedCategory).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY); + assertThat(returnedName).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME); + assertThat(returnedVersion).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION); + assertThat(returnedResource).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME); + assertThat(returnedDeploymentId).isEqualTo(MockProvider.EXAMPLE_DEPLOYMENT_ID); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testDecisionRequirementsDefinitionRetrievalByList() { + mockedQuery = createMockQuery(MockProvider.createMockTwoDecisionRequirementsDefinitions()); + + Response response = given() + .queryParam("decisionRequirementsDefinitionIdIn", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionRequirementsDefinitionIdIn(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID, MockProvider.ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedDefinitionId1 = from(content).getString("[0].id"); + String returnedDefinitionId2 = from(content).getString("[1].id"); + + assertThat(returnedDefinitionId1).isEqualTo(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + assertThat(returnedDefinitionId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + } + + @Test + public void testDecisionRequirementsDefinitionRetrievalByEmptyList() { + given() + .queryParam("decisionRequirementsDefinitionIdIn", "") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery, never()).decisionRequirementsDefinitionIdIn(Mockito.any()); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testAdditionalParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given() + .queryParams(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + // assert query invocation + verify(mockedQuery).decisionRequirementsDefinitionId(queryParameters.get("decisionRequirementsDefinitionId")); + verify(mockedQuery).decisionRequirementsDefinitionCategory(queryParameters.get("category")); + verify(mockedQuery).decisionRequirementsDefinitionCategoryLike(queryParameters.get("categoryLike")); + verify(mockedQuery).decisionRequirementsDefinitionName(queryParameters.get("name")); + verify(mockedQuery).decisionRequirementsDefinitionNameLike(queryParameters.get("nameLike")); + verify(mockedQuery).decisionRequirementsDefinitionKey(queryParameters.get("key")); + verify(mockedQuery).decisionRequirementsDefinitionKeyLike(queryParameters.get("keyLike")); + verify(mockedQuery).decisionRequirementsDefinitionVersion(Integer.parseInt(queryParameters.get("version"))); + verify(mockedQuery).latestVersion(); + verify(mockedQuery).decisionRequirementsDefinitionResourceName(queryParameters.get("resourceName")); + verify(mockedQuery).decisionRequirementsDefinitionResourceNameLike(queryParameters.get("resourceNameLike")); + verify(mockedQuery).deploymentId(queryParameters.get("deploymentId")); + verify(mockedQuery).list(); + } + + @Test + public void testDecisionRequirementDefinitionTenantIdList() { + List decisionRequirementsDefinitions = Arrays.asList( + MockProvider.mockDecisionRequirementsDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.createAnotherMockDecisionRequirementsDefinition()); + mockedQuery = createMockQuery(decisionRequirementsDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testDecisionRequirementsDefinitionWithoutTenantId() { + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testDecisionRequirementsDefinitionTenantIdIncludeDefinitionsWithoutTenantid() { + List decisionDefinitions = Arrays.asList( + MockProvider.mockDecisionRequirementsDefinition().tenantId(null).build(), + MockProvider.mockDecisionRequirementsDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockedQuery = createMockQuery(decisionDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("includeDecisionRequirementsDefinitionsWithoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DECISION_REQUIREMENTS_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockedQuery).includeDecisionRequirementsDefinitionsWithoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(DECISION_REQUIREMENTS_DEFINITION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("decisionRequirementsDefinitionId", "anId"); + parameters.put("category", "cat"); + parameters.put("categoryLike", "catlike"); + parameters.put("name", "name"); + parameters.put("nameLike", "namelike"); + parameters.put("key", "key"); + parameters.put("keyLike", "keylike"); + parameters.put("version", "1"); + parameters.put("latestVersion", "true"); + parameters.put("resourceName", "res"); + parameters.put("resourceNameLike", "resLike"); + parameters.put("deploymentId", "depId"); + + return parameters; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DeploymentRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DeploymentRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..38b287ae7b50721a7b08b7f72f57b640fdd32501 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DeploymentRestServiceInteractionTest.java @@ -0,0 +1,2176 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import io.restassured.http.ContentType; +import io.restassured.path.json.JsonPath; +import io.restassured.response.Response; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ParseException; +import org.camunda.bpm.engine.Problem; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.ResourceReport; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.bpmn.parser.ResourceReportImpl; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.util.ReflectUtil; +import org.camunda.bpm.engine.repository.*; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.model.bpmn.Bpmn; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.*; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.helper.MockProvider.*; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.*; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.*; + +public class DeploymentRestServiceInteractionTest extends AbstractRestServiceTest { + + protected static final String PROPERTY_DEPLOYED_PROCESS_DEFINITIONS = "deployedProcessDefinitions"; + protected static final String PROPERTY_DEPLOYED_CASE_DEFINITIONS = "deployedCaseDefinitions"; + protected static final String PROPERTY_DEPLOYED_DECISION_DEFINITIONS = "deployedDecisionDefinitions"; + protected static final String PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS = "deployedDecisionRequirementsDefinitions"; + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/deployment"; + protected static final String DEPLOYMENT_URL = RESOURCE_URL + "/{id}"; + protected static final String RESOURCES_URL = DEPLOYMENT_URL + "/resources"; + protected static final String SINGLE_RESOURCE_URL = RESOURCES_URL + "/{resourceId}"; + protected static final String SINGLE_RESOURCE_DATA_URL = SINGLE_RESOURCE_URL + "/data"; + protected static final String CREATE_DEPLOYMENT_URL = RESOURCE_URL + "/create"; + protected static final String REDEPLOY_DEPLOYMENT_URL = DEPLOYMENT_URL + "/redeploy"; + + protected RepositoryService mockRepositoryService; + protected Deployment mockDeployment; + protected DeploymentWithDefinitions mockDeploymentWithDefinitions; + protected List mockDeploymentResources; + protected Resource mockDeploymentResource; + protected DeploymentQuery mockDeploymentQuery; + protected DeploymentBuilder mockDeploymentBuilder; + protected Collection resourceNames = new ArrayList<>(); + + @Before + public void setUpRuntimeData() { + mockRepositoryService = mock(RepositoryService.class); + when(processEngine.getRepositoryService()).thenReturn(mockRepositoryService); + + mockDeployment = MockProvider.createMockDeployment(); + mockDeploymentWithDefinitions = MockProvider.createMockDeploymentWithDefinitions(); + mockDeploymentQuery = mock(DeploymentQuery.class); + when(mockDeploymentQuery.deploymentId(EXAMPLE_DEPLOYMENT_ID)).thenReturn(mockDeploymentQuery); + when(mockDeploymentQuery.singleResult()).thenReturn(mockDeployment); + when(mockRepositoryService.createDeploymentQuery()).thenReturn(mockDeploymentQuery); + + mockDeploymentResources = MockProvider.createMockDeploymentResources(); + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(mockDeploymentResources); + + mockDeploymentResource = MockProvider.createMockDeploymentResource(); + + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_RESOURCE_ID))).thenReturn(createMockDeploymentResourceBpmnData()); + + mockDeploymentBuilder = mock(DeploymentBuilder.class); + when(mockRepositoryService.createDeployment()).thenReturn(mockDeploymentBuilder); + when(mockDeploymentBuilder.addInputStream(anyString(), any(InputStream.class))).thenReturn(mockDeploymentBuilder); + when(mockDeploymentBuilder.addDeploymentResourcesById(anyString(), anyList())).thenReturn(mockDeploymentBuilder); + when(mockDeploymentBuilder.addDeploymentResourcesByName(anyString(), anyList())).thenReturn(mockDeploymentBuilder); + when(mockDeploymentBuilder.source(anyString())).thenReturn(mockDeploymentBuilder); + when(mockDeploymentBuilder.tenantId(anyString())).thenReturn(mockDeploymentBuilder); + when(mockDeploymentBuilder.getResourceNames()).thenReturn(resourceNames); + when(mockDeploymentBuilder.deployWithResult()).thenReturn(mockDeploymentWithDefinitions); + } + + private byte[] createMockDeploymentResourceByteData() { + return "someContent".getBytes(); + } + + private InputStream createMockDeploymentResourceBpmnData() { + // do not close the input stream, will be done in implementation + InputStream bpmn20XmlIn = ReflectUtil.getResourceAsStream("processes/fox-invoice_en_long_id.bpmn"); + assertNotNull(bpmn20XmlIn); + return bpmn20XmlIn; + } + + private InputStream createMockDeploymentResourceBpmnDataNonExecutableProcess() { + // do not close the input stream, will be done in implementation + String model = Bpmn.convertToString(Bpmn.createProcess().startEvent().endEvent().done()); + InputStream inputStream = new ByteArrayInputStream(model.getBytes()); + return inputStream; + } + + private InputStream createMockDeploymentResourceSvgData() { + // do not close the input stream, will be done in implementation + InputStream image = ReflectUtil.getResourceAsStream("processes/diagram.svg"); + assertNotNull(image); + return image; + } + + @Test + public void testGetSingleDeployment() { + + Response response = given().pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_URL); + + verifyDeployment(mockDeployment, response); + + } + + @Test + public void testGetNonExistingSingleDeployment() { + + when(mockDeploymentQuery.deploymentId(NON_EXISTING_DEPLOYMENT_ID)).thenReturn(mockDeploymentQuery); + when(mockDeploymentQuery.singleResult()).thenReturn(null); + + given().pathParam("id", NON_EXISTING_DEPLOYMENT_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment with id '" + NON_EXISTING_DEPLOYMENT_ID + "' does not exist")) + .when().get(DEPLOYMENT_URL); + + } + + @Test + public void testGetDeploymentResources() { + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(RESOURCES_URL); + + verifyDeploymentResources(mockDeploymentResources, response); + + } + + @Test + public void testGetNonExistingDeploymentResources() { + + given().pathParam("id", NON_EXISTING_DEPLOYMENT_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment resources for deployment id '" + NON_EXISTING_DEPLOYMENT_ID + "' do not exist.")) + .when().get(RESOURCES_URL); + + } + + @Test + public void testGetDeploymentResourcesThrowsAuthorizationException() { + String message = "expected exception"; + when(mockRepositoryService.getDeploymentResources(EXAMPLE_DEPLOYMENT_ID)).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when().get(RESOURCES_URL); + } + + @Test + public void testGetDeploymentResource() { + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(SINGLE_RESOURCE_URL); + + verifyDeploymentResource(mockDeploymentResource, response); + + } + + @Test + public void testGetNonExistingDeploymentResource() { + + given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", NON_EXISTING_DEPLOYMENT_RESOURCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment resource with resource id '" + NON_EXISTING_DEPLOYMENT_RESOURCE_ID + "' for deployment id '" + EXAMPLE_DEPLOYMENT_ID + "' does not exist.")) + .when().get(SINGLE_RESOURCE_URL); + + } + + @Test + public void testGetDeploymentResourceWithNonExistingDeploymentId() { + + given() + .pathParam("id", NON_EXISTING_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment resources for deployment id '" + NON_EXISTING_DEPLOYMENT_ID + "' do not exist.")) + .when().get(SINGLE_RESOURCE_URL); + + } + + @Test + public void testGetDeploymentResourceWithNonExistingDeploymentIdAndNonExistingResourceId() { + + given() + .pathParam("id", NON_EXISTING_DEPLOYMENT_ID) + .pathParam("resourceId", NON_EXISTING_DEPLOYMENT_RESOURCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment resources for deployment id '" + NON_EXISTING_DEPLOYMENT_ID + "' do not exist.")) + .when().get(SINGLE_RESOURCE_URL); + + } + + @Test + public void testGetDeploymentResourceThrowsAuthorizationException() { + String message = "expected exception"; + when(mockRepositoryService.getDeploymentResources(EXAMPLE_DEPLOYMENT_ID)).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .get(SINGLE_RESOURCE_URL); + } + + @Test + public void testGetDeploymentResourceData() { + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("application/octet-stream") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(" resources = new ArrayList<>(); + resources.add(resource); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_SVG_RESOURCE_ID))).thenReturn(createMockDeploymentResourceSvgData()); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_SVG_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/svg+xml") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_SVG_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_SVG_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(" resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_PNG_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_PNG_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/png") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_PNG_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_PNG_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentGifResourceData() { + Resource resource = MockProvider.createMockDeploymentGifResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_GIF_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_GIF_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/gif") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_GIF_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_GIF_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentJpgResourceData() { + Resource resource = MockProvider.createMockDeploymentJpgResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_JPG_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_JPG_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/jpeg") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_JPG_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_JPG_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentJpegResourceData() { + Resource resource = MockProvider.createMockDeploymentJpegResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/jpeg") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentJpeResourceData() { + Resource resource = MockProvider.createMockDeploymentJpeResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_JPE_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_JPE_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/jpeg") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_JPE_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_JPE_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentTifResourceData() { + Resource resource = MockProvider.createMockDeploymentTifResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_TIF_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_TIF_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/tiff") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_TIF_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_TIF_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentTiffResourceData() { + Resource resource = MockProvider.createMockDeploymentTiffResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("image/tiff") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentBpmnResourceData() { + Resource resource = MockProvider.createMockDeploymentBpmnResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_ID))).thenReturn(createMockDeploymentResourceBpmnData()); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentBpmnXmlResourceData() { + Resource resource = MockProvider.createMockDeploymentBpmnXmlResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_ID))).thenReturn(createMockDeploymentResourceBpmnData()); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentCmmnResourceData() { + Resource resource = MockProvider.createMockDeploymentCmmnResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentCmmnXmlResourceData() { + Resource resource = MockProvider.createMockDeploymentCmmnXmlResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentDmnResourceData() { + Resource resource = MockProvider.createMockDeploymentDmnResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_DMN_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_DMN_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_DMN_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_DMN_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentDmnXmlResourceData() { + Resource resource = MockProvider.createMockDeploymentDmnXmlResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentXmlResourceData() { + Resource resource = MockProvider.createMockDeploymentXmlResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_XML_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_XML_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_XML_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_XML_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentJsonResourceData() { + Resource resource = MockProvider.createMockDeploymentJsonResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_JSON_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_JSON_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_JSON_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_JSON_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentGroovyResourceData() { + Resource resource = MockProvider.createMockDeploymentGroovyResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentJavaResourceData() { + Resource resource = MockProvider.createMockDeploymentJavaResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentJsResourceData() { + Resource resource = MockProvider.createMockDeploymentJsResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_JS_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_JS_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_JS_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_JS_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentPythonResourceData() { + Resource resource = MockProvider.createMockDeploymentPythonResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentRubyResourceData() { + Resource resource = MockProvider.createMockDeploymentRubyResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentPhpResourceData() { + Resource resource = MockProvider.createMockDeploymentPhpResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_PHP_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_PHP_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_PHP_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_PHP_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentHtmlpResourceData() { + Resource resource = MockProvider.createMockDeploymentHtmlResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_HTML_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_HTML_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.HTML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_HTML_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_HTML_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentTxtResourceData() { + Resource resource = MockProvider.createMockDeploymentTxtResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_TXT_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_TXT_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_TXT_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_TXT_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentCamundaFormResourceData() { + Resource resource = MockProvider.createMockDeploymentCamundaFormResource(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("application/octet-stream") + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentResourceDataFilename() { + Resource resource = MockProvider.createMockDeploymentResourceFilename(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentResourceDataFilenameBackslash() { + Resource resource = MockProvider.createMockDeploymentResourceFilenameBackslash(); + + List resources = new ArrayList<>(); + resources.add(resource); + + InputStream input = new ByteArrayInputStream(createMockDeploymentResourceByteData()); + + when(mockRepositoryService.getDeploymentResources(eq(EXAMPLE_DEPLOYMENT_ID))).thenReturn(resources); + when(mockRepositoryService.getResourceAsStreamById(eq(EXAMPLE_DEPLOYMENT_ID), eq(EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_ID))).thenReturn(input); + + Response response = given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.XML) + .header("Content-Disposition", "attachment; " + + "filename=\"" + MockProvider.EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_NAME + "\"; " + + "filename*=UTF-8''" + MockProvider.EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_NAME) + .when().get(SINGLE_RESOURCE_DATA_URL); + + String responseContent = response.asString(); + assertNotNull(responseContent); + } + + @Test + public void testGetDeploymentResourceDataForNonExistingDeploymentId() { + + given() + .pathParam("id", NON_EXISTING_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment resource '" + EXAMPLE_DEPLOYMENT_RESOURCE_ID + "' for deployment id '" + NON_EXISTING_DEPLOYMENT_ID + "' does not exist.")) + .when().get(SINGLE_RESOURCE_DATA_URL); + + } + + @Test + public void testGetDeploymentResourceDataForNonExistingResourceId() { + + given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", NON_EXISTING_DEPLOYMENT_RESOURCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment resource '" + NON_EXISTING_DEPLOYMENT_RESOURCE_ID + "' for deployment id '" + EXAMPLE_DEPLOYMENT_ID + "' does not exist.")) + .when().get(SINGLE_RESOURCE_DATA_URL); + + } + + @Test + public void testGetDeploymentResourceDataForNonExistingDeploymentIdAndNonExistingResourceId() { + + given() + .pathParam("id", NON_EXISTING_DEPLOYMENT_ID) + .pathParam("resourceId", NON_EXISTING_DEPLOYMENT_RESOURCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment resource '" + NON_EXISTING_DEPLOYMENT_RESOURCE_ID + "' for deployment id '" + NON_EXISTING_DEPLOYMENT_ID + "' does not exist.")) + .when().get(SINGLE_RESOURCE_DATA_URL); + + } + + @Test + public void testGetDeploymentResourceDataThrowsAuthorizationException() { + String message = "expected exception"; + when(mockRepositoryService.getResourceAsStreamById(EXAMPLE_DEPLOYMENT_ID, EXAMPLE_DEPLOYMENT_RESOURCE_ID)).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", EXAMPLE_DEPLOYMENT_ID) + .pathParam("resourceId", EXAMPLE_DEPLOYMENT_RESOURCE_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .get(SINGLE_RESOURCE_DATA_URL); + } + + @Test + public void testCreateCompleteDeployment() throws Exception { + + resourceNames.addAll( Arrays.asList("data", "more-data") ); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .multiPart("enable-duplicate-filtering", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + verifyCreatedDeployment(mockDeployment, response); + + verify(mockDeploymentBuilder).name(MockProvider.EXAMPLE_DEPLOYMENT_ID); + verify(mockDeploymentBuilder).enableDuplicateFiltering(false); + + } + + @Test + public void testCreateCompleteBpmnDeployment() throws Exception { + // given + DeploymentWithDefinitions mockDeployment = MockProvider.createMockDeploymentWithDefinitions(); + when(mockDeployment.getDeployedDecisionDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedCaseDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedDecisionRequirementsDefinitions()).thenReturn(null); + when(mockDeploymentBuilder.deployWithResult()).thenReturn(mockDeployment); + + // when + resourceNames.addAll(Arrays.asList("data", "more-data")); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .multiPart("enable-duplicate-filtering", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + // then + verifyCreatedBpmnDeployment(mockDeployment, response); + + verify(mockDeploymentBuilder).name(MockProvider.EXAMPLE_DEPLOYMENT_ID); + verify(mockDeploymentBuilder).enableDuplicateFiltering(false); + + } + + @Test + public void testCreateCompleteCmmnDeployment() throws Exception { + // given + DeploymentWithDefinitions mockDeployment = MockProvider.createMockDeploymentWithDefinitions(); + when(mockDeployment.getDeployedDecisionDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedProcessDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedDecisionRequirementsDefinitions()).thenReturn(null); + when(mockDeploymentBuilder.deployWithResult()).thenReturn(mockDeployment); + + // when + resourceNames.addAll(Arrays.asList("data", "more-data")); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .multiPart("enable-duplicate-filtering", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + // then + verifyCreatedCmmnDeployment(mockDeployment, response); + + verify(mockDeploymentBuilder).name(MockProvider.EXAMPLE_DEPLOYMENT_ID); + verify(mockDeploymentBuilder).enableDuplicateFiltering(false); + + } + + @Test + public void testCreateCompleteDmnDeployment() throws Exception { + // given + DeploymentWithDefinitions mockDeployment = MockProvider.createMockDeploymentWithDefinitions(); + when(mockDeployment.getDeployedCaseDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedProcessDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedDecisionRequirementsDefinitions()).thenReturn(null); + when(mockDeploymentBuilder.deployWithResult()).thenReturn(mockDeployment); + + // when + resourceNames.addAll(Arrays.asList("data", "more-data")); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .multiPart("enable-duplicate-filtering", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + // then + verifyCreatedDmnDeployment(mockDeployment, response); + + verify(mockDeploymentBuilder).name(MockProvider.EXAMPLE_DEPLOYMENT_ID); + verify(mockDeploymentBuilder).enableDuplicateFiltering(false); + + } + + @Test + public void testCreateCompleteDrdDeployment() throws Exception { + // given + DeploymentWithDefinitions mockDeployment = MockProvider.createMockDeploymentWithDefinitions(); + when(mockDeployment.getDeployedCaseDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedProcessDefinitions()).thenReturn(null); + when(mockDeploymentBuilder.deployWithResult()).thenReturn(mockDeployment); + + // when + resourceNames.addAll(Arrays.asList("data", "more-data")); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .multiPart("enable-duplicate-filtering", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + // then + verifyCreatedDrdDeployment(mockDeployment, response); + + verify(mockDeploymentBuilder).name(MockProvider.EXAMPLE_DEPLOYMENT_ID); + verify(mockDeploymentBuilder).enableDuplicateFiltering(false); + + } + + @Test + public void testCreateDeploymentWithNonExecutableProcess() throws Exception { + + // given + DeploymentWithDefinitions mockDeployment = MockProvider.createMockDeploymentWithDefinitions(); + when(mockDeployment.getDeployedDecisionDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedCaseDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedProcessDefinitions()).thenReturn(null); + when(mockDeployment.getDeployedDecisionRequirementsDefinitions()).thenReturn(null); + when(mockDeploymentBuilder.deployWithResult()).thenReturn(mockDeployment); + + // when + resourceNames.addAll(Arrays.asList("data", "more-data")); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnDataNonExecutableProcess()) + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .multiPart("enable-duplicate-filtering", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + // then + verifyCreatedEmptyDeployment(mockDeployment, response); + + verify(mockDeploymentBuilder).name(MockProvider.EXAMPLE_DEPLOYMENT_ID); + verify(mockDeploymentBuilder).enableDuplicateFiltering(false); + + } + + @Test + public void testCreateCompleteDeploymentDeployChangedOnly() throws Exception { + + resourceNames.addAll( Arrays.asList("data", "more-data") ); + + given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("deploy-changed-only", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).enableDuplicateFiltering(true); + + } + + @Test + public void testCreateCompleteDeploymentConflictingDuplicateSetting() throws Exception { + + resourceNames.addAll( Arrays.asList("data", "more-data") ); + + // deploy-changed-only should override enable-duplicate-filtering + given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("enable-duplicate-filtering", "false") + .multiPart("deploy-changed-only", "true") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).enableDuplicateFiltering(true); + + } + + @Test + public void testCreateDeploymentWithDeploymentSource() throws Exception { + + resourceNames.addAll( Arrays.asList("data", "more-data") ); + + // deploy-changed-only should override enable-duplicate-filtering + given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("enable-duplicate-filtering", "false") + .multiPart("deployment-source", "my-deployment-source") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).source("my-deployment-source"); + + } + + @Test + public void testCreateDeploymentWithActivationTime() throws Exception { + + resourceNames.addAll( Arrays.asList("data", "more-data") ); + + given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("deployment-activation-time", "2030-11-11T11:11:11Z") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).activateProcessDefinitionsOn(DateTimeUtil.parseDate("2030-11-11T11:11:11Z")); + + } + + @Test + public void testCreateDeploymentWithTenantId() throws Exception { + + resourceNames.addAll( Arrays.asList("data", "more-data") ); + + given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("tenant-id", EXAMPLE_TENANT_ID) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).tenantId(EXAMPLE_TENANT_ID); + } + + @Test + public void testCreateDeploymentOnlyWithBytes() throws Exception { + + resourceNames.addAll(Arrays.asList("data", "more-data")); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + verifyCreatedDeployment(mockDeployment, response); + + } + + @Test + public void testCreateDeploymentWithoutBytes() throws Exception { + + given() + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + } + + @Test + public void testCreateDeploymentWithNonExistentPart() throws Exception { + + given() + .multiPart("non-existent-body-part", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(CREATE_DEPLOYMENT_URL); + + } + + @Test + public void testCreateDeploymentThrowsAuthorizationException() { + String message = "expected exception"; + when(mockDeploymentBuilder.deployWithResult()).thenThrow(new AuthorizationException(message)); + + resourceNames.addAll( Arrays.asList("data", "more-data") ); + + given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .multiPart("more-data", "unspecified", createMockDeploymentResourceBpmnData()) + .multiPart("deployment-name", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .multiPart("enable-duplicate-filtering", "true") + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .post(CREATE_DEPLOYMENT_URL); + } + + + @Test + @SuppressWarnings("unchecked") + public void testCreateDeploymentThrowsParseException() { + resourceNames.addAll( Arrays.asList("data", "more-data") ); + String message = "expected exception"; + List mockErrors = mockProblems(EXAMPLE_PROBLEM_COLUMN, EXAMPLE_PROBLEM_LINE, message, EXAMPLE_PROBLEM_ELEMENT_ID); + List mockWarnings = mockProblems(EXAMPLE_PROBLEM_COLUMN_2, EXAMPLE_PROBLEM_LINE_2, EXAMPLE_EXCEPTION_MESSAGE, EXAMPLE_PROBLEM_ELEMENT_ID_2); + ParseException mockParseException = createMockParseException(mockErrors, mockWarnings, message); + when(mockDeploymentBuilder.deployWithResult()).thenThrow(mockParseException); + + Response response = given() + .multiPart("data", "unspecified", createMockDeploymentResourceByteData()) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(ParseException.class.getSimpleName())) + .body("message", is(message)) + .when() + .post(CREATE_DEPLOYMENT_URL); + + String content = response.asString(); + + Map details = from(content).getMap("details"); + HashMap>> problems = (HashMap>>) details.get("abc"); + + List> errors = problems.get("errors"); + HashMap error = errors.get(0); + assertEquals(EXAMPLE_PROBLEM_COLUMN, error.get("column")); + assertEquals(EXAMPLE_PROBLEM_LINE, error.get("line")); + assertEquals(message, error.get("message")); + assertEquals(EXAMPLE_PROBLEM_ELEMENT_ID, error.get("mainElementId")); + assertEquals(EXAMPLE_ELEMENT_IDS, error.get("еlementIds")); + + List> warnings = problems.get("warnings"); + HashMap warning = warnings.get(0); + assertEquals(EXAMPLE_PROBLEM_COLUMN_2, warning.get("column")); + assertEquals(EXAMPLE_PROBLEM_LINE_2, warning.get("line")); + assertEquals(EXAMPLE_EXCEPTION_MESSAGE, warning.get("message")); + assertEquals(EXAMPLE_PROBLEM_ELEMENT_ID_2, warning.get("mainElementId")); + assertEquals(EXAMPLE_ELEMENT_IDS, warning.get("еlementIds")); + } + + @Test + public void testDeleteDeployment() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentCascade() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("cascade", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, true, false, false); + } + + @Test + public void testDeleteDeploymentCascadeNonsense() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("cascade", "bla") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentCascadeFalse() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("cascade", false) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListeners() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("skipCustomListeners", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, false, true, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListenersNonsense() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("skipCustomListeners", "bla") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListenersFalse() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("skipCustomListeners", false) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListenersAndCascade() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("cascade", true) + .queryParam("skipCustomListeners", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, true, true, false); + } + + @Test + public void testDeleteDeploymentSkipIoMappings() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("cascade", true) + .queryParam("skipIoMappings", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, true, false, true); + } + + @Test + public void testDeleteDeploymentSkipIoMappingsFalse() { + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .queryParam("cascade", true) + .queryParam("skipIoMappings", false) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DEPLOYMENT_URL); + + verify(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, true, false, false); + } + + @Test + public void testDeleteNonExistingDeployment() { + + when(mockDeploymentQuery.deploymentId(NON_EXISTING_DEPLOYMENT_ID)).thenReturn(mockDeploymentQuery); + when(mockDeploymentQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", NON_EXISTING_DEPLOYMENT_ID) + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deployment with id '" + NON_EXISTING_DEPLOYMENT_ID + "' do not exist")) + .when() + .delete(DEPLOYMENT_URL); + } + + @Test + public void testDeleteDeploymentThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(mockRepositoryService).deleteDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID, false, false, false); + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .delete(DEPLOYMENT_URL); + } + + @Test + public void testRedeployDeployment() { + Map json = new HashMap<>(); + + List resourceIds = new ArrayList<>(); + resourceIds.add("first-resource-id"); + resourceIds.add("second-resource-id"); + json.put("resourceIds", resourceIds); + + List resourceNames = new ArrayList<>(); + resourceNames.add("first-resource-name"); + resourceNames.add("second-resource-name"); + json.put("resourceNames", resourceNames); + + json.put("source", MockProvider.EXAMPLE_DEPLOYMENT_SOURCE); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder, never()).addDeploymentResources(anyString()); + verify(mockDeploymentBuilder).nameFromDeployment(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceById(anyString(), anyString()); + verify(mockDeploymentBuilder).addDeploymentResourcesById(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), eq(resourceIds)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceByName(anyString(), anyString()); + verify(mockDeploymentBuilder).addDeploymentResourcesByName(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), eq(resourceNames)); + verify(mockDeploymentBuilder).source(MockProvider.EXAMPLE_DEPLOYMENT_SOURCE); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployDeploymentWithoutRequestBody() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).addDeploymentResources(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder).nameFromDeployment(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceById(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesById(anyString(), anyList()); + verify(mockDeploymentBuilder, never()).addDeploymentResourceByName(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesByName(anyString(), anyList()); + verify(mockDeploymentBuilder, never()).source(anyString()); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployDeploymentEmptyRequestBody() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body("{}") + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).addDeploymentResources(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder).nameFromDeployment(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceById(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesById(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), anyList()); + verify(mockDeploymentBuilder, never()).addDeploymentResourceByName(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesByName(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), anyList()); + verify(mockDeploymentBuilder).source(null); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployDeploymentResourceIds() { + Map json = new HashMap<>(); + + List resourceIds = new ArrayList<>(); + resourceIds.add("first-resource-id"); + resourceIds.add("second-resource-id"); + json.put("resourceIds", resourceIds); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder, never()).addDeploymentResources(anyString()); + verify(mockDeploymentBuilder).nameFromDeployment(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceById(anyString(), anyString()); + verify(mockDeploymentBuilder).addDeploymentResourcesById(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), eq(resourceIds)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceByName(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesByName(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), anyList()); + verify(mockDeploymentBuilder).source(null); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployDeploymentResourceNames() { + Map json = new HashMap<>(); + + List resourceNames = new ArrayList<>(); + resourceNames.add("first-resource-name"); + resourceNames.add("second-resource-name"); + json.put("resourceNames", resourceNames); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder, never()).addDeploymentResources(anyString()); + verify(mockDeploymentBuilder).nameFromDeployment(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceById(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesById(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), anyList()); + verify(mockDeploymentBuilder, never()).addDeploymentResourceByName(anyString(), anyString()); + verify(mockDeploymentBuilder).addDeploymentResourcesByName(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID), eq(resourceNames)); + verify(mockDeploymentBuilder).source(null); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployDeploymentSource() { + Map json = new HashMap<>(); + json.put("source", MockProvider.EXAMPLE_DEPLOYMENT_SOURCE); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).addDeploymentResources(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder).nameFromDeployment(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder, never()).addDeploymentResourceById(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesById(anyString(), anyList()); + verify(mockDeploymentBuilder, never()).addDeploymentResourceByName(anyString(), anyString()); + verify(mockDeploymentBuilder, never()).addDeploymentResourcesByName(anyString(), anyList()); + verify(mockDeploymentBuilder).source(eq(MockProvider.EXAMPLE_DEPLOYMENT_SOURCE)); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployDeploymentWithoutTenantId() { + when(mockDeployment.getTenantId()).thenReturn(null); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).addDeploymentResources(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder, never()).tenantId(any(String.class)); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployDeploymentWithTenantId() { + when(mockDeployment.getTenantId()).thenReturn(MockProvider.EXAMPLE_TENANT_ID); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + + verify(mockDeploymentBuilder).addDeploymentResources(eq(MockProvider.EXAMPLE_DEPLOYMENT_ID)); + verify(mockDeploymentBuilder).tenantId(eq(MockProvider.EXAMPLE_TENANT_ID)); + verify(mockDeploymentBuilder).deployWithResult(); + + verifyDeployment(mockDeployment, response); + } + + @Test + public void testRedeployThrowsNotFoundException() { + String message = "deployment not found"; + doThrow(new NotFoundException(message)).when(mockDeploymentBuilder).deployWithResult(); + + String expected = "Cannot redeploy deployment '" + MockProvider.EXAMPLE_DEPLOYMENT_ID + "': " + message; + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(expected)) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + } + + @Test + public void testRedeployThrowsNotValidException() { + String message = "not valid"; + doThrow(new NotValidException(message)).when(mockDeploymentBuilder).deployWithResult(); + + String expected = "Cannot redeploy deployment '" + MockProvider.EXAMPLE_DEPLOYMENT_ID + "': " + message; + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(expected)) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + } + + @Test + public void testRedeployThrowsProcessEngineException() { + String message = "something went wrong"; + doThrow(new ProcessEngineException(message)).when(mockDeploymentBuilder).deployWithResult(); + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(message)) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + } + + @Test + public void testRedeployThrowsAuthorizationException() { + String message = "missing authorization"; + doThrow(new AuthorizationException(message)).when(mockDeploymentBuilder).deployWithResult(); + + given() + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .post(REDEPLOY_DEPLOYMENT_URL); + } + + private void verifyDeployment(Deployment mockDeployment, Response response) { + String content = response.asString(); + verifyDeploymentValues(mockDeployment, content); + } + + private void verifyCreatedDeployment(Deployment mockDeployment, Response response) { + String content = response.asString(); + verifyDeploymentWithDefinitionsValues(mockDeployment, content); + verifyDeploymentLink(mockDeployment, content); + } + + private void verifyCreatedBpmnDeployment(Deployment mockDeployment, Response response) { + String content = response.asString(); + verifyBpmnDeploymentValues(mockDeployment, content); + verifyDeploymentLink(mockDeployment, content); + } + + private void verifyCreatedCmmnDeployment(Deployment mockDeployment, Response response) { + String content = response.asString(); + verifyCmmnDeploymentValues(mockDeployment, content); + verifyDeploymentLink(mockDeployment, content); + } + + private void verifyCreatedDmnDeployment(Deployment mockDeployment, Response response) { + String content = response.asString(); + verifyDmnDeploymentValues(mockDeployment, content); + verifyDeploymentLink(mockDeployment, content); + } + + private void verifyCreatedDrdDeployment(Deployment mockDeployment, Response response) { + String content = response.asString(); + verifyDrdDeploymentValues(mockDeployment, content); + verifyDeploymentLink(mockDeployment, content); + } + + private void verifyCreatedEmptyDeployment(Deployment mockDeployment, Response response) { + String content = response.asString(); + verifyDeploymentValuesEmptyDefinitions(mockDeployment, content); + verifyDeploymentLink(mockDeployment, content); + } + + private void verifyDeploymentValues(Deployment mockDeployment, String responseContent) { + JsonPath path = from(responseContent); + verifyStandardDeploymentValues(mockDeployment, path); + } + + private void verifyDeploymentWithDefinitionsValues(Deployment mockDeployment, String responseContent) { + JsonPath path = from(responseContent); + verifyStandardDeploymentValues(mockDeployment, path); + + Map> deployedProcessDefinitions = path.getMap(PROPERTY_DEPLOYED_PROCESS_DEFINITIONS); + Map> deployedCaseDefinitions = path.getMap(PROPERTY_DEPLOYED_CASE_DEFINITIONS); + Map> deployedDecisionDefinitions = path.getMap(PROPERTY_DEPLOYED_DECISION_DEFINITIONS); + Map> deployedDecisionRequirementsDefinitions = path.getMap(PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS); + + assertEquals(1, deployedProcessDefinitions.size()); + assertNotNull(deployedProcessDefinitions.get(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + assertEquals(1, deployedCaseDefinitions.size()); + assertNotNull(deployedCaseDefinitions.get(EXAMPLE_CASE_DEFINITION_ID)); + assertEquals(1, deployedDecisionDefinitions.size()); + assertNotNull(deployedDecisionDefinitions.get(EXAMPLE_DECISION_DEFINITION_ID)); + assertEquals(1, deployedDecisionRequirementsDefinitions.size()); + assertNotNull(deployedDecisionRequirementsDefinitions.get(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)); + } + + private void verifyBpmnDeploymentValues(Deployment mockDeployment, String responseContent) { + JsonPath path = from(responseContent); + verifyStandardDeploymentValues(mockDeployment, path); + + Map> deployedProcessDefinitionDtos = path.getMap(PROPERTY_DEPLOYED_PROCESS_DEFINITIONS); + + assertEquals(1, deployedProcessDefinitionDtos.size()); + HashMap processDefinitionDto = deployedProcessDefinitionDtos.get(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertNotNull(processDefinitionDto); + verifyBpmnDeployment(processDefinitionDto); + + assertNull(path.get(PROPERTY_DEPLOYED_CASE_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_DECISION_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS)); + } + + private void verifyCmmnDeploymentValues(Deployment mockDeployment, String responseContent) { + JsonPath path = from(responseContent); + verifyStandardDeploymentValues(mockDeployment, path); + + Map> deployedCaseDefinitions = path.getMap(PROPERTY_DEPLOYED_CASE_DEFINITIONS); + + assertEquals(1, deployedCaseDefinitions.size()); + HashMap caseDefinitionDto = deployedCaseDefinitions.get(EXAMPLE_CASE_DEFINITION_ID); + assertNotNull(caseDefinitionDto); + verifyCmnDeployment(caseDefinitionDto); + + assertNull(path.get(PROPERTY_DEPLOYED_PROCESS_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_DECISION_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS)); + } + + private void verifyDmnDeploymentValues(Deployment mockDeployment, String responseContent) { + JsonPath path = from(responseContent); + verifyStandardDeploymentValues(mockDeployment, path); + + Map> deployedDecisionDefinitions = path.getMap(PROPERTY_DEPLOYED_DECISION_DEFINITIONS); + + assertEquals(1, deployedDecisionDefinitions.size()); + HashMap decisionDefinitionDto = deployedDecisionDefinitions.get(EXAMPLE_DECISION_DEFINITION_ID); + assertNotNull(decisionDefinitionDto); + verifyDmnDeployment(decisionDefinitionDto); + + assertNull(path.get(PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_PROCESS_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_CASE_DEFINITIONS)); + } + + private void verifyDrdDeploymentValues(Deployment mockDeployment, String responseContent) { + JsonPath path = from(responseContent); + verifyStandardDeploymentValues(mockDeployment, path); + + Map> deployedDecisionDefinitions = + path.getMap(PROPERTY_DEPLOYED_DECISION_DEFINITIONS); + Map> deployedDecisionRequirementsDefinitions = + path.getMap(PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS); + + assertEquals(1, deployedDecisionDefinitions.size()); + HashMap decisionDefinitionDto = deployedDecisionDefinitions.get(EXAMPLE_DECISION_DEFINITION_ID); + assertNotNull(decisionDefinitionDto); + verifyDmnDeployment(decisionDefinitionDto); + + assertEquals(1, deployedDecisionRequirementsDefinitions.size()); + HashMap decisionRequirementsDefinitionDto = deployedDecisionRequirementsDefinitions.get(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + assertNotNull(decisionRequirementsDefinitionDto); + verifyDrdDeployment(decisionRequirementsDefinitionDto); + + assertNull(path.get(PROPERTY_DEPLOYED_PROCESS_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_CASE_DEFINITIONS)); + } + + private void verifyBpmnDeployment(HashMap dto) { + assertEquals(dto.get("id"), MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertEquals(dto.get("category"), EXAMPLE_PROCESS_DEFINITION_CATEGORY); + assertEquals(dto.get("name"), EXAMPLE_PROCESS_DEFINITION_NAME); + assertEquals(dto.get("key"), EXAMPLE_PROCESS_DEFINITION_KEY); + assertEquals(dto.get("description"), EXAMPLE_PROCESS_DEFINITION_DESCRIPTION); + assertEquals(dto.get("version"), EXAMPLE_PROCESS_DEFINITION_VERSION); + assertEquals(dto.get("resource"), EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME); + assertEquals(dto.get("deploymentId"), EXAMPLE_DEPLOYMENT_ID); + assertEquals(dto.get("diagram"), EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME); + assertEquals(dto.get("suspended"), EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED); + } + private void verifyCmnDeployment(HashMap dto) { + assertEquals(dto.get("id"), EXAMPLE_CASE_DEFINITION_ID); + assertEquals(dto.get("category"), EXAMPLE_CASE_DEFINITION_CATEGORY); + assertEquals(dto.get("name"), EXAMPLE_CASE_DEFINITION_NAME); + assertEquals(dto.get("key"), EXAMPLE_CASE_DEFINITION_KEY); + assertEquals(dto.get("version"), EXAMPLE_CASE_DEFINITION_VERSION); + assertEquals(dto.get("resource"), EXAMPLE_CASE_DEFINITION_RESOURCE_NAME); + assertEquals(dto.get("deploymentId"), EXAMPLE_DEPLOYMENT_ID); + } + + private void verifyDmnDeployment(HashMap dto) { + assertEquals(dto.get("id"), EXAMPLE_DECISION_DEFINITION_ID); + assertEquals(dto.get("category"), EXAMPLE_DECISION_DEFINITION_CATEGORY); + assertEquals(dto.get("name"), EXAMPLE_DECISION_DEFINITION_NAME); + assertEquals(dto.get("key"), EXAMPLE_DECISION_DEFINITION_KEY); + assertEquals(dto.get("version"), EXAMPLE_DECISION_DEFINITION_VERSION); + assertEquals(dto.get("resource"), EXAMPLE_DECISION_DEFINITION_RESOURCE_NAME); + assertEquals(dto.get("deploymentId"), EXAMPLE_DEPLOYMENT_ID); + assertEquals(dto.get("decisionRequirementsDefinitionId"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + assertEquals(dto.get("decisionRequirementsDefinitionKey"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + } + + private void verifyDrdDeployment(HashMap dto) { + assertEquals(dto.get("id"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + assertEquals(dto.get("category"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY); + assertEquals(dto.get("name"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME); + assertEquals(dto.get("key"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + assertEquals(dto.get("version"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION); + assertEquals(dto.get("resource"), EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME); + assertEquals(dto.get("deploymentId"), EXAMPLE_DEPLOYMENT_ID); + } + + private void verifyDeploymentValuesEmptyDefinitions(Deployment mockDeployment, String responseContent) { + JsonPath path = from(responseContent); + verifyStandardDeploymentValues(mockDeployment, path); + + assertNull(path.get(PROPERTY_DEPLOYED_PROCESS_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_CASE_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_DECISION_DEFINITIONS)); + assertNull(path.get(PROPERTY_DEPLOYED_DECISION_REQUIREMENTS_DEFINITIONS)); + } + + private void verifyStandardDeploymentValues(Deployment mockDeployment, JsonPath path) { + String returnedId = path.get("id"); + String returnedName = path.get("name"); + Date returnedDeploymentTime = DateTimeUtil.parseDate(path.get("deploymentTime")); + + assertEquals(mockDeployment.getId(), returnedId); + assertEquals(mockDeployment.getName(), returnedName); + assertEquals(mockDeployment.getDeploymentTime(), returnedDeploymentTime); + } + + private void verifyDeploymentLink(Deployment mockDeployment, String responseContent) { + List> returnedLinks = from(responseContent).getList("links"); + assertEquals(1, returnedLinks.size()); + + Map returnedLink = returnedLinks.get(0); + assertEquals(HttpMethod.GET, returnedLink.get("method")); + assertTrue(returnedLink.get("href").endsWith(RESOURCE_URL + "/" + mockDeployment.getId())); + assertEquals("self", returnedLink.get("rel")); + } + + private void verifyDeploymentResource(Resource mockDeploymentResource, Response response) { + String content = response.asString(); + + JsonPath path = from(content); + String returnedId = path.get("id"); + String returnedName = path.get("name"); + String returnedDeploymentId = path.get("deploymentId"); + + assertEquals(mockDeploymentResource.getId(), returnedId); + assertEquals(mockDeploymentResource.getName(), returnedName); + assertEquals(mockDeploymentResource.getDeploymentId(), returnedDeploymentId); + } + + @SuppressWarnings("unchecked") + private void verifyDeploymentResources(List mockDeploymentResources, Response response) { + List list = response.as(List.class); + assertEquals(1, list.size()); + + LinkedHashMap resourceHashMap = (LinkedHashMap) list.get(0); + + String returnedId = resourceHashMap.get("id"); + String returnedName = resourceHashMap.get("name"); + String returnedDeploymentId = resourceHashMap.get("deploymentId"); + + Resource mockDeploymentResource = mockDeploymentResources.get(0); + + assertEquals(mockDeploymentResource.getId(), returnedId); + assertEquals(mockDeploymentResource.getName(), returnedName); + assertEquals(mockDeploymentResource.getDeploymentId(), returnedDeploymentId); + } + + private List mockProblems(int column, int line, String message, String elementId) { + Problem mockProblem = mock(Problem.class); + when(mockProblem.getColumn()).thenReturn(column); + when(mockProblem.getLine()).thenReturn(line); + when(mockProblem.getMessage()).thenReturn(message); + when(mockProblem.getMainElementId()).thenReturn(elementId); + when(mockProblem.getElementIds()).thenReturn(EXAMPLE_ELEMENT_IDS); + List mockProblems = new ArrayList<>(); + mockProblems.add(mockProblem); + return mockProblems; + } + + private ParseException createMockParseException(List mockErrors, + List mockWarnings, String message) { + ParseException mockParseException = mock(ParseException.class); + when(mockParseException.getMessage()).thenReturn(message); + + ResourceReportImpl report = mock(ResourceReportImpl.class); + when(report.getResourceName()).thenReturn(EXAMPLE_RESOURCE_NAME); + when(report.getErrors()).thenReturn(mockErrors); + when(report.getWarnings()).thenReturn(mockWarnings); + + List reports = new ArrayList<>(); + reports.add(report); + + when(mockParseException.getResorceReports()).thenReturn(reports); + return mockParseException; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DeploymentRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DeploymentRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..77d33a42aef651145f1f31c389d2d9019b1b2bc8 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/DeploymentRestServiceQueryTest.java @@ -0,0 +1,412 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.repository.DeploymentQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class DeploymentRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String DEPLOYMENT_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/deployment"; + protected static final String DEPLOYMENT_COUNT_QUERY_URL = DEPLOYMENT_QUERY_URL + "/count"; + private DeploymentQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockDeploymentQuery(MockProvider.createMockDeployments()); + } + + private DeploymentQuery setUpMockDeploymentQuery(List mockedDeployments) { + DeploymentQuery sampleDeploymentQuery = mock(DeploymentQuery.class); + when(sampleDeploymentQuery.list()).thenReturn(mockedDeployments); + when(sampleDeploymentQuery.count()).thenReturn((long) mockedDeployments.size()); + when(processEngine.getRepositoryService().createDeploymentQuery()).thenReturn(sampleDeploymentQuery); + return sampleDeploymentQuery; + } + + @Test + public void testEmptyQuery() { + given() + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifyFailingSorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST, + InvalidRequestException.class.getSimpleName(), "Cannot set query parameter 'sortBy' to value 'anInvalidSortByOption'"); + executeAndVerifyFailingSorting("name", "anInvalidSortOrderOption", Status.BAD_REQUEST, + InvalidRequestException.class.getSimpleName(), "Cannot set query parameter 'sortOrder' to value 'anInvalidSortOrderOption'"); + } + + protected void executeAndVerifySuccessfulSorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(DEPLOYMENT_QUERY_URL); + } + + protected void executeAndVerifyFailingSorting(String sortBy, String sortOrder, Status expectedStatus, String expectedErrorType, String expectedErrorMessage) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(expectedErrorType)) + .body("message", equalTo(expectedErrorMessage)) + .when().get(DEPLOYMENT_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "name") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(DEPLOYMENT_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(DEPLOYMENT_QUERY_URL); + } + + @Test + public void testDeploymentRetrieval() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + + String queryKey = "Name"; + Response response = given().queryParam("nameLike", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_QUERY_URL); + + // assert query invocation + inOrder.verify(mockedQuery).deploymentNameLike(queryKey); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List deployments = from(content).getList(""); + Assert.assertEquals("There should be one deployment returned.", 1, deployments.size()); + Assert.assertNotNull("There should be one deployment returned", deployments.get(0)); + + String returnedId = from(content).getString("[0].id"); + String returnedName = from(content).getString("[0].name"); + String returnedSource = from(content).getString("[0].source"); + String returnedDeploymentTime = from(content).getString("[0].deploymentTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_NAME, returnedName); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_SOURCE, returnedSource); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_TIME, returnedDeploymentTime); + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testAdditionalParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given().queryParams(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_QUERY_URL); + + // assert query invocation + verify(mockedQuery).deploymentName(queryParameters.get("name")); + verify(mockedQuery).deploymentNameLike(queryParameters.get("nameLike")); + verify(mockedQuery).deploymentId(queryParameters.get("id")); + verify(mockedQuery).deploymentSource(queryParameters.get("source")); + verify(mockedQuery).list(); + } + + @Test + public void testWithoutSourceParameter() { + + given() + .queryParam("withoutSource", true) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DEPLOYMENT_QUERY_URL); + + // assert query invocation + verify(mockedQuery).deploymentSource(null); + verify(mockedQuery).list(); + } + + @Test + public void testSourceAndWithoutSource() { + given() + .queryParam("withoutSource", true) + .queryParam("source", "source") + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("The query parameters \"withoutSource\" and \"source\" cannot be used in combination.")) + .when() + .get(DEPLOYMENT_QUERY_URL); + } + + @Test + public void testDeploymentBefore() { + given() + .queryParam("before", MockProvider.EXAMPLE_DEPLOYMENT_TIME_BEFORE) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).deploymentBefore(any(Date.class)); + verify(mockedQuery).list(); + } + + @Test + public void testDeploymentAfter() { + given() + .queryParam("after", MockProvider.EXAMPLE_DEPLOYMENT_TIME_AFTER) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).deploymentAfter(any(Date.class)); + verify(mockedQuery).list(); + } + + @Test + public void testDeploymentTenantIdList() { + List deployments = Arrays.asList( + MockProvider.createMockDeployment(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockDeployment(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + mockedQuery = setUpMockDeploymentQuery(deployments); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testDeploymentWithoutTenantId() { + Deployment mockDeployment = MockProvider.createMockDeployment(null); + mockedQuery = setUpMockDeploymentQuery(Collections.singletonList(mockDeployment)); + + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testDeploymentTenantIdIncludeDefinitionsWithoutTenantid() { + List mockDeployments = Arrays.asList( + MockProvider.createMockDeployment(null), + MockProvider.createMockDeployment(MockProvider.EXAMPLE_TENANT_ID)); + mockedQuery = setUpMockDeploymentQuery(mockDeployments); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("includeDeploymentsWithoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockedQuery).includeDeploymentsWithoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("id", "depId"); + parameters.put("name", "name"); + parameters.put("nameLike", "nameLike"); + parameters.put("source", "source"); + + return parameters; + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("id", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("id", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("deploymentTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("deploymentTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("name", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("name", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given().queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given().queryParam("firstResult", firstResult) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(DEPLOYMENT_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/EventSubscriptionRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/EventSubscriptionRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..91761f399e727a0d39bef31072a632b824b86242 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/EventSubscriptionRestServiceQueryTest.java @@ -0,0 +1,331 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.EventSubscription; +import org.camunda.bpm.engine.runtime.EventSubscriptionQuery; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.response.Response; + +public class EventSubscriptionRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String EVENT_SUBSCRIPTION_URL = TEST_RESOURCE_ROOT_PATH + "/event-subscription"; + protected static final String EVENT_SUBSCRIPTION_COUNT_QUERY_URL = EVENT_SUBSCRIPTION_URL + "/count"; + + private EventSubscriptionQuery mockedEventSubscriptionQuery; + + @Before + public void setUpRuntimeData() { + mockedEventSubscriptionQuery = setUpMockEventSubscriptionQuery(createMockEventSubscriptionList()); + } + + private EventSubscriptionQuery setUpMockEventSubscriptionQuery(List mockedInstances) { + EventSubscriptionQuery sampleEventSubscriptionsQuery = mock(EventSubscriptionQuery.class); + when(sampleEventSubscriptionsQuery.list()).thenReturn(mockedInstances); + when(sampleEventSubscriptionsQuery.count()).thenReturn((long) mockedInstances.size()); + when(processEngine.getRuntimeService().createEventSubscriptionQuery()).thenReturn(sampleEventSubscriptionsQuery); + return sampleEventSubscriptionsQuery; + } + + private List createMockEventSubscriptionList() { + List mocks = new ArrayList(); + + mocks.add(MockProvider.createMockEventSubscription()); + return mocks; + } + + @Test + public void testEmptyQuery() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + } + + @Test + public void testEventSubscriptionRetrieval() { + Response response = + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedEventSubscriptionQuery); + inOrder.verify(mockedEventSubscriptionQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one event subscription returned.", 1, instances.size()); + Assert.assertNotNull("There should be one event subscription returned", instances.get(0)); + + String returnedEventSubscriptionId = from(content).getString("[0].id"); + String returnedEventType = from(content).getString("[0].eventType"); + String returnedEventName = from(content).getString("[0].eventName"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedCreatedDate = from(content).getString("[0].createdDate"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_ID, returnedEventSubscriptionId); + Assert.assertEquals(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_TYPE, returnedEventType); + Assert.assertEquals(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_NAME, returnedEventName); + Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_ID, returnedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_CREATION_DATE, returnedCreatedDate); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "created") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + verify(mockedEventSubscriptionQuery).list(); + verifyNoMoreInteractions(mockedEventSubscriptionQuery); + } + + @Test + public void testQueryParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given() + .queryParams(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + verify(mockedEventSubscriptionQuery).eventSubscriptionId(queryParameters.get("eventSubscriptionId")); + verify(mockedEventSubscriptionQuery).eventType(queryParameters.get("eventType")); + verify(mockedEventSubscriptionQuery).eventName(queryParameters.get("eventName")); + verify(mockedEventSubscriptionQuery).executionId(queryParameters.get("executionId")); + verify(mockedEventSubscriptionQuery).processInstanceId(queryParameters.get("processInstanceId")); + verify(mockedEventSubscriptionQuery).activityId(queryParameters.get("activityId")); + verify(mockedEventSubscriptionQuery).list(); + } + + @Test + public void testTenantIdListParameter() { + mockedEventSubscriptionQuery = setUpMockEventSubscriptionQuery(createMockEventSubscriptionTwoTenants()); + + Response response = + given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + verify(mockedEventSubscriptionQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedEventSubscriptionQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertThat(instances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + + @Test + public void testWithoutTenantIdParameter() { + mockedEventSubscriptionQuery = setUpMockEventSubscriptionQuery(Arrays.asList(MockProvider.createMockEventSubscription(null))); + + Response response = + given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + verify(mockedEventSubscriptionQuery).withoutTenantId(); + verify(mockedEventSubscriptionQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedEventSubscriptionQuery); + executeAndVerifySorting("created", "asc", Status.OK); + inOrder.verify(mockedEventSubscriptionQuery).orderByCreated(); + inOrder.verify(mockedEventSubscriptionQuery).asc(); + + inOrder = Mockito.inOrder(mockedEventSubscriptionQuery); + executeAndVerifySorting("created", "desc", Status.OK); + inOrder.verify(mockedEventSubscriptionQuery).orderByCreated(); + inOrder.verify(mockedEventSubscriptionQuery).desc(); + + inOrder = Mockito.inOrder(mockedEventSubscriptionQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedEventSubscriptionQuery).orderByTenantId(); + inOrder.verify(mockedEventSubscriptionQuery).asc(); + + inOrder = Mockito.inOrder(mockedEventSubscriptionQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedEventSubscriptionQuery).orderByTenantId(); + inOrder.verify(mockedEventSubscriptionQuery).desc(); + + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = 0; + int maxResults = 10; + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + verify(mockedEventSubscriptionQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given() + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + verify(mockedEventSubscriptionQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as + * default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + + verify(mockedEventSubscriptionQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()).body("count", equalTo(1)) + .when().get(EVENT_SUBSCRIPTION_COUNT_QUERY_URL); + + verify(mockedEventSubscriptionQuery).count(); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when().get(EVENT_SUBSCRIPTION_URL); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("eventSubscriptionId", "anEventSubscriptionId"); + parameters.put("eventType", "aEventType"); + parameters.put("eventName", "aEventName"); + parameters.put("executionId", "aExecutionId"); + parameters.put("processInstanceId", "aProcessInstanceId"); + parameters.put("activityId", "aActivityId"); + + return parameters; + } + + private List createMockEventSubscriptionTwoTenants() { + return Arrays.asList( + MockProvider.createMockEventSubscription(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockEventSubscription(MockProvider.ANOTHER_EXAMPLE_TENANT_ID) + ); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExceptionHandlerTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExceptionHandlerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c43ed3d069c6b25a25c8e4b68d09ade140c7cc51 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExceptionHandlerTest.java @@ -0,0 +1,134 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.nullValue; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; + +public class ExceptionHandlerTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + private static final String EXCEPTION_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/unannotated"; + + private static final String GENERAL_EXCEPTION_URL = EXCEPTION_RESOURCE_URL + "/exception"; + private static final String PROCESS_ENGINE_EXCEPTION_URL = EXCEPTION_RESOURCE_URL + "/processEngineException"; + private static final String REST_EXCEPTION_URL = EXCEPTION_RESOURCE_URL + "/restException"; + private static final String AUTH_EXCEPTION_URL = EXCEPTION_RESOURCE_URL + "/authorizationException"; + private static final String AUTH_EXCEPTION_MULTIPLE_URL = EXCEPTION_RESOURCE_URL + "/authorizationExceptionMultiple"; + private static final String STACK_OVERFLOW_ERROR_URL = EXCEPTION_RESOURCE_URL + "/stackOverflowError"; + + + @Test + public void testGeneralExceptionHandler() { + given().header(ACCEPT_WILDCARD_HEADER) + .expect().contentType(ContentType.JSON) + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(Exception.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .body("code", nullValue()) + .when().get(GENERAL_EXCEPTION_URL); + } + + @Test + public void testRestExceptionHandler() { + given().header(ACCEPT_WILDCARD_HEADER) + .expect().contentType(ContentType.JSON) + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .body("code", nullValue()) + .when().get(REST_EXCEPTION_URL); + } + + @Test + public void testProcessEngineExceptionHandler() { + given().header(ACCEPT_WILDCARD_HEADER) + .expect().contentType(ContentType.JSON) + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .body("code", equalTo(0)) + .when().get(PROCESS_ENGINE_EXCEPTION_URL); + } + + @Test + public void testAuthorizationExceptionHandler() { + // TODO remove "resourceName", "resourceId", "permissionName" once the deprecated methods from AuthorizationException are removed + given().header(ACCEPT_WILDCARD_HEADER) + .expect().contentType(ContentType.JSON) + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("The user with id 'someUser' does not have 'somePermission' permission on resource 'someResourceId' of type 'someResourceName'.")) + .body("code", equalTo(0)) + .body("userId", equalTo("someUser")) + .body("resourceName", equalTo("someResourceName")) + .body("resourceId", equalTo("someResourceId")) + .body("permissionName", equalTo("somePermission")) + .body("missingAuthorizations.resourceName", hasItems("someResourceName")) + .body("missingAuthorizations.resourceId", hasItems("someResourceId")) + .body("missingAuthorizations.permissionName", hasItems("somePermission")) + .when().get(AUTH_EXCEPTION_URL); + } + + @Test + public void testAuthorizationExceptionWithMultipleMissingAuthorizationsHandler() { + // TODO remove "resourceName", "resourceId", "permissionName" once the deprecated methods from AuthorizationException are removed + given().header(ACCEPT_WILDCARD_HEADER) + .expect().contentType(ContentType.JSON) + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("code", equalTo(0)) + .body("message", equalTo("The user with id 'someUser' does not have one of the following permissions: 'somePermission1' permission on resource " + + "'someResourceId1' of type 'someResourceName1' or 'somePermission2' permission on resource " + + "'someResourceId2' of type 'someResourceName2'")) + .body("userId", equalTo("someUser")) + .body("resourceName", equalTo(null)) + .body("resourceId", equalTo(null)) + .body("permissionName", equalTo(null)) + .body("missingAuthorizations.resourceName", hasItems("someResourceName1", "someResourceName2")) + .body("missingAuthorizations.resourceId", hasItems("someResourceId1", "someResourceId2")) + .body("missingAuthorizations.permissionName", hasItems("somePermission1", "somePermission2")) + .when().get(AUTH_EXCEPTION_MULTIPLE_URL); + } + + @Test + public void testThrowableHandler() { + given().header(ACCEPT_WILDCARD_HEADER) + .expect().contentType(ContentType.JSON) + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(StackOverflowError.class.getSimpleName())) + .body("message", equalTo("Stack overflow")) + .body("code", nullValue()) + .when().get(STACK_OVERFLOW_ERROR_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExecutionRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExecutionRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f400df17ab1018d21f4991f0099d82b39dca3dd0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExecutionRestServiceInteractionTest.java @@ -0,0 +1,1655 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ID; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.EqualsList; +import org.camunda.bpm.engine.rest.helper.EqualsMap; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsNullValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.DeserializationTypeValidator; +import org.camunda.bpm.engine.runtime.EventSubscription; +import org.camunda.bpm.engine.runtime.EventSubscriptionQuery; +import org.camunda.bpm.engine.runtime.Execution; +import org.camunda.bpm.engine.runtime.ExecutionQuery; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.BooleanValue; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class ExecutionRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String EXECUTION_URL = TEST_RESOURCE_ROOT_PATH + "/execution/{id}"; + protected static final String SIGNAL_EXECUTION_URL = EXECUTION_URL + "/signal"; + protected static final String EXECUTION_LOCAL_VARIABLES_URL = EXECUTION_URL + "/localVariables"; + protected static final String SINGLE_EXECUTION_LOCAL_VARIABLE_URL = EXECUTION_LOCAL_VARIABLES_URL + "/{varId}"; + protected static final String SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL = SINGLE_EXECUTION_LOCAL_VARIABLE_URL + "/data"; + protected static final String MESSAGE_SUBSCRIPTION_URL = EXECUTION_URL + "/messageSubscriptions/{messageName}"; + protected static final String TRIGGER_MESSAGE_SUBSCRIPTION_URL = EXECUTION_URL + "/messageSubscriptions/{messageName}/trigger"; + protected static final String CREATE_INCIDENT_URL = EXECUTION_URL + "/create-incident"; + + private RuntimeServiceImpl runtimeServiceMock; + + @Before + public void setUpRuntimeData() { + runtimeServiceMock = mock(RuntimeServiceImpl.class); + when(runtimeServiceMock.getVariablesLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, true)).thenReturn(EXAMPLE_VARIABLES); + mockEventSubscriptionQuery(); + + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + } + + private void mockEventSubscriptionQuery() { + EventSubscription mockSubscription = MockProvider.createMockEventSubscription(); + EventSubscriptionQuery mockQuery = mock(EventSubscriptionQuery.class); + when(runtimeServiceMock.createEventSubscriptionQuery()).thenReturn(mockQuery); + when(mockQuery.executionId(eq(MockProvider.EXAMPLE_EXECUTION_ID))).thenReturn(mockQuery); + when(mockQuery.eventType(eq(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_TYPE))).thenReturn(mockQuery); + when(mockQuery.eventName(eq(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_NAME))).thenReturn(mockQuery); + when(mockQuery.singleResult()).thenReturn(mockSubscription); + } + + @Test + public void testGetSingleExecution() { + Execution mockExecution = MockProvider.createMockExecution(); + ExecutionQuery sampleExecutionQuery = mock(ExecutionQuery.class); + when(runtimeServiceMock.createExecutionQuery()).thenReturn(sampleExecutionQuery); + when(sampleExecutionQuery.executionId(MockProvider.EXAMPLE_EXECUTION_ID)).thenReturn(sampleExecutionQuery); + when(sampleExecutionQuery.singleResult()).thenReturn(mockExecution); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_EXECUTION_ID)) + .body("ended", equalTo(MockProvider.EXAMPLE_EXECUTION_IS_ENDED)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .when().get(EXECUTION_URL); + } + + @Test + public void testGetNonExistingExecution() { + ExecutionQuery sampleExecutionQuery = mock(ExecutionQuery.class); + when(runtimeServiceMock.createExecutionQuery()).thenReturn(sampleExecutionQuery); + when(sampleExecutionQuery.executionId(anyString())).thenReturn(sampleExecutionQuery); + when(sampleExecutionQuery.singleResult()).thenReturn(null); + + String nonExistingExecutionId = "aNonExistingInstanceId"; + + given().pathParam("id", nonExistingExecutionId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Execution with id " + nonExistingExecutionId + " does not exist")) + .when().get(EXECUTION_URL); + } + + @Test + public void testSignalExecution() { + String variableKey = "aKey"; + int variableValue = 123; + + Map variablesJson = new HashMap<>(); + Map variables = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SIGNAL_EXECUTION_URL); + + Map expectedSignalVariables = new HashMap<>(); + expectedSignalVariables.put(variableKey, variableValue); + + verify(runtimeServiceMock).signal(eq(MockProvider.EXAMPLE_EXECUTION_ID), argThat(new EqualsMap(expectedSignalVariables))); + } + + @Test + public void testSignalWithUnparseableIntegerVariable() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + + Map variablesJson = new HashMap<>(); + Map variables = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot signal execution anExecutionId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testSignalWithUnparseableShortVariable() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + + Map variablesJson = new HashMap<>(); + Map variables = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot signal execution anExecutionId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testSignalWithUnparseableLongVariable() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variablesJson = new HashMap<>(); + Map variables = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot signal execution anExecutionId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testSignalWithUnparseableDoubleVariable() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + + Map variablesJson = new HashMap<>(); + Map variables = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot signal execution anExecutionId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testSignalWithUnparseableDateVariable() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variablesJson = new HashMap<>(); + Map variables = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot signal execution anExecutionId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testSignalWithNotSupportedVariableType() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "X"; + + + Map variablesJson = new HashMap<>(); + Map variables = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot signal execution anExecutionId: Unsupported value type 'X'")) + .when().post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testSignalNonExistingExecution() { + doThrow(new ProcessEngineException("expected exception")).when(runtimeServiceMock).signal(any(), any()); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot signal execution " + MockProvider.EXAMPLE_EXECUTION_ID + ": expected exception")) + .when().post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testSignalThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).signal(any(), any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SIGNAL_EXECUTION_URL); + } + + @Test + public void testGetLocalVariables() { + Response response = given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(String.class.getSimpleName())) + .when().get(EXECUTION_LOCAL_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + } + + @Test + public void testGetLocalVariablesForNonExistingExecution() { + when(runtimeServiceMock.getVariablesLocalTyped(anyString(), eq(true))).thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", "aNonExistingExecutionId") + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when().get(EXECUTION_LOCAL_VARIABLES_URL); + } + + @Test + public void testGetLocalObjectVariables() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(runtimeServiceMock.getVariablesLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo(payload)) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(EXECUTION_LOCAL_VARIABLES_URL); + + // then + verify(runtimeServiceMock).getVariablesLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, true); + } + + @Test + public void testGetLocalObjectVariablesSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(runtimeServiceMock.getVariablesLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .queryParam("deserializeValues", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo("a serialized value")) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(EXECUTION_LOCAL_VARIABLES_URL); + + // then + verify(runtimeServiceMock).getVariablesLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, false); + } + + @Test + public void testGetLocalVariablesThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).getVariablesLocalTyped(anyString(), anyBoolean()); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(EXECUTION_LOCAL_VARIABLES_URL); + } + + @Test + public void testLocalVariableModification() { + Map messageBodyJson = new HashMap<>(); + + String variableKey = "aKey"; + int variableValue = 123; + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + List deletions = new ArrayList<>(); + deletions.add("deleteKey"); + messageBodyJson.put("deletions", deletions); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(EXECUTION_LOCAL_VARIABLES_URL); + + Map expectedModifications = new HashMap<>(); + expectedModifications.put(variableKey, variableValue); + verify(runtimeServiceMock).updateVariablesLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), argThat(new EqualsMap(expectedModifications)), + argThat(new EqualsList(deletions))); + } + + @Test + public void testLocalVariableModificationForNonExistingExecution() { + doThrow(new ProcessEngineException("expected exception")).when(runtimeServiceMock).updateVariablesLocal(any(), any(), any()); + + Map messageBodyJson = new HashMap<>(); + + String variableKey = "aKey"; + int variableValue = 123; + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for execution " + MockProvider.EXAMPLE_EXECUTION_ID + ": expected exception")) + .when().post(EXECUTION_LOCAL_VARIABLES_URL); + } + + @Test + public void testEmptyLocalVariableModification() { + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(EXECUTION_LOCAL_VARIABLES_URL); + } + + @Test + public void testLocalVariableModificationThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).updateVariablesLocal(any(), any(), any()); + + Map messageBodyJson = new HashMap<>(); + + String variableKey = "aKey"; + int variableValue = 123; + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(EXECUTION_LOCAL_VARIABLES_URL); + } + + @Test + public void testGetSingleLocalVariable() { + String variableKey = "aVariableKey"; + int variableValue = 123; + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(Variables.integerValue(variableValue)); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", is(123)) + .body("type", is("Integer")) + .when().get(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + + @Test + public void testGetSingleLocalVariableData() { + + when(runtimeServiceMock.getVariableLocalTyped(anyString(), eq(EXAMPLE_BYTES_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE_BYTES); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_BYTES_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .when() + .get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, EXAMPLE_BYTES_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalVariableDataNonExisting() { + + when(runtimeServiceMock.getVariableLocalTyped(anyString(), eq("nonExisting"), eq(false))).thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", "nonExisting") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("execution variable with name " + "nonExisting" + " does not exist")) + .when() + .get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, "nonExisting", false); + } + + @Test + public void testGetSingleLocalVariabledataNotBinary() { + + when(runtimeServiceMock.getVariableLocalTyped(anyString(), eq(EXAMPLE_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, EXAMPLE_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalObjectVariable() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo(payload)) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + // then + verify(runtimeServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, variableKey, true); + } + + @Test + public void testGetSingleLocalObjectVariableSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo("a serialized value")) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + // then + verify(runtimeServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_EXECUTION_ID, variableKey, false); + } + + @Test + public void testNonExistingLocalVariable() { + String variableKey = "aVariableKey"; + + when(runtimeServiceMock.getVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey))).thenReturn(null); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("execution variable with name " + variableKey + " does not exist")) + .when().get(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testGetLocalVariableForNonExistingExecution() { + String variableKey = "aVariableKey"; + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), eq(true))) + .thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot get execution variable " + variableKey + ": expected exception")) + .when().get(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testGetLocalVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).getVariableLocalTyped(anyString(), anyString(), anyBoolean()); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testGetFileVariable() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(mimeType).create(); + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON.toString()) + .and() + .body("valueInfo.mimeType", equalTo(mimeType)) + .body("valueInfo.filename", equalTo(filename)) + .body("value", nullValue()) + .when().get(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testGetNullFileVariable() { + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).mimeType(mimeType).create(); + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(""))) + .when().get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithTypeAndEncoding() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + String contentType = response.contentType().replaceAll(" ", ""); + assertThat(contentType, is(ContentType.TEXT + ";charset=" + encoding)); + } + + @Test + public void testGetFileVariableDownloadWithoutType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).create(); + + when(runtimeServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .and() + .body(is(equalTo(new String(byteContent)))) + .header("Content-Disposition", containsString(filename)) + .when().get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testCannotDownloadVariableOtherThanFile() { + String variableKey = "aVariableKey"; + BooleanValue variableValue = Variables.booleanValue(true); + + when(runtimeServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariable() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsUntypedValue.matcher().value(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeInteger() { + String variableKey = "aVariableKey"; + Integer variableValue = 123; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.integerValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableInteger() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class))) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeShort() { + String variableKey = "aVariableKey"; + Short variableValue = 123; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.shortValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableShort() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class))) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeLong() { + String variableKey = "aVariableKey"; + Long variableValue = 123L; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.longValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableLong() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class))) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeDouble() { + String variableKey = "aVariableKey"; + Double variableValue = 123.456; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.doubleValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDouble() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class))) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeBoolean() { + String variableKey = "aVariableKey"; + Boolean variableValue = true; + String type = "Boolean"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.booleanValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeDate() throws Exception { + Date now = new Date(); + + String variableKey = "aVariableKey"; + String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now); + String type = "Date"; + + Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.dateValue(expectedValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDate() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Date"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put execution variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class))) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "X"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put execution variable aVariableKey: Unsupported value type 'X'")) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "String"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).setVariableLocal(anyString(), anyString(), any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalBinaryVariable() { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal( + eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleLocalBinaryVariableWithValueType() { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "Bytes", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal( + eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleLocalBinaryVariableWithUnknownValueType() { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "SomeUnknownType", "text/plain") + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Unsupported value type 'SomeUnknownType'")) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock, never()).setVariableLocal(anyString(), anyString(), any(Object.class)); + } + + @Test + public void testPutSingleLocalBinaryVariableWithValueTypeOfWrongMimeType() { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "{ \"type\": \"Bytes\"", "application/json") + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Form part with name 'valueType' must have a text/plain value")) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock, never()).setVariableLocal(anyString(), anyString(), any(Object.class)); + } + + @Test + public void testPutSingleLocalBinaryVariableWithNoValue() { + byte[] bytes = new byte[0]; + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal( + eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleLocalSerializableVariableFromJson() throws Exception { + + ArrayList serializable = new ArrayList<>(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable))); + } + + @Test + public void testValidationOnPutSingleLocalSerializableVariableFromJson() throws Exception { + boolean previousIsValidationEnabled = processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled(); + DeserializationTypeValidator previousValidator = processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator(); + + DeserializationTypeValidator validatorMock = mock(DeserializationTypeValidator.class); + when(validatorMock.validate(anyString())).thenReturn(true); + when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(true); + when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(validatorMock); + + try { + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString("test"); + String typeName = TypeFactory.defaultInstance().constructType(String.class).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(validatorMock).validate("java.lang.String"); + verifyNoMoreInteractions(validatorMock); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value("test"))); + } finally { + when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(previousIsValidationEnabled); + when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(previousValidator); + } + } + + @Test + public void testFailingValidationOnPutSingleLocalSerializableVariableFromJson() throws Exception { + boolean previousIsValidationEnabled = processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled(); + DeserializationTypeValidator previousValidator = processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator(); + + DeserializationTypeValidator validatorMock = mock(DeserializationTypeValidator.class); + when(validatorMock.validate(anyString())).thenReturn(false); + when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(true); + when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(validatorMock); + + try { + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString("test"); + String typeName = TypeFactory.defaultInstance().constructType(String.class).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(validatorMock).validate("java.lang.String"); + verifyNoMoreInteractions(validatorMock); + } finally { + when(processEngine.getProcessEngineConfiguration().isDeserializationTypeValidationEnabled()).thenReturn(previousIsValidationEnabled); + when(processEngine.getProcessEngineConfiguration().getDeserializationTypeValidator()).thenReturn(previousValidator); + } + } + + @Test + public void testPutSingleLocalSerializableVariableUnsupportedMediaType() throws Exception { + + ArrayList serializable = new ArrayList<>(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, "unsupported") + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Unrecognized content type for serialized java type: unsupported")) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock, never()).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + eq(serializable)); + } + + @Test + public void testPutSingleLocalBinaryVariableThrowsAuthorizationException() { + byte[] bytes = "someContent".getBytes(); + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).setVariableLocal(anyString(), anyString(), any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", "unspecified", bytes) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableFromSerialized() { + String serializedValue = "{\"prop\" : \"value\"}"; + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, ValueType.OBJECT.getName(), "aDataFormat", "aRootType"); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsObjectValue + .objectValueMatcher() + .serializationFormat("aDataFormat") + .objectTypeName("aRootType") + .serializedValue(serializedValue))); + } + + @Test + public void testPutSingleLocalVariableFromInvalidSerialized() { + String serializedValue = "{\"prop\" : \"value\"}"; + + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, "aNonExistingType", null, null); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put execution variable aVariableKey: Unsupported value type 'aNonExistingType'")) + .when() + .put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableFromSerializedWithNoValue() { + String variableKey = "aVariableKey"; + + Map requestJson = VariablesBuilder + .getObjectValueMap(null, ValueType.OBJECT.getName(), null, null); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(requestJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsObjectValue + .objectValueMatcher() + .serializationFormat(null) + .objectTypeName(null) + .serializedValue(null))); + } + + @Test + public void testPutSingleLocalVariableWithNoValue() { + String variableKey = "aVariableKey"; + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + argThat(EqualsNullValue.matcher())); + } + + + @Test + public void testPutLocalVariableForNonExistingExecution() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new BadUserRequestException("expected exception")) + .when(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), any()); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot put execution variable " + variableKey + ": expected exception")) + .when().put(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testDeleteSingleLocalVariable() { + String variableKey = "aVariableKey"; + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + + verify(runtimeServiceMock).removeVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey)); + } + + @Test + public void testPostSingleLocalFileVariableWithEncodingAndMimeType() { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype + "; encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(encoding)); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleLocalFileVariableWithMimeType() { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleLocalFileVariableWithEncoding() { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, "encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + //when the user passes an encoding, he has to provide the type, too + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleLocalFileVariableOnlyFilename() throws Exception { + + String variableKey = "aVariableKey"; + String filename = "test.txt"; + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .multiPart("data", filename, new byte[0]) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_EXECUTION_LOCAL_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(runtimeServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(MediaType.APPLICATION_OCTET_STREAM)); + assertThat(captured.getValue().available(), is(0)); + } + + @Test + public void testDeleteLocalVariableForNonExistingExecution() { + String variableKey = "aVariableKey"; + + doThrow(new ProcessEngineException("expected exception")) + .when(runtimeServiceMock).removeVariableLocal(eq(MockProvider.EXAMPLE_EXECUTION_ID), eq(variableKey)); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot delete execution variable " + variableKey + ": expected exception")) + .when().delete(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testDeleteLocalVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).removeVariableLocal(anyString(), anyString()); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .delete(SINGLE_EXECUTION_LOCAL_VARIABLE_URL); + } + + @Test + public void testGetMessageEventSubscription() { + String messageName = MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_NAME; + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("messageName", messageName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_ID)) + .body("eventType", equalTo(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_TYPE)) + .body("eventName", equalTo(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_NAME)) + .body("executionId", equalTo(MockProvider.EXAMPLE_EXECUTION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("activityId", equalTo(MockProvider.EXAMPLE_ACTIVITY_ID)) + .body("createdDate", equalTo(MockProvider.EXAMPLE_EVENT_SUBSCRIPTION_CREATION_DATE)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .when().get(MESSAGE_SUBSCRIPTION_URL); + } + + @Test + public void testGetNonExistingMessageEventSubscription() { + EventSubscriptionQuery sampleEventSubscriptionQuery = mock(EventSubscriptionQuery.class); + when(runtimeServiceMock.createEventSubscriptionQuery()).thenReturn(sampleEventSubscriptionQuery); + when(sampleEventSubscriptionQuery.executionId(anyString())).thenReturn(sampleEventSubscriptionQuery); + when(sampleEventSubscriptionQuery.eventName(anyString())).thenReturn(sampleEventSubscriptionQuery); + when(sampleEventSubscriptionQuery.eventType(anyString())).thenReturn(sampleEventSubscriptionQuery); + when(sampleEventSubscriptionQuery.singleResult()).thenReturn(null); + + String executionId = MockProvider.EXAMPLE_EXECUTION_ID; + String nonExistingMessageName = "aMessage"; + + given().pathParam("id", executionId).pathParam("messageName", nonExistingMessageName) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Message event subscription for execution " + executionId + " named " + nonExistingMessageName + " does not exist")) + .when().get(MESSAGE_SUBSCRIPTION_URL); + } + + @Test + public void testMessageEventTriggering() { + String messageName = "aMessageName"; + String variableKey1 = "aVarName"; + String variableValue1 = "aVarValue"; + String variableKey2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + + Map variables = VariablesBuilder.create() + .variable(variableKey1, variableValue1) + .variable(variableKey2, variableValue2).getVariables(); + + Map variablesJson = new HashMap<>(); + variablesJson.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("messageName", messageName) + .contentType(ContentType.JSON).body(variablesJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(TRIGGER_MESSAGE_SUBSCRIPTION_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put(variableKey1, variableValue1); + expectedVariables.put(variableKey2, variableValue2); + + verify(runtimeServiceMock).messageEventReceived(eq(messageName), eq(MockProvider.EXAMPLE_EXECUTION_ID), + argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testMessageEventTriggeringWithoutVariables() { + String messageName = "aMessageName"; + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("messageName", messageName) + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(TRIGGER_MESSAGE_SUBSCRIPTION_URL); + + verify(runtimeServiceMock).messageEventReceived(eq(messageName), eq(MockProvider.EXAMPLE_EXECUTION_ID), + argThat(new EqualsMap(null))); + } + + @Test + public void testFailingMessageEventTriggering() { + String messageName = "someMessage"; + doThrow(new ProcessEngineException("expected exception")) + .when(runtimeServiceMock).messageEventReceived(any(), any(), any()); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("messageName", messageName) + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot trigger message " + messageName + " for execution " + MockProvider.EXAMPLE_EXECUTION_ID + ": expected exception")) + .when().post(TRIGGER_MESSAGE_SUBSCRIPTION_URL); + } + + @Test + public void testMessageEventTriggeringThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)) + .when(runtimeServiceMock).messageEventReceived(any(), any(), any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID) + .pathParam("messageName", "someMessage") + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .post(TRIGGER_MESSAGE_SUBSCRIPTION_URL); + } + + @Test + public void testCreateIncident() { + when(runtimeServiceMock.createIncident(anyString(), anyString(), anyString(), anyString())).thenReturn(mock(Incident.class)); + Map json = new HashMap<>(); + json.put("incidentType", "incidentType"); + json.put("configuration", "configuration"); + json.put("message", "message"); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(json).then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(CREATE_INCIDENT_URL); + + verify(runtimeServiceMock).createIncident("incidentType", MockProvider.EXAMPLE_EXECUTION_ID, "configuration", "message"); + } + + @Test + public void testCreateIncidentWithNullIncidentType() { + doThrow(new BadUserRequestException()).when(runtimeServiceMock).createIncident(any(), any(), any(), any()); + Map json = new HashMap<>(); + json.put("configuration", "configuration"); + json.put("message", "message"); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).contentType(ContentType.JSON).body(json).then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).when().post(CREATE_INCIDENT_URL); + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExecutionRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExecutionRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d8ad3a4c149b5c74e2215deafc38355c96951afc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExecutionRestServiceQueryTest.java @@ -0,0 +1,1161 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.Execution; +import org.camunda.bpm.engine.runtime.ExecutionQuery; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class ExecutionRestServiceQueryTest extends + AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String EXECUTION_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/execution"; + protected static final String EXECUTION_COUNT_QUERY_URL = EXECUTION_QUERY_URL + "/count"; + + private ExecutionQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockExecutionQuery(createMockExecutionList()); + } + + private ExecutionQuery setUpMockExecutionQuery(List mockedExecutions) { + ExecutionQuery sampleExecutionQuery = mock(ExecutionQuery.class); + when(sampleExecutionQuery.list()).thenReturn(mockedExecutions); + when(sampleExecutionQuery.count()).thenReturn((long) mockedExecutions.size()); + when(processEngine.getRuntimeService().createExecutionQuery()).thenReturn(sampleExecutionQuery); + return sampleExecutionQuery; + } + + private List createMockExecutionList() { + List mocks = new ArrayList(); + + mocks.add(MockProvider.createMockExecution()); + return mocks; + } + + @Test + public void testInvalidVariableRequests() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_" + invalidComparator + "_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid variable comparator specified: " + invalidComparator)) + .when().get(EXECUTION_QUERY_URL); + + given().queryParam("processVariables", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid process variable comparator specified: " + invalidComparator)) + .when().get(EXECUTION_QUERY_URL); + + // invalid format + queryValue = "invalidFormattedVariableQuery"; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("variable query parameter has to have format KEY_OPERATOR_VALUE")) + .when().get(EXECUTION_QUERY_URL); + + given().queryParam("processVariables", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("variable query parameter has to have format KEY_OPERATOR_VALUE")) + .when().get(EXECUTION_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "definitionId") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + } + + @Test + public void testExecutionRetrieval() { + String queryKey = "key"; + Response response = given().queryParam("processDefinitionKey", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).processDefinitionKey(queryKey); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + Assert.assertEquals("There should be one execution returned.", 1, executions.size()); + Assert.assertNotNull("There should be one execution returned", executions.get(0)); + + String returnedExecutionId = from(content).getString("[0].id"); + Boolean returnedIsEnded = from(content).getBoolean("[0].ended"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_IS_ENDED, returnedIsEnded); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testIncompleteExecution() { + setUpMockExecutionQuery(createIncompleteMockExecutions()); + Response response = expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + String content = response.asString(); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + Assert.assertNull("Should be null, as it is also null in the original execution on the server.", + returnedProcessInstanceId); + } + + private List createIncompleteMockExecutions() { + List mocks = new ArrayList(); + Execution mockExecution = mock(Execution.class); + when(mockExecution.getId()).thenReturn(MockProvider.EXAMPLE_EXECUTION_ID); + + mocks.add(mockExecution); + return mocks; + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(EXECUTION_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testAdditionalParametersExcludingVariables() { + Map queryParameters = getCompleteQueryParameters(); + + given().queryParams(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + verify(mockedQuery).processInstanceBusinessKey(queryParameters.get("businessKey")); + verify(mockedQuery).processInstanceId(queryParameters.get("processInstanceId")); + verify(mockedQuery).processDefinitionKey(queryParameters.get("processDefinitionKey")); + verify(mockedQuery).processDefinitionId(queryParameters.get("processDefinitionId")); + verify(mockedQuery).activityId(queryParameters.get("activityId")); + verify(mockedQuery).signalEventSubscriptionName(queryParameters.get("signalEventSubscriptionName")); + verify(mockedQuery).messageEventSubscriptionName(queryParameters.get("messageEventSubscriptionName")); + verify(mockedQuery).active(); + verify(mockedQuery).suspended(); + verify(mockedQuery).incidentId(queryParameters.get("incidentId")); + verify(mockedQuery).incidentMessage(queryParameters.get("incidentMessage")); + verify(mockedQuery).incidentMessageLike(queryParameters.get("incidentMessageLike")); + verify(mockedQuery).incidentType(queryParameters.get("incidentType")); + + verify(mockedQuery).list(); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("businessKey", "aBusinessKey"); + parameters.put("processInstanceId", "aProcInstId"); + parameters.put("processDefinitionKey", "aProcDefKey"); + parameters.put("processDefinitionId", "aProcDefId"); + parameters.put("activityId", "anActivityId"); + parameters.put("signalEventSubscriptionName", "anEventName"); + parameters.put("messageEventSubscriptionName", "aMessageName"); + parameters.put("suspended", "true"); + parameters.put("active", "true"); + parameters.put("incidentId", "incId"); + parameters.put("incidentType", "incType"); + parameters.put("incidentMessage", "incMessage"); + parameters.put("incidentMessageLike", "incMessageLike"); + + return parameters; + } + + @Test + public void testVariableValueEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gt_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueGreaterThan(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gteq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueGreaterThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lt_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueLessThan(variableName, variableValue); + } + + @Test + public void testVariableValueLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lteq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueLessThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + + @Test + public void testVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testProcessVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("processVariables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).processVariableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testProcessVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("processVariables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).processVariableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testProcessVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("processVariables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).processVariableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testProcessVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("processVariables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).processVariableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableValueEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLessThan("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLikeAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + @Test + public void testVariableValueNotEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + + @Test + public void testVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testProcessVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).processVariableValueEquals("varName", "varValue"); + } + + @Test + public void testProcessVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).processVariableValueNotEquals("varName", "varValue"); + } + + @Test + public void testProcessVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("processVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).processVariableValueEquals("varName", "varValue"); + } + + @Test + public void testProcessVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("processVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).processVariableValueNotEquals("varName", "varValue"); + } + + @Test + public void testProcessVariableParameters() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("processVariables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).processVariableValueEquals(variableName, variableValue); + + queryValue = variableName + "_neq_" + variableValue; + given().queryParam("processVariables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + verify(mockedQuery).processVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName1, variableValue1); + verify(mockedQuery).variableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleProcessVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam("processVariables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + verify(mockedQuery).processVariableValueEquals(variableName1, variableValue1); + verify(mockedQuery).processVariableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(EXECUTION_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).variableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + + } + + @Test + public void testMultipleProcessVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("processVariables", variables); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(EXECUTION_QUERY_URL); + + verify(mockedQuery).processVariableValueEquals(variableName, variableValue); + verify(mockedQuery).processVariableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + + } + + @Test + public void testCompletePostParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given().contentType(POST_JSON_CONTENT_TYPE).body(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(EXECUTION_QUERY_URL); + + verify(mockedQuery).processInstanceBusinessKey(queryParameters.get("businessKey")); + verify(mockedQuery).processInstanceId(queryParameters.get("processInstanceId")); + verify(mockedQuery).processDefinitionKey(queryParameters.get("processDefinitionKey")); + verify(mockedQuery).processDefinitionId(queryParameters.get("processDefinitionId")); + verify(mockedQuery).activityId(queryParameters.get("activityId")); + verify(mockedQuery).signalEventSubscriptionName(queryParameters.get("signalEventSubscriptionName")); + verify(mockedQuery).messageEventSubscriptionName(queryParameters.get("messageEventSubscriptionName")); + verify(mockedQuery).active(); + verify(mockedQuery).suspended(); + verify(mockedQuery).incidentId(queryParameters.get("incidentId")); + verify(mockedQuery).incidentMessage(queryParameters.get("incidentMessage")); + verify(mockedQuery).incidentMessageLike(queryParameters.get("incidentMessageLike")); + verify(mockedQuery).incidentType(queryParameters.get("incidentType")); + verify(mockedQuery).list(); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockExecutionQuery(createMockExecutionsTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXECUTION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockExecutionQuery(createMockExecutionsTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + private List createMockExecutionsTwoTenants() { + return Arrays.asList( + MockProvider.createMockExecution(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockExecution(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("definitionKey").desc() + .orderBy("instanceId").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(EXECUTION_QUERY_URL); + + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given().queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given().queryParam("firstResult", firstResult) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(EXECUTION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(EXECUTION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b4ed9669a91fbe71f94b21b086521dc88e34b94a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskRestServiceInteractionTest.java @@ -0,0 +1,2238 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockBatch; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + +import io.restassured.http.ContentType; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.servlet.ServletContextEvent; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.externaltask.ExternalTaskQuery; +import org.camunda.bpm.engine.externaltask.ExternalTaskQueryTopicBuilder; +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.externaltask.UpdateExternalTaskRetriesBuilder; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.impl.ExternalTaskQueryImpl; +import org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl; +import org.camunda.bpm.engine.impl.HistoryServiceImpl; +import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.impl.externaltask.FetchAndLockBuilderImpl; +import org.camunda.bpm.engine.rest.dto.SortingDto; +import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskQueryDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.EqualsVariableMap; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.impl.FetchAndLockContextListener; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mockito; + +/** + * @author Thorben Lindhauer + * + */ +public class ExternalTaskRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String EXTERNAL_TASK_URL = TEST_RESOURCE_ROOT_PATH + "/external-task"; + protected static final String FETCH_EXTERNAL_TASK_URL = EXTERNAL_TASK_URL + "/fetchAndLock"; + protected static final String SINGLE_EXTERNAL_TASK_URL = EXTERNAL_TASK_URL + "/{id}"; + protected static final String COMPLETE_EXTERNAL_TASK_URL = SINGLE_EXTERNAL_TASK_URL + "/complete"; + protected static final String GET_EXTERNAL_TASK_ERROR_DETAILS_URL = SINGLE_EXTERNAL_TASK_URL + "/errorDetails"; + protected static final String HANDLE_EXTERNAL_TASK_FAILURE_URL = SINGLE_EXTERNAL_TASK_URL + "/failure"; + protected static final String HANDLE_EXTERNAL_TASK_BPMN_ERROR_URL = SINGLE_EXTERNAL_TASK_URL + "/bpmnError"; + protected static final String UNLOCK_EXTERNAL_TASK_URL = SINGLE_EXTERNAL_TASK_URL + "/unlock"; + protected static final String RETRIES_EXTERNAL_TASK_URL = SINGLE_EXTERNAL_TASK_URL + "/retries"; + protected static final String RETRIES_EXTERNAL_TASK_SYNC_URL = EXTERNAL_TASK_URL + "/retries"; + protected static final String RETRIES_EXTERNAL_TASKS_ASYNC_URL = EXTERNAL_TASK_URL + "/retries-async"; + protected static final String PRIORITY_EXTERNAL_TASK_URL = SINGLE_EXTERNAL_TASK_URL + "/priority"; + protected static final String LOCK_EXTERNAL_TASK = SINGLE_EXTERNAL_TASK_URL + "/lock"; + protected static final String EXTEND_LOCK_ON_EXTERNAL_TASK = SINGLE_EXTERNAL_TASK_URL + "/extendLock"; + + + protected ExternalTaskService externalTaskService; + protected RuntimeServiceImpl runtimeServiceMock; + protected HistoryServiceImpl historyServiceMock; + + protected LockedExternalTask lockedExternalTaskMock; + protected ExternalTaskQueryTopicBuilder fetchTopicBuilder; + protected FetchAndLockBuilderImpl fetchAndLockBuilder; + + protected ExternalTask externalTaskMock; + protected ExternalTaskQuery externalTaskQueryMock; + + protected UpdateExternalTaskRetriesBuilder updateRetriesBuilder; + + @Before + public void setUpRuntimeData() { + externalTaskService = mock(ExternalTaskService.class); + when(processEngine.getExternalTaskService()).thenReturn(externalTaskService); + + runtimeServiceMock = mock(RuntimeServiceImpl.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + + historyServiceMock = mock(HistoryServiceImpl.class); + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + // locked external task + lockedExternalTaskMock = MockProvider.createMockLockedExternalTask(); + + // fetching + fetchTopicBuilder = mock(ExternalTaskQueryTopicBuilder.class); + when(externalTaskService.fetchAndLock(anyInt(), any())).thenReturn(fetchTopicBuilder); + when(externalTaskService.fetchAndLock(anyInt(), any(), anyBoolean())).thenReturn(fetchTopicBuilder); + + when(fetchTopicBuilder.topic(any(), anyLong())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.variables(Mockito.>any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.variables(Mockito.any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.enableCustomObjectDeserialization()).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.localVariables()).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.topic(any(), anyLong())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.businessKey(any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.processDefinitionId(any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.processDefinitionIdIn(Mockito.any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.processDefinitionKey(any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.processDefinitionKeyIn(Mockito.any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.processInstanceVariableEquals(any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.processDefinitionVersionTag(any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.withoutTenantId()).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.tenantIdIn(Mockito.any())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.includeExtensionProperties()).thenReturn(fetchTopicBuilder); + + fetchAndLockBuilder = mock(FetchAndLockBuilderImpl.class); + when(fetchAndLockBuilder.orderByCreateTime()).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.asc()).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.desc()).thenReturn(fetchAndLockBuilder); + + when(fetchAndLockBuilder.workerId(anyString())).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.maxTasks(anyInt())).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.usePriority(anyBoolean())).thenReturn(fetchAndLockBuilder); + + when(fetchAndLockBuilder.subscribe()).thenReturn(fetchTopicBuilder); + when(externalTaskService.fetchAndLock()).thenReturn(fetchAndLockBuilder); + + Batch batch = createMockBatch(); + updateRetriesBuilder = mock(UpdateExternalTaskRetriesBuilder.class); + when(externalTaskService.updateRetries()).thenReturn(updateRetriesBuilder); + + when(updateRetriesBuilder.externalTaskIds(Mockito.>any())).thenReturn(updateRetriesBuilder); + when(updateRetriesBuilder.processInstanceIds(Mockito.>any())).thenReturn(updateRetriesBuilder); + when(updateRetriesBuilder.externalTaskQuery(any())).thenReturn(updateRetriesBuilder); + when(updateRetriesBuilder.processInstanceQuery(any())).thenReturn(updateRetriesBuilder); + when(updateRetriesBuilder.historicProcessInstanceQuery(any())).thenReturn(updateRetriesBuilder); + when(updateRetriesBuilder.setAsync(anyInt())).thenReturn(batch); + + // querying + externalTaskQueryMock = mock(ExternalTaskQuery.class); + when(externalTaskQueryMock.externalTaskId(any())).thenReturn(externalTaskQueryMock); + when(externalTaskService.createExternalTaskQuery()).thenReturn(externalTaskQueryMock); + + // external task + externalTaskMock = MockProvider.createMockExternalTask(); + + new FetchAndLockContextListener().contextInitialized(mock(ServletContextEvent.class, RETURNS_DEEP_STUBS)); + } + + @Test + public void testFetchAndLock() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", true); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + parameters.put("topics", Arrays.asList(topicParameter)); + + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(true); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).variables(Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchTopicBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithBusinessKey() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", true); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("businessKey", EXAMPLE_BUSINESS_KEY); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + parameters.put("topics", Arrays.asList(topicParameter)); + + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(true); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).businessKey(EXAMPLE_BUSINESS_KEY); + inOrder.verify(fetchTopicBuilder).variables(Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithProcessDefinition() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", true); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("processDefinitionId", EXAMPLE_PROCESS_DEFINITION_ID); + topicParameter.put("processDefinitionIdIn", Arrays.asList(EXAMPLE_PROCESS_DEFINITION_ID)); + topicParameter.put("processDefinitionKey", EXAMPLE_PROCESS_DEFINITION_KEY); + topicParameter.put("processDefinitionKeyIn", Arrays.asList(EXAMPLE_PROCESS_DEFINITION_KEY)); + topicParameter.put("lockDuration", 12354L); + parameters.put("topics", Arrays.asList(topicParameter)); + + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(true); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).processDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + inOrder.verify(fetchTopicBuilder).processDefinitionIdIn(EXAMPLE_PROCESS_DEFINITION_ID); + inOrder.verify(fetchTopicBuilder).processDefinitionKey(EXAMPLE_PROCESS_DEFINITION_KEY); + inOrder.verify(fetchTopicBuilder).processDefinitionKeyIn(EXAMPLE_PROCESS_DEFINITION_KEY); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithVariableValue() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", true); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("businessKey", EXAMPLE_BUSINESS_KEY); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + + Map variableValueParameter = new HashMap<>(); + variableValueParameter.put(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue()); + topicParameter.put("processVariables", variableValueParameter); + + parameters.put("topics", Arrays.asList(topicParameter)); + + // when + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(true); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).businessKey(EXAMPLE_BUSINESS_KEY); + inOrder.verify(fetchTopicBuilder).variables(Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).processInstanceVariableEquals(variableValueParameter); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithCreateTimeDesc() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", false); + parameters.put("sorting", List.of(create("createTime", "desc"))); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("businessKey", EXAMPLE_BUSINESS_KEY); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + + Map variableValueParameter = new HashMap<>(); + variableValueParameter.put(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue()); + topicParameter.put("processVariables", variableValueParameter); + + parameters.put("topics", Arrays.asList(topicParameter)); + + // when + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + + // then + inOrder.verify(fetchAndLockBuilder).orderByCreateTime(); + inOrder.verify(fetchAndLockBuilder).desc(); + + inOrder.verify(fetchAndLockBuilder).subscribe(); + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).businessKey(EXAMPLE_BUSINESS_KEY); + inOrder.verify(fetchTopicBuilder).variables(Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).processInstanceVariableEquals(variableValueParameter); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithSortOrderInvalidCase() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", false); + parameters.put("sorting", List.of(create("createTime", "DESC"))); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("businessKey", EXAMPLE_BUSINESS_KEY); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + + Map variableValueParameter = new HashMap<>(); + variableValueParameter.put(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue()); + topicParameter.put("processVariables", variableValueParameter); + + parameters.put("topics", Arrays.asList(topicParameter)); + + // when + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot set query sortOrder parameter to value DESC")) + .when().post(FETCH_EXTERNAL_TASK_URL); + + // then + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + inOrder.verify(externalTaskService).fetchAndLock(); + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).orderByCreateTime(); + inOrder.verify(fetchAndLockBuilder, never()).desc(); + inOrder.verify(fetchAndLockBuilder, never()).asc(); + } + + @Test + public void testFetchAndLockWithEmptySortOrder() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", false); + parameters.put("sorting", List.of(create("createTime", ""))); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("businessKey", EXAMPLE_BUSINESS_KEY); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + + Map variableValueParameter = new HashMap<>(); + variableValueParameter.put(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue()); + topicParameter.put("processVariables", variableValueParameter); + + parameters.put("topics", Arrays.asList(topicParameter)); + + // when + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot set query sortOrder parameter to value ")) + .when().post(FETCH_EXTERNAL_TASK_URL); + + // then + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + inOrder.verify(externalTaskService).fetchAndLock(); + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).orderByCreateTime(); + inOrder.verify(fetchAndLockBuilder, never()).desc(); + inOrder.verify(fetchAndLockBuilder, never()).asc(); + } + + @Test + public void testFetchAndLockWithBlankSortOrder() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + String sortOrder = " "; + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", false); + parameters.put("sorting", List.of(create("createTime", sortOrder))); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("businessKey", EXAMPLE_BUSINESS_KEY); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + + Map variableValueParameter = new HashMap<>(); + variableValueParameter.put(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue()); + topicParameter.put("processVariables", variableValueParameter); + + parameters.put("topics", Arrays.asList(topicParameter)); + + // when + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot set query sortOrder parameter to value " + sortOrder)) + .when().post(FETCH_EXTERNAL_TASK_URL); + + // then + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + inOrder.verify(externalTaskService).fetchAndLock(); + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).orderByCreateTime(); + inOrder.verify(fetchAndLockBuilder, never()).desc(); + inOrder.verify(fetchAndLockBuilder, never()).asc(); + } + + @Test + public void testFetchAndLockWithCreateTimeWithoutOrder() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", false); + parameters.put("sorting", List.of(create("createTime", null))); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("businessKey", EXAMPLE_BUSINESS_KEY); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + + Map variableValueParameter = new HashMap<>(); + variableValueParameter.put(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue()); + topicParameter.put("processVariables", variableValueParameter); + + parameters.put("topics", Arrays.asList(topicParameter)); + + // when + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + // then + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).orderByCreateTime(); + inOrder.verify(fetchAndLockBuilder, never()).desc(); // no order call on builder + inOrder.verify(fetchAndLockBuilder, never()).asc(); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).businessKey(EXAMPLE_BUSINESS_KEY); + inOrder.verify(fetchTopicBuilder).variables(Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).processInstanceVariableEquals(variableValueParameter); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithCreateTimeWithInvalidOrder() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", false); + parameters.put("sorting", List.of(create("createTime", "invalid"))); + + // when + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot set query sortOrder parameter to value invalid")) + .when().post(FETCH_EXTERNAL_TASK_URL); + + // then + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + inOrder.verify(externalTaskService).fetchAndLock(); + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).orderByCreateTime(); + inOrder.verify(fetchAndLockBuilder, never()).desc(); + inOrder.verify(fetchAndLockBuilder, never()).asc(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithCreateTimeWithInvalidSortByField() { + // given + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", false); + parameters.put("sorting", List.of(create("invalid", "desc"))); + + // when + given().contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot set query sortBy parameter to value invalid")) + .when().post(FETCH_EXTERNAL_TASK_URL); + + // then + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + inOrder.verify(fetchAndLockBuilder, never()).orderByCreateTime(); + } + + @Test + public void testFetchWithoutVariables() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("lockDuration", 12354L); + parameters.put("topics", Arrays.asList(topicParameter)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("[0].id", equalTo(MockProvider.EXTERNAL_TASK_ID)) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchTopicBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockWithTenant() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + parameters.put("usePriority", true); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("withoutTenantId", true); + topicParameter.put("tenantId", "tenant1"); + topicParameter.put("tenantIdIn", Arrays.asList("tenant2")); + topicParameter.put("lockDuration", 12354L); + parameters.put("topics", Arrays.asList(topicParameter)); + + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(true); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).withoutTenantId(); + inOrder.verify(fetchTopicBuilder).tenantIdIn("tenant2"); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockByProcessDefinitionVersionTag() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("processDefinitionVersionTag", "versionTag"); + parameters.put("topics", Arrays.asList(topicParameter)); + + executePost(parameters); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).processDefinitionVersionTag("versionTag"); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testFetchAndLockIncludeExtensionProperties() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("includeExtensionProperties", true); + parameters.put("topics", Arrays.asList(topicParameter)); + + executePost(parameters); + + // then + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).includeExtensionProperties(); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testEnableCustomObjectDeserialization() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + topicParameter.put("deserializeValues", true); + parameters.put("topics", Arrays.asList(topicParameter)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + + inOrder.verify(fetchTopicBuilder).variables(Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).enableCustomObjectDeserialization(); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, externalTaskService); + } + + @Test + public void testLocalVariables() { + // given + when(fetchTopicBuilder.execute()).thenReturn(Arrays.asList(lockedExternalTaskMock)); + + // when + Map parameters = new HashMap<>(); + parameters.put("maxTasks", 5); + parameters.put("workerId", "aWorkerId"); + + Map topicParameter = new HashMap<>(); + topicParameter.put("topicName", "aTopicName"); + topicParameter.put("lockDuration", 12354L); + topicParameter.put("variables", Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + topicParameter.put("localVariables", true); + parameters.put("topics", Arrays.asList(topicParameter)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + var topicBuilder = fetchAndLockBuilder.subscribe(); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(topicBuilder).topic("aTopicName", 12354L); + inOrder.verify(topicBuilder).variables(Arrays.asList(EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(topicBuilder).localVariables(); + + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchTopicBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void testComplete() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(COMPLETE_EXTERNAL_TASK_URL); + + verify(externalTaskService).complete("anExternalTaskId", "aWorkerId", null, null); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testCompleteWithVariables() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + + Map variables = VariablesBuilder + .create() + .variable("var1", "val1") + .variable("var2", "val2", "String") + .variable("var3", ValueType.OBJECT.getName(), "val3", "aFormat", "aRootType") + .getVariables(); + parameters.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(COMPLETE_EXTERNAL_TASK_URL); + + verify(externalTaskService).complete( + eq("anExternalTaskId"), + eq("aWorkerId"), + argThat(EqualsVariableMap.matches() + .matcher("var1", EqualsUntypedValue.matcher().value("val1")) + .matcher("var2", EqualsPrimitiveValue.stringValue("val2")) + .matcher("var3", + EqualsObjectValue.objectValueMatcher() + .type(ValueType.OBJECT) + .serializedValue("val3") + .serializationFormat("aFormat") + .objectTypeName("aRootType"))), + eq((Map) null)); + + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testCompleteWithLocalVariables() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + + Map variables = VariablesBuilder + .create() + .variable("var1", "val1") + .variable("var2", "val2", "String") + .variable("var3", ValueType.OBJECT.getName(), "val3", "aFormat", "aRootType") + .getVariables(); + parameters.put("localVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(COMPLETE_EXTERNAL_TASK_URL); + + verify(externalTaskService).complete( + eq("anExternalTaskId"), + eq("aWorkerId"), + eq((Map) null), + argThat(EqualsVariableMap.matches() + .matcher("var1", EqualsUntypedValue.matcher().value("val1")) + .matcher("var2", EqualsPrimitiveValue.stringValue("val2")) + .matcher("var3", + EqualsObjectValue.objectValueMatcher() + .type(ValueType.OBJECT) + .serializedValue("val3") + .serializationFormat("aFormat") + .objectTypeName("aRootType")))); + + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testCompleteNonExistingTask() { + doThrow(new NotFoundException()) + .when(externalTaskService) + .complete(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .post(COMPLETE_EXTERNAL_TASK_URL); + } + + @Test + public void testCompleteThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")) + .when(externalTaskService) + .complete(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(COMPLETE_EXTERNAL_TASK_URL); + } + + @Test + public void testCompleteThrowsBadUserRequestException() { + doThrow(new BadUserRequestException("aMessage")) + .when(externalTaskService) + .complete(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(COMPLETE_EXTERNAL_TASK_URL); + } + + @Test + public void testUnlock() { + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(UNLOCK_EXTERNAL_TASK_URL); + + verify(externalTaskService).unlock("anExternalTaskId"); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testUnlockNonExistingTask() { + doThrow(new NotFoundException()).when(externalTaskService).unlock(any(String.class)); + + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .post(UNLOCK_EXTERNAL_TASK_URL); + + verify(externalTaskService).unlock("anExternalTaskId"); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testUnlockThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")).when(externalTaskService).unlock(any(String.class)); + + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(UNLOCK_EXTERNAL_TASK_URL); + + verify(externalTaskService).unlock("anExternalTaskId"); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testGetErrorDetails() { + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .get(GET_EXTERNAL_TASK_ERROR_DETAILS_URL); + + verify(externalTaskService).getExternalTaskErrorDetails("anExternalTaskId"); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testGetErrorDetailsNonExistingTask() { + doThrow(new NotFoundException()).when(externalTaskService).getExternalTaskErrorDetails(any(String.class)); + + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .get(GET_EXTERNAL_TASK_ERROR_DETAILS_URL); + + verify(externalTaskService).getExternalTaskErrorDetails("anExternalTaskId"); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testGetErrorDetailsThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")).when(externalTaskService).getExternalTaskErrorDetails(any(String.class)); + + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .get(GET_EXTERNAL_TASK_ERROR_DETAILS_URL); + + verify(externalTaskService).getExternalTaskErrorDetails("anExternalTaskId"); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testHandleFailure() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorMessage", "anErrorMessage"); + parameters.put("retries", 5); + parameters.put("retryTimeout", 12345); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_EXTERNAL_TASK_FAILURE_URL); + + verify(externalTaskService).handleFailure("anExternalTaskId", "aWorkerId", "anErrorMessage", null, 5, 12345, null, null); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testHandleFailureWithStackTrace() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorMessage", "anErrorMessage"); + parameters.put("errorDetails", "aStackTrace"); + parameters.put("retries", 5); + parameters.put("retryTimeout", 12345); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_EXTERNAL_TASK_FAILURE_URL); + + verify(externalTaskService).handleFailure("anExternalTaskId", "aWorkerId", "anErrorMessage","aStackTrace", 5, 12345, null, null); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testHandleFailureNonExistingTask() { + doThrow(new NotFoundException()) + .when(externalTaskService) + .handleFailure(any(), any(), any(), any(), anyInt(), anyLong(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorMessage", "anErrorMessage"); + parameters.put("retries", 5); + parameters.put("retryTimeout", 12345); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .post(HANDLE_EXTERNAL_TASK_FAILURE_URL); + } + + @Test + public void testHandleFailureThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")) + .when(externalTaskService) + .handleFailure(any(), any(), any(),any(), anyInt(), anyLong(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorMessage", "anErrorMessage"); + parameters.put("retries", 5); + parameters.put("retryTimeout", 12345); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_EXTERNAL_TASK_FAILURE_URL); + } + + @Test + public void testHandleFailureThrowsBadUserRequestException() { + doThrow(new BadUserRequestException("aMessage")) + .when(externalTaskService) + .handleFailure(any(), any(), any(),any(), anyInt(), anyLong(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorMessage", "anErrorMessage"); + parameters.put("retries", 5); + parameters.put("retryTimeout", 12345); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_EXTERNAL_TASK_FAILURE_URL); + } + + @Test + public void testHandleFailureWithVariables() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorMessage", "anErrorMessage"); + parameters.put("retries", 5); + parameters.put("retryTimeout", 12345); + Map variables = VariablesBuilder.create().variable("var1", "val1").getVariables(); + parameters.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_EXTERNAL_TASK_FAILURE_URL); + + verify(externalTaskService).handleFailure( + eq("anExternalTaskId"), + eq("aWorkerId"), + eq("anErrorMessage"), + eq(null), + eq(5), + eq(12345L), + argThat(EqualsVariableMap.matches().matcher("var1", EqualsUntypedValue.matcher().value("val1"))), + eq((Map) null)); + + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testHandleFailureWithLocalVariables() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorMessage", "anErrorMessage"); + parameters.put("retries", 5); + parameters.put("retryTimeout", 12345); + Map localVariables = VariablesBuilder.create().variable("var1", "val1").getVariables(); + parameters.put("localVariables", localVariables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_EXTERNAL_TASK_FAILURE_URL); + + verify(externalTaskService).handleFailure( + eq("anExternalTaskId"), + eq("aWorkerId"), + eq("anErrorMessage"), + eq(null), + eq(5), + eq(12345L), + eq((Map) null), + argThat(EqualsVariableMap.matches().matcher("var1", EqualsUntypedValue.matcher().value("val1")))); + + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testHandleBpmnError() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorCode", "anErrorCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_EXTERNAL_TASK_BPMN_ERROR_URL); + + verify(externalTaskService).handleBpmnError("anExternalTaskId", "aWorkerId", "anErrorCode", null, null); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testHandleBpmnErrorWithVariables() { + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorCode", "anErrorCode"); + parameters.put("errorMessage", "anErrorMessage"); + Map variables = VariablesBuilder + .create() + .variable("var1", "val1") + .variable("var2", "val2", "String") + .variable("var3", ValueType.OBJECT.getName(), "val3", "aFormat", "aRootType") + .getVariables(); + parameters.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_EXTERNAL_TASK_BPMN_ERROR_URL); + + verify(externalTaskService).handleBpmnError( + eq("anExternalTaskId"), + eq("aWorkerId"), + eq("anErrorCode"), + eq("anErrorMessage"), + argThat(EqualsVariableMap.matches() + .matcher("var1", EqualsUntypedValue.matcher().value("val1")) + .matcher("var2", EqualsPrimitiveValue.stringValue("val2")) + .matcher("var3", + EqualsObjectValue.objectValueMatcher() + .type(ValueType.OBJECT) + .serializedValue("val3") + .serializationFormat("aFormat") + .objectTypeName("aRootType")))); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testHandleBpmnErrorNonExistingTask() { + doThrow(new NotFoundException()) + .when(externalTaskService) + .handleBpmnError(any(), any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorCode", "errorCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .post(HANDLE_EXTERNAL_TASK_BPMN_ERROR_URL); + } + + @Test + public void testHandleBpmnErrorThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")) + .when(externalTaskService) + .handleBpmnError(any(), any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorCode", "errorCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_EXTERNAL_TASK_BPMN_ERROR_URL); + } + + @Test + public void testHandleBpmnErrorThrowsBadUserRequestException() { + doThrow(new BadUserRequestException("aMessage")) + .when(externalTaskService) + .handleBpmnError(any(), any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + parameters.put("errorCode", "errorCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_EXTERNAL_TASK_BPMN_ERROR_URL); + } + + + @Test + public void testSetRetries() { + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(RETRIES_EXTERNAL_TASK_URL); + + verify(externalTaskService).setRetries("anExternalTaskId", 5); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testSetRetriesNonExistingTask() { + doThrow(new NotFoundException()).when(externalTaskService).setRetries(any(String.class), anyInt()); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .put(RETRIES_EXTERNAL_TASK_URL); + } + + @Test + public void testSetRetriesThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")).when(externalTaskService).setRetries(any(String.class), anyInt()); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .put(RETRIES_EXTERNAL_TASK_URL); + } + + + + @Test + public void testSetPriority() { + Map parameters = new HashMap<>(); + parameters.put("priority", "5"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PRIORITY_EXTERNAL_TASK_URL); + + verify(externalTaskService).setPriority("anExternalTaskId", 5); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void testSetPriorityNonExistingTask() { + doThrow(new NotFoundException()).when(externalTaskService).setPriority(any(), anyLong()); + + Map parameters = new HashMap<>(); + parameters.put("priority", "5"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .put(PRIORITY_EXTERNAL_TASK_URL); + } + + @Test + public void testSetPriorityThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")).when(externalTaskService).setPriority(any(), anyLong()); + + Map parameters = new HashMap<>(); + parameters.put("priority", "5"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .put(PRIORITY_EXTERNAL_TASK_URL); + } + + @Test + public void testGetSingleExternalTask() { + when(externalTaskQueryMock.singleResult()).thenReturn(externalTaskMock); + + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("activityId", equalTo(MockProvider.EXAMPLE_ACTIVITY_ID)) + .body("activityInstanceId", equalTo(MockProvider.EXAMPLE_ACTIVITY_INSTANCE_ID)) + .body("errorMessage", equalTo(MockProvider.EXTERNAL_TASK_ERROR_MESSAGE)) + .body("executionId", equalTo(MockProvider.EXAMPLE_EXECUTION_ID)) + .body("id", equalTo(MockProvider.EXTERNAL_TASK_ID)) + .body("lockExpirationTime", equalTo(MockProvider.EXTERNAL_TASK_LOCK_EXPIRATION_TIME)) + .body("createTime", equalTo(MockProvider.EXTERNAL_TASK_CREATE_TIME)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processDefinitionKey", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("retries", equalTo(MockProvider.EXTERNAL_TASK_RETRIES)) + .body("suspended", equalTo(MockProvider.EXTERNAL_TASK_SUSPENDED)) + .body("topicName", equalTo(MockProvider.EXTERNAL_TASK_TOPIC_NAME)) + .body("workerId", equalTo(MockProvider.EXTERNAL_TASK_WORKER_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("priority", equalTo(MockProvider.EXTERNAL_TASK_PRIORITY)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .when() + .get(SINGLE_EXTERNAL_TASK_URL); + } + + @Test + public void testGetNonExistingExternalTask() { + when(externalTaskQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("External task with id anExternalTaskId does not exist")) + .when() + .get(SINGLE_EXTERNAL_TASK_URL); + } + + @Test + public void testSetRetriesForExternalTasksAsync() { + List externalTaskIds = Arrays.asList("externalTaskId1", "externalTaskId2"); + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("externalTaskIds", externalTaskIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds(externalTaskIds); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).setAsync(5); + verifyNoMoreInteractions(updateRetriesBuilder); + } + + @Test + public void testSetRetriesForExternalTasksSync() { + List externalTaskIds = Arrays.asList("externalTaskId1", "externalTaskId2"); + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("externalTaskIds", externalTaskIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds(externalTaskIds); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).setAsync(5); + verifyNoMoreInteractions(updateRetriesBuilder); + } + + @Test + public void testSetRetriesForExternalTasksAsyncByProcessInstanceIds() { + List processInstanceIds = Arrays.asList("123", "456"); + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("processInstanceIds", processInstanceIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds(processInstanceIds); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).setAsync(5); + verifyNoMoreInteractions(updateRetriesBuilder); + } + + @Test + public void testSetRetriesForExternalTasksSyncByProcessInstanceIds() { + List processInstanceIds = Arrays.asList("123", "456"); + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("processInstanceIds", processInstanceIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(RETRIES_EXTERNAL_TASK_SYNC_URL); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds(processInstanceIds); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).set(5); + verifyNoMoreInteractions(updateRetriesBuilder); + } + + @Test + public void testSetRetriesForExternalTasksWithNullExternalTaskIdsAsync() { + doThrow(BadUserRequestException.class).when(updateRetriesBuilder).setAsync(anyInt()); + + List externalTaskIds = null; + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("externalTaskIds", externalTaskIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds(externalTaskIds); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).setAsync(5); + verifyNoMoreInteractions(updateRetriesBuilder); + } + + @Test + public void testSetNegativeRetriesForExternalTasksAsync() { + doThrow(BadUserRequestException.class).when(updateRetriesBuilder).setAsync(anyInt()); + + List externalTaskIds = null; + Map parameters = new HashMap<>(); + parameters.put("retries", "-5"); + parameters.put("externalTaskIds", externalTaskIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds(externalTaskIds); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).setAsync(-5); + verifyNoMoreInteractions(updateRetriesBuilder); + } + + @Test + public void testSetNullRetriesForExternalTasks() { + List externalTaskIds = null; + Map parameters = new HashMap<>(); + parameters.put("retries", null); + parameters.put("externalTaskIds", externalTaskIds); + + // test set retries to null synchronous + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(RETRIES_EXTERNAL_TASK_SYNC_URL); + + verify(updateRetriesBuilder, never()).set(anyInt()); + + // test set retries to null asynchronous + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + verify(updateRetriesBuilder, never()).setAsync(anyInt()); + + // test set retries to null on single task + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(RETRIES_EXTERNAL_TASK_URL); + + verify(externalTaskService, never()).setRetries(anyString() ,anyInt()); + } + + @Test + public void testSetRetriesForExternalTasksAsyncWithProcessInstanceQuery() { + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + + ProcessInstanceQueryDto processInstanceQuery = new ProcessInstanceQueryDto(); + processInstanceQuery.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("processInstanceQuery", processInstanceQuery); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + ArgumentCaptor queryCapture = ArgumentCaptor.forClass(ProcessInstanceQuery.class); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(queryCapture.capture()); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).setAsync(5); + verifyNoMoreInteractions(updateRetriesBuilder); + + ProcessInstanceQueryImpl actualQuery = (ProcessInstanceQueryImpl) queryCapture.getValue(); + assertThat(actualQuery).isNotNull(); + assertThat(actualQuery.getProcessDefinitionId()).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testSetRetriesForExternalTasksAsyncWithHistoricProcessInstanceQuery() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + query.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("historicProcessInstanceQuery", query); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + ArgumentCaptor queryCapture = ArgumentCaptor.forClass(HistoricProcessInstanceQuery.class); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(queryCapture.capture()); + verify(updateRetriesBuilder).setAsync(5); + verifyNoMoreInteractions(updateRetriesBuilder); + + HistoricProcessInstanceQueryImpl actualQuery = (HistoricProcessInstanceQueryImpl) queryCapture.getValue(); + assertThat(actualQuery).isNotNull(); + assertThat(actualQuery.getProcessDefinitionId()).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testSetRetriesWithProcessInstanceQuery() { + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + + ProcessInstanceQueryDto processInstanceQuery = new ProcessInstanceQueryDto(); + processInstanceQuery.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("processInstanceQuery", processInstanceQuery); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(RETRIES_EXTERNAL_TASK_SYNC_URL); + + ArgumentCaptor queryCapture = ArgumentCaptor.forClass(ProcessInstanceQuery.class); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(queryCapture.capture()); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).set(5); + verifyNoMoreInteractions(updateRetriesBuilder); + + ProcessInstanceQueryImpl actualQuery = (ProcessInstanceQueryImpl) queryCapture.getValue(); + assertThat(actualQuery).isNotNull(); + assertThat(actualQuery.getProcessDefinitionId()).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testSetRetriesWithHistoricProcessInstanceQuery() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + query.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("historicProcessInstanceQuery", query); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(RETRIES_EXTERNAL_TASK_SYNC_URL); + + ArgumentCaptor queryCapture = ArgumentCaptor.forClass(HistoricProcessInstanceQuery.class); + + verify(externalTaskService).updateRetries(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(null); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(queryCapture.capture()); + verify(updateRetriesBuilder).set(5); + verifyNoMoreInteractions(updateRetriesBuilder); + + HistoricProcessInstanceQueryImpl actualQuery = (HistoricProcessInstanceQueryImpl) queryCapture.getValue(); + assertThat(actualQuery).isNotNull(); + assertThat(actualQuery.getProcessDefinitionId()).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testSetRetriesSyncWithExternalTaskQuery() { + when(externalTaskService.createExternalTaskQuery()).thenReturn(new ExternalTaskQueryImpl()); + + ExternalTaskQueryDto query = new ExternalTaskQueryDto(); + query.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("externalTaskQuery", query); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(RETRIES_EXTERNAL_TASK_SYNC_URL); + + ArgumentCaptor queryCapture = ArgumentCaptor.forClass(ExternalTaskQuery.class); + + verify(externalTaskService).updateRetries(); + verify(externalTaskService).createExternalTaskQuery(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(queryCapture.capture()); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).set(5); + verifyNoMoreInteractions(updateRetriesBuilder); + + ExternalTaskQueryImpl actualQuery = (ExternalTaskQueryImpl) queryCapture.getValue(); + assertThat(actualQuery).isNotNull(); + assertThat(actualQuery.getProcessDefinitionId()).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testSetRetriesAsyncWithExternalTaskQuery() { + when(externalTaskService.createExternalTaskQuery()).thenReturn(new ExternalTaskQueryImpl()); + + ExternalTaskQueryDto query = new ExternalTaskQueryDto(); + query.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Map parameters = new HashMap<>(); + parameters.put("retries", "5"); + parameters.put("externalTaskQuery", query); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RETRIES_EXTERNAL_TASKS_ASYNC_URL); + + ArgumentCaptor queryCapture = ArgumentCaptor.forClass(ExternalTaskQuery.class); + + verify(externalTaskService).updateRetries(); + verify(externalTaskService).createExternalTaskQuery(); + verifyNoMoreInteractions(externalTaskService); + + verify(updateRetriesBuilder).externalTaskIds((List) null); + verify(updateRetriesBuilder).processInstanceIds((List) null); + verify(updateRetriesBuilder).externalTaskQuery(queryCapture.capture()); + verify(updateRetriesBuilder).processInstanceQuery(null); + verify(updateRetriesBuilder).historicProcessInstanceQuery(null); + verify(updateRetriesBuilder).setAsync(5); + verifyNoMoreInteractions(updateRetriesBuilder); + + ExternalTaskQueryImpl actualQuery = (ExternalTaskQueryImpl) queryCapture.getValue(); + assertThat(actualQuery).isNotNull(); + assertThat(actualQuery.getProcessDefinitionId()).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void shouldLockExternalTask() { + + Map parameters = new HashMap<>(); + parameters.put("workerId", "workerId"); + parameters.put("lockDuration", "1000"); + + given() + .pathParam("id", MockProvider.EXTERNAL_TASK_ID) + .contentType(ContentType.JSON) + .body(parameters) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(LOCK_EXTERNAL_TASK); + + verify(externalTaskService).lock(MockProvider.EXTERNAL_TASK_ID, "workerId", 1000); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void shouldFailOnLockExternalTaskWithNegativeLockDuration() { + + doThrow(BadUserRequestException.class).when(externalTaskService).lock(anyString(), anyString(), anyLong()); + Map parameters = new HashMap<>(); + parameters.put("workerId", "workerId"); + parameters.put("lockDuration", -1); + + given() + .pathParam("id", MockProvider.EXTERNAL_TASK_ID) + .contentType(ContentType.JSON) + .body(parameters) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(LOCK_EXTERNAL_TASK); + + } + + @Test + public void shouldFailToLockNonexistentExternalTask() { + doThrow(NotFoundException.class).when(externalTaskService).lock(anyString(), anyString(), anyLong()); + + Map json = new HashMap<>(); + json.put("workerId", "workerId"); + json.put("lockDuration", 1000); + + given() + .pathParam("id", MockProvider.EXTERNAL_TASK_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .post(LOCK_EXTERNAL_TASK); + } + + @Test + public void shouldExtendLockOnExternalTask() { + + Map parameters = new HashMap<>(); + parameters.put("workerId", "workerId"); + parameters.put("newDuration", "1000"); + + validateExtendLockRequest(parameters, Status.NO_CONTENT.getStatusCode()); + verify(externalTaskService).extendLock(MockProvider.EXTERNAL_TASK_ID, "workerId", 1000); + verifyNoMoreInteractions(externalTaskService); + } + + @Test + public void shouldFailOnExtendLockOnExternalTaskWithNegativeNewDuration() { + + doThrow(BadUserRequestException.class).when(externalTaskService).extendLock(anyString(), anyString(), anyLong()); + Map parameters = new HashMap<>(); + parameters.put("workerId", "workerId"); + parameters.put("newDuration", -1); + + validateExtendLockRequest(parameters, Status.BAD_REQUEST.getStatusCode()); + } + + @Test + public void shouldFailToExtendLockOnNonexistentExternalTask() { + doThrow(NotFoundException.class).when(externalTaskService).extendLock(anyString(), anyString(), anyLong()); + + Map json = new HashMap<>(); + json.put("workerId", "workerId"); + json.put("newDuration", 1000); + + validateExtendLockRequest(json, Status.NOT_FOUND.getStatusCode()); + } + + @Test + public void shouldReturnErrorCodeWhenCompleting() { + doThrow(new ProcessEngineException("foo", 123)) + .when(externalTaskService) + .complete(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("workerId", "aWorkerId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "anExternalTaskId") + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("foo")) + .body("code", equalTo(123)) + .when() + .post(COMPLETE_EXTERNAL_TASK_URL); + } + + protected void validateExtendLockRequest(Map json, int statusCode) { + given() + .pathParam("id", MockProvider.EXTERNAL_TASK_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(statusCode) + .when() + .post(EXTEND_LOCK_ON_EXTERNAL_TASK); + } + + protected void executePost(Map parameters) { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + + .body("[0].id", equalTo(MockProvider.EXTERNAL_TASK_ID)) + .body("[0].topicName", equalTo(MockProvider.EXTERNAL_TASK_TOPIC_NAME)) + .body("[0].workerId", equalTo(MockProvider.EXTERNAL_TASK_WORKER_ID)) + .body("[0].lockExpirationTime", equalTo(MockProvider.EXTERNAL_TASK_LOCK_EXPIRATION_TIME)) + .body("[0].createTime", equalTo(MockProvider.EXTERNAL_TASK_CREATE_TIME)) + .body("[0].processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("[0].executionId", equalTo(MockProvider.EXAMPLE_EXECUTION_ID)) + .body("[0].activityId", equalTo(MockProvider.EXAMPLE_ACTIVITY_ID)) + .body("[0].activityInstanceId", equalTo(MockProvider.EXAMPLE_ACTIVITY_INSTANCE_ID)) + .body("[0].processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("[0].processDefinitionKey", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("[0].tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("[0].retries", equalTo(MockProvider.EXTERNAL_TASK_RETRIES)) + .body("[0].errorMessage", equalTo(MockProvider.EXTERNAL_TASK_ERROR_MESSAGE)) + .body("[0].priority", equalTo(MockProvider.EXTERNAL_TASK_PRIORITY)) + .body("[0].variables." + EXAMPLE_VARIABLE_INSTANCE_NAME, notNullValue()) + .body("[0].variables." + EXAMPLE_VARIABLE_INSTANCE_NAME + ".value", equalTo(EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .body("[0].variables." + EXAMPLE_VARIABLE_INSTANCE_NAME + ".type", equalTo("String")) + + .when().post(FETCH_EXTERNAL_TASK_URL); + } + + public static SortingDto create(String sortBy, String sortOrder) { + var result = new SortingDto(); + result.setSortOrder(sortOrder); + result.setSortBy(sortBy); + return result; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..292b6dd3cbb107940f80be8440728586b473a591 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskRestServiceQueryTest.java @@ -0,0 +1,1016 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.reset; + +import java.util.*; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.externaltask.ExternalTaskQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Thorben Lindhauer + * + */ +public class ExternalTaskRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String EXTERNAL_TASK_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/external-task"; + protected static final String EXTERNAL_TASK_COUNT_QUERY_URL = EXTERNAL_TASK_QUERY_URL + "/count"; + public static final long EXTERNAL_TASK_LOW_BOUND_PRIORITY = 3L; + public static final long EXTERNAL_TASK_HIGH_BOUND_PRIORITY = 4L; + + private static final String SAMPLE_VAR_NAME = "varName"; + private static final String SAMPLE_VAR_VALUE = "varValue"; + + protected ExternalTaskQuery mockQuery; + + @Before + public void setUpRuntimeData() { + mockQuery = setUpMockExternalTaskQuery(MockProvider.createMockExternalTasks()); + } + + private ExternalTaskQuery setUpMockExternalTaskQuery(List mockedTasks) { + ExternalTaskQuery sampleTaskQuery = mock(ExternalTaskQuery.class); + when(sampleTaskQuery.list()).thenReturn(mockedTasks); + when(sampleTaskQuery.count()).thenReturn((long) mockedTasks.size()); + + when(processEngine.getExternalTaskService().createExternalTaskQuery()).thenReturn(sampleTaskQuery); + + return sampleTaskQuery; + } + + @Test + public void testInvalidDateParameter() { + given().queryParams("lockExpirationBefore", "anInvalidDate") + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'lockExpirationBefore' to value 'anInvalidDate': " + + "Cannot convert value \"anInvalidDate\" to java type java.util.Date")) + .when().get(EXTERNAL_TASK_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "processInstanceId") + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(EXTERNAL_TASK_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(EXTERNAL_TASK_QUERY_URL); + } + + @Test + public void testSimpleTaskQuery() { + Response response = given() + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXTERNAL_TASK_QUERY_URL); + + Mockito.verify(mockQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one external task returned.", 1, instances.size()); + Assert.assertNotNull("The returned external task should not be null.", instances.get(0)); + + String activityId = from(content).getString("[0].activityId"); + String activityInstanceId = from(content).getString("[0].activityInstanceId"); + String errorMessage = from(content).getString("[0].errorMessage"); + String executionId = from(content).getString("[0].executionId"); + String id = from(content).getString("[0].id"); + String lockExpirationTime = from(content).getString("[0].lockExpirationTime"); + String createTime = from(content).getString("[0].createTime"); + String processDefinitionId = from(content).getString("[0].processDefinitionId"); + String processDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String processDefinitionVersionTag = from(content).getString("[0].processDefinitionVersionTag"); + String processInstanceId = from(content).getString("[0].processInstanceId"); + Integer retries = from(content).getInt("[0].retries"); + Boolean suspended = from(content).getBoolean("[0].suspended"); + String topicName = from(content).getString("[0].topicName"); + String workerId = from(content).getString("[0].workerId"); + String tenantId = from(content).getString("[0].tenantId"); + long priority = from(content).getLong("[0].priority"); + String businessKey = from(content).getString("[0].businessKey"); + + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_ID, activityId); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_INSTANCE_ID, activityInstanceId); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_ERROR_MESSAGE, errorMessage); + Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, executionId); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_ID, id); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_LOCK_EXPIRATION_TIME, lockExpirationTime); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_CREATE_TIME, createTime); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, processDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, processDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION_TAG, processDefinitionVersionTag); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, processInstanceId); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_RETRIES, retries); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_SUSPENDED, suspended); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_TOPIC_NAME, topicName); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_WORKER_ID, workerId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, tenantId); + Assert.assertEquals(MockProvider.EXTERNAL_TASK_PRIORITY, priority); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY, businessKey); + } + + @Test + public void testCompleteGETQuery() { + Map parameters = new HashMap<>(); + + parameters.put("externalTaskId", "someExternalTaskId"); + parameters.put("activityId", "someActivityId"); + parameters.put("lockExpirationBefore", withTimezone("2013-01-23T14:42:42")); + parameters.put("lockExpirationAfter", withTimezone("2013-01-23T15:52:52")); + parameters.put("topicName", "someTopic"); + parameters.put("locked", "true"); + parameters.put("notLocked", "true"); + parameters.put("executionId", "someExecutionId"); + parameters.put("processInstanceId", "someProcessInstanceId"); + parameters.put("processInstanceIdIn", "aProcessInstanceId,anotherProcessInstanceId"); + parameters.put("processDefinitionId", "someProcessDefinitionId"); + parameters.put("processDefinitionVersionTag", "someProcessDefinitionVersionTag"); + parameters.put("processDefinitionKey", "procDefKey"); + parameters.put("processDefinitionKeyIn", "procDefKey2,procDefKey3"); + parameters.put("processDefinitionName", "procDefName"); + parameters.put("processDefinitionNameLike", "procDefName%"); + parameters.put("active", "true"); + parameters.put("suspended", "true"); + parameters.put("withRetriesLeft", "true"); + parameters.put("noRetriesLeft", "true"); + parameters.put("workerId", "someWorkerId"); + parameters.put("priorityHigherThanOrEquals", "3"); + parameters.put("priorityLowerThanOrEquals", "4"); + + given() + .queryParams(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).externalTaskId("someExternalTaskId"); + verify(mockQuery).activityId("someActivityId"); + verify(mockQuery).lockExpirationBefore(DateTimeUtil.parseDate(withTimezone("2013-01-23T14:42:42"))); + verify(mockQuery).lockExpirationAfter(DateTimeUtil.parseDate(withTimezone("2013-01-23T15:52:52"))); + verify(mockQuery).topicName("someTopic"); + verify(mockQuery).locked(); + verify(mockQuery).notLocked(); + verify(mockQuery).executionId("someExecutionId"); + verify(mockQuery).processInstanceId("someProcessInstanceId"); + verify(mockQuery).processInstanceIdIn("aProcessInstanceId", "anotherProcessInstanceId"); + verify(mockQuery).processDefinitionId("someProcessDefinitionId"); + verify(mockQuery).processDefinitionKey("procDefKey"); + verify(mockQuery).processDefinitionKeyIn("procDefKey2", "procDefKey3"); + verify(mockQuery).processDefinitionName("procDefName"); + verify(mockQuery).processDefinitionNameLike("procDefName%"); + verify(mockQuery).active(); + verify(mockQuery).suspended(); + verify(mockQuery).withRetriesLeft(); + verify(mockQuery).noRetriesLeft(); + verify(mockQuery).workerId("someWorkerId"); + verify(mockQuery).priorityHigherThanOrEquals(3); + verify(mockQuery).priorityLowerThanOrEquals(4); + } + + @Test + public void testCompletePOSTQuery() { + Map parameters = new HashMap<>(); + + parameters.put("externalTaskId", "someExternalTaskId"); + parameters.put("activityId", "someActivityId"); + parameters.put("lockExpirationBefore", withTimezone("2013-01-23T14:42:42")); + parameters.put("lockExpirationAfter", withTimezone("2013-01-23T15:52:52")); + parameters.put("topicName", "someTopic"); + parameters.put("locked", "true"); + parameters.put("notLocked", "true"); + parameters.put("executionId", "someExecutionId"); + parameters.put("processInstanceId", "someProcessInstanceId"); + parameters.put("processInstanceIdIn", Arrays.asList("aProcessInstanceId", "anotherProcessInstanceId")); + parameters.put("processDefinitionId", "someProcessDefinitionId"); + parameters.put("active", "true"); + parameters.put("suspended", "true"); + parameters.put("withRetriesLeft", "true"); + parameters.put("noRetriesLeft", "true"); + parameters.put("workerId", "someWorkerId"); + parameters.put("priorityHigherThanOrEquals", "3"); + parameters.put("priorityLowerThanOrEquals", "4"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).externalTaskId("someExternalTaskId"); + verify(mockQuery).activityId("someActivityId"); + verify(mockQuery).lockExpirationBefore(DateTimeUtil.parseDate(withTimezone("2013-01-23T14:42:42"))); + verify(mockQuery).lockExpirationAfter(DateTimeUtil.parseDate(withTimezone("2013-01-23T15:52:52"))); + verify(mockQuery).topicName("someTopic"); + verify(mockQuery).locked(); + verify(mockQuery).notLocked(); + verify(mockQuery).executionId("someExecutionId"); + verify(mockQuery).processInstanceId("someProcessInstanceId"); + verify(mockQuery).processInstanceIdIn("aProcessInstanceId", "anotherProcessInstanceId"); + verify(mockQuery).processDefinitionId("someProcessDefinitionId"); + verify(mockQuery).active(); + verify(mockQuery).suspended(); + verify(mockQuery).withRetriesLeft(); + verify(mockQuery).noRetriesLeft(); + verify(mockQuery).workerId("someWorkerId"); + verify(mockQuery).priorityHigherThanOrEquals(3); + verify(mockQuery).priorityLowerThanOrEquals(4); + } + + @Test + public void testGETQuerySorting() { + // desc + InOrder inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("id", "desc", Status.OK); + inOrder.verify(mockQuery).orderById(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("lockExpirationTime", "desc", Status.OK); + inOrder.verify(mockQuery).orderByLockExpirationTime(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("processInstanceId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByProcessInstanceId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByProcessDefinitionId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("processDefinitionKey", "desc", Status.OK); + inOrder.verify(mockQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("tenantId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTenantId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("taskPriority", "desc", Status.OK); + inOrder.verify(mockQuery).orderByPriority(); + inOrder.verify(mockQuery).desc(); + // asc + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("id", "asc", Status.OK); + inOrder.verify(mockQuery).orderById(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("lockExpirationTime", "asc", Status.OK); + inOrder.verify(mockQuery).orderByLockExpirationTime(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByProcessInstanceId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByProcessDefinitionId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("processDefinitionKey", "asc", Status.OK); + inOrder.verify(mockQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("tenantId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTenantId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyGETSorting("taskPriority", "asc", Status.OK); + inOrder.verify(mockQuery).orderByPriority(); + inOrder.verify(mockQuery).asc(); + } + + protected void executeAndVerifyGETSorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(EXTERNAL_TASK_QUERY_URL); + } + + @Test + public void testPOSTQuerySorting() { + InOrder inOrder = Mockito.inOrder(mockQuery); + executeAndVerifyPOSTSorting( + OrderingBuilder.create() + .orderBy("processDefinitionKey").desc() + .orderBy("lockExpirationTime").asc() + .getJson(), + Status.OK); + + inOrder.verify(mockQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockQuery).desc(); + inOrder.verify(mockQuery).orderByLockExpirationTime(); + inOrder.verify(mockQuery).asc(); + } + + protected void executeAndVerifyPOSTSorting(List> sortingJson, Status expectedStatus) { + Map json = new HashMap<>(); + json.put("sorting", sortingJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(EXTERNAL_TASK_QUERY_URL); + } + + @Test + public void testPaginationGET() { + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + @Test + public void testPaginationPOST() { + int firstResult = 0; + int maxResults = 10; + given() + .queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + @Test + public void testGETQueryCount() { + given() + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(EXTERNAL_TASK_COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void testPOSTQueryCount() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(EXTERNAL_TASK_COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void testQueryByTenantIdListGet() { + mockQuery = setUpMockExternalTaskQuery(createMockExternalTasksTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryByTenantIdListPost() { + mockQuery = setUpMockExternalTaskQuery(createMockExternalTasksTwoTenants()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + private List createMockExternalTasksTwoTenants() { + return Arrays.asList( + MockProvider.mockExternalTask().buildExternalTask(), + MockProvider.mockExternalTask().tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).buildExternalTask()); + } + + @Test + public void testQueryByActivityIdListGet() { + mockQuery = setUpMockExternalTaskQuery(createMockExternalTasksTwoActivityIds()); + + Response response = given() + .queryParam("activityIdIn", MockProvider.EXAMPLE_ACTIVITY_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).activityIdIn(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedActivityId1 = from(content).getString("[0].activityId"); + String returnedActivityId2 = from(content).getString("[1].activityId"); + + assertThat(returnedActivityId1).isEqualTo(MockProvider.EXAMPLE_ACTIVITY_ID); + assertThat(returnedActivityId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID); + } + + @Test + public void testQueryByActivityIdListPost() { + mockQuery = setUpMockExternalTaskQuery(createMockExternalTasksTwoActivityIds()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("activityIdIn", MockProvider.EXAMPLE_ACTIVITY_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).activityIdIn(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedActivityId1 = from(content).getString("[0].activityId"); + String returnedActivityId2 = from(content).getString("[1].activityId"); + + assertThat(returnedActivityId1).isEqualTo(MockProvider.EXAMPLE_ACTIVITY_ID); + assertThat(returnedActivityId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID); + } + + private List createMockExternalTasksTwoActivityIds() { + return Arrays.asList( + MockProvider.mockExternalTask().buildExternalTask(), + MockProvider.mockExternalTask().activityId(MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID).buildExternalTask()); + } + + @Test + public void testQueryByPriorityListGet() { + mockQuery = setUpMockExternalTaskQuery(createMockedExternalTasksWithPriorities()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("priorityHigherThanOrEquals", "3"); + queryParameters.put("priorityLowerThanOrEquals", "4"); + + Response response = given() + .queryParams(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).priorityHigherThanOrEquals(EXTERNAL_TASK_LOW_BOUND_PRIORITY); + verify(mockQuery).priorityLowerThanOrEquals(EXTERNAL_TASK_HIGH_BOUND_PRIORITY); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + long prio1 = from(content).getLong("[0].priority"); + long prio2 = from(content).getLong("[1].priority"); + + assertThat(prio1).isEqualTo(EXTERNAL_TASK_LOW_BOUND_PRIORITY); + assertThat(prio2).isEqualTo(EXTERNAL_TASK_HIGH_BOUND_PRIORITY); + } + + @Test + public void testQueryByPriorityListPost() { + mockQuery = setUpMockExternalTaskQuery(createMockedExternalTasksWithPriorities()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("priorityHigherThanOrEquals", "3"); + queryParameters.put("priorityLowerThanOrEquals", "4"); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).priorityHigherThanOrEquals(EXTERNAL_TASK_LOW_BOUND_PRIORITY); + verify(mockQuery).priorityLowerThanOrEquals(EXTERNAL_TASK_HIGH_BOUND_PRIORITY); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + long prio1 = from(content).getLong("[0].priority"); + long prio2 = from(content).getLong("[1].priority"); + + assertThat(prio1).isEqualTo(EXTERNAL_TASK_LOW_BOUND_PRIORITY); + assertThat(prio2).isEqualTo(EXTERNAL_TASK_HIGH_BOUND_PRIORITY); + } + + private List createMockedExternalTasksWithPriorities() { + return Arrays.asList( + MockProvider.mockExternalTask().priority(EXTERNAL_TASK_LOW_BOUND_PRIORITY).buildExternalTask(), + MockProvider.mockExternalTask().priority(EXTERNAL_TASK_HIGH_BOUND_PRIORITY).buildExternalTask()); + } + + @Test + public void testQueryByExternalTaskIdListGet() { + mockQuery = setUpMockExternalTaskQuery(createMockExternalTasksTwoIds()); + + Response response = given() + .queryParam("externalTaskIdIn", MockProvider.EXTERNAL_TASK_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + Set expectedIds = new HashSet<>(); + Collections.addAll(expectedIds, MockProvider.EXTERNAL_TASK_ID, MockProvider.EXTERNAL_TASK_ANOTHER_ID); + verify(mockQuery).externalTaskIdIn(expectedIds); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedId1 = from(content).getString("[0].id"); + String returnedId2 = from(content).getString("[1].id"); + + assertThat(returnedId1).isEqualTo(MockProvider.EXTERNAL_TASK_ID); + assertThat(returnedId2).isEqualTo(MockProvider.EXTERNAL_TASK_ANOTHER_ID); + } + + @Test + public void testQueryByExternalTaskIdListPost() { + mockQuery = setUpMockExternalTaskQuery(createMockExternalTasksTwoIds()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("externalTaskIdIn", MockProvider.EXTERNAL_TASK_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + Set expectedIds = new HashSet<>(); + Collections.addAll(expectedIds, MockProvider.EXTERNAL_TASK_ID, MockProvider.EXTERNAL_TASK_ANOTHER_ID); + verify(mockQuery).externalTaskIdIn(expectedIds); + verify(mockQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedId1 = from(content).getString("[0].id"); + String returnedId2 = from(content).getString("[1].id"); + + assertThat(returnedId1).isEqualTo(MockProvider.EXTERNAL_TASK_ID); + assertThat(returnedId2).isEqualTo(MockProvider.EXTERNAL_TASK_ANOTHER_ID); + } + + @Test + public void testProcessVariableParameters() { + // equals + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + //equals case-insensitive + queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + + // greater than + queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).processVariableValueGreaterThan(variableName, variableValue); + + // greater than equals + queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).processVariableValueGreaterThanOrEquals(variableName, variableValue); + + // lower than + queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).processVariableValueLessThan(variableName, variableValue); + + // lower than equals + queryValue = variableName + "_lteq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).processVariableValueLessThanOrEquals(variableName, variableValue); + + // like + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).processVariableValueLike(variableName, variableValue); + reset(mockQuery); + + // like case-insensitive + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueLike(variableName, variableValue); + + // not equals + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).processVariableValueNotEquals(variableName, variableValue); + reset(mockQuery); + + // not equals case-insensitive + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testProcessVariableValueEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testProcessVariableNameEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME.toLowerCase()); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + reset(mockQuery); + + json.put("variableValuesIgnoreCase", true); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + + } + + @Test + public void testProcessVariableValueNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "neq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueNotEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testProcessVariableValueLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "like"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueLike(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testProcessVariableValueNotLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "notLike"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXTERNAL_TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueNotLike(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + private List createMockExternalTasksTwoIds() { + return Arrays.asList( + MockProvider.mockExternalTask().buildExternalTask(), + MockProvider.mockExternalTask().id(MockProvider.EXTERNAL_TASK_ANOTHER_ID).buildExternalTask()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskTopicNamesRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskTopicNamesRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..c43333bfd18aa135c717b90f0134e35459651459 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ExternalTaskTopicNamesRestServiceTest.java @@ -0,0 +1,126 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import io.restassured.response.Response; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import javax.ws.rs.core.MediaType; +import java.util.Arrays; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.junit.Assert.assertEquals; +import javax.ws.rs.core.Response.Status; +import static org.mockito.Mockito.when; + +public class ExternalTaskTopicNamesRestServiceTest extends AbstractRestServiceTest { + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String EXTERNAL_TASK_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/external-task"; + protected static final String GET_EXTERNAL_TASK_TOPIC_NAMES_URL = EXTERNAL_TASK_QUERY_URL + "/topic-names"; + + protected static final String WITH_LOCKED_TASKS = "withLockedTasks"; + protected static final String WITH_UNLOCKED_TASKS = "withUnlockedTasks"; + protected static final String WITH_RETRIES_LEFT = "withRetriesLeft"; + + @Before + public void setupMocks(){ + when(processEngine.getExternalTaskService().getTopicNames(false,false,false)).thenReturn(Arrays.asList("allTopics")); + when(processEngine.getExternalTaskService().getTopicNames(true,false,false)).thenReturn(Arrays.asList("lockedTasks")); + when(processEngine.getExternalTaskService().getTopicNames(false,true,false)).thenReturn(Arrays.asList("unlockedTasks")); + when(processEngine.getExternalTaskService().getTopicNames(false,false,true)).thenReturn(Arrays.asList("withRetriesLeft")); + } + + @Test + public void testGetTopicNames(){ + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(GET_EXTERNAL_TASK_TOPIC_NAMES_URL); + + String content = response.asString(); + List topicNames = from(content).getList(""); + + assertEquals("allTopics", topicNames.get(0)); + } + + @Test + public void testGetTopicNamesOfLockedTasks(){ + Response response = given() + .header("accept", MediaType.APPLICATION_JSON) + .param(WITH_LOCKED_TASKS, true) + .param(WITH_UNLOCKED_TASKS, false) + .param(WITH_RETRIES_LEFT, false) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(GET_EXTERNAL_TASK_TOPIC_NAMES_URL); + + String content = response.asString(); + List topicNames = from(content).getList(""); + + assertEquals("lockedTasks", topicNames.get(0)); + } + + @Test + public void testGetTopicNamesOfUnlockedTasks(){ + Response response = given() + .header("accept", MediaType.APPLICATION_JSON) + .param(WITH_LOCKED_TASKS, false) + .param(WITH_UNLOCKED_TASKS, true) + .param(WITH_RETRIES_LEFT, false) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(GET_EXTERNAL_TASK_TOPIC_NAMES_URL); + + String content = response.asString(); + List topicNames = from(content).getList(""); + + assertEquals("unlockedTasks", topicNames.get(0)); + } + + @Test + public void testGetTopicNamesOfTasksWithRetriesLeft(){ + Response response = given() + .header("accept", MediaType.APPLICATION_JSON) + .param(WITH_LOCKED_TASKS, false) + .param(WITH_UNLOCKED_TASKS, false) + .param(WITH_RETRIES_LEFT, true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(GET_EXTERNAL_TASK_TOPIC_NAMES_URL); + + String content = response.asString(); + List topicNames = from(content).getList(""); + + assertEquals("withRetriesLeft", topicNames.get(0)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/FilterRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/FilterRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..84b8ee5232af029e6b9a517dabf5d65a9a900fba --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/FilterRestServiceInteractionTest.java @@ -0,0 +1,1913 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.READ; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.FILTER; +import static org.camunda.bpm.engine.rest.dto.AbstractQueryDto.SORT_ORDER_ASC_VALUE; +import static org.camunda.bpm.engine.rest.dto.AbstractQueryDto.SORT_ORDER_DESC_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_ASSIGNEE_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_CASE_EXECUTION_ID_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_CASE_EXECUTION_VARIABLE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_CASE_INSTANCE_ID_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_CASE_INSTANCE_VARIABLE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_CREATE_TIME_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_DESCRIPTION_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_DUE_DATE_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_EXECUTION_ID_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_EXECUTION_VARIABLE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_FOLLOW_UP_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_ID_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_NAME_CASE_INSENSITIVE_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_NAME_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_PRIORITY_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_PROCESS_INSTANCE_ID_VALUE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_PROCESS_VARIABLE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_TASK_VARIABLE; +import static org.camunda.bpm.engine.rest.dto.task.TaskQueryDto.SORT_BY_TENANT_ID_VALUE; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_FILTER_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.mockFilter; +import static org.camunda.bpm.engine.rest.helper.MockProvider.mockVariableInstance; +import static org.camunda.bpm.engine.rest.helper.TaskQueryMatcher.hasName; +import static org.camunda.bpm.engine.variable.Variables.stringValue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.emptyOrNullString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.Assert.assertEquals; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.FilterService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.filter.FilterQuery; +import org.camunda.bpm.engine.impl.AuthorizationServiceImpl; +import org.camunda.bpm.engine.impl.IdentityServiceImpl; +import org.camunda.bpm.engine.impl.TaskQueryImpl; +import org.camunda.bpm.engine.impl.VariableInstanceQueryImpl; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.impl.persistence.entity.FilterEntity; +import org.camunda.bpm.engine.impl.persistence.entity.TaskEntity; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.MockTaskBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.task.TaskQuery; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +import io.restassured.response.Response; +import org.mockito.ArgumentCaptor; + +/** + * @author Sebastian Menski + */ +public class FilterRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + public static final String FILTER_URL = TEST_RESOURCE_ROOT_PATH + FilterRestService.PATH; + public static final String SINGLE_FILTER_URL = FILTER_URL + "/{id}"; + public static final String CREATE_FILTER_URL = FILTER_URL + "/create"; + public static final String EXECUTE_SINGLE_RESULT_FILTER_URL = SINGLE_FILTER_URL + "/singleResult"; + public static final String EXECUTE_LIST_FILTER_URL = SINGLE_FILTER_URL + "/list"; + public static final String EXECUTE_COUNT_FILTER_URL = SINGLE_FILTER_URL + "/count"; + + public static final TaskQuery extendingQuery = new TaskQueryImpl().taskName(MockProvider.EXAMPLE_TASK_NAME); + public static final TaskQueryDto extendingQueryDto = TaskQueryDto.fromQuery(extendingQuery); + public static final TaskQuery extendingOrQuery = new TaskQueryImpl().or().taskDescription(MockProvider.EXAMPLE_TASK_DESCRIPTION).endOr().or().taskName(MockProvider.EXAMPLE_TASK_NAME).endOr(); + public static final TaskQueryDto extendingOrQueryDto = TaskQueryDto.fromQuery(extendingOrQuery); + public static final String invalidExtendingQuery = "abc"; + + public static final String PROCESS_INSTANCE_A_ID = "processInstanceA"; + public static final String CASE_INSTANCE_A_ID = "caseInstanceA"; + public static final String EXECUTION_A_ID = "executionA"; + public static final String EXECUTION_B_ID = "executionB"; + public static final String CASE_EXECUTION_A_ID = "caseExecutionA"; + public static final String TASK_A_ID = "taskA"; + public static final String TASK_B_ID = "taskB"; + public static final String TASK_C_ID = "taskC"; + + protected FilterService filterServiceMock; + protected Filter filterMock; + + protected AuthorizationService authorizationServiceMock; + protected IdentityService identityServiceMock; + protected VariableInstanceQueryImpl variableInstanceQueryMock; + protected ProcessEngineConfiguration processEngineConfigurationMock; + + @Before + public void setUpRuntimeData() { + filterServiceMock = mock(FilterService.class); + + when(processEngine.getFilterService()).thenReturn(filterServiceMock); + + FilterQuery filterQuery = MockProvider.createMockFilterQuery(); + + when(filterServiceMock.createFilterQuery()).thenReturn(filterQuery); + + filterMock = MockProvider.createMockFilter(); + + when(filterServiceMock.newTaskFilter()).thenReturn(filterMock); + when(filterServiceMock.saveFilter(eq(filterMock))).thenReturn(filterMock); + when(filterServiceMock.getFilter(eq(EXAMPLE_FILTER_ID))).thenReturn(filterMock); + when(filterServiceMock.getFilter(eq(MockProvider.NON_EXISTING_ID))).thenReturn(null); + + List mockTasks = Collections.singletonList(new TaskEntity()); + + when(filterServiceMock.singleResult(eq(EXAMPLE_FILTER_ID))) + .thenReturn(mockTasks.get(0)); + when(filterServiceMock.singleResult(eq(EXAMPLE_FILTER_ID), any())) + .thenReturn(mockTasks.get(0)); + when(filterServiceMock.list(eq(EXAMPLE_FILTER_ID))) + .thenReturn(mockTasks); + when(filterServiceMock.list(eq(EXAMPLE_FILTER_ID), any())) + .thenReturn(mockTasks); + when(filterServiceMock.listPage(eq(EXAMPLE_FILTER_ID), anyInt(), anyInt())) + .thenReturn(mockTasks); + when(filterServiceMock.listPage(eq(EXAMPLE_FILTER_ID), any(), anyInt(), anyInt())) + .thenReturn(mockTasks); + when(filterServiceMock.count(eq(EXAMPLE_FILTER_ID))) + .thenReturn((long) 1); + when(filterServiceMock.count(eq(EXAMPLE_FILTER_ID), any())) + .thenReturn((long) 1); + + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).singleResult(eq(MockProvider.NON_EXISTING_ID)); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).singleResult(eq(MockProvider.NON_EXISTING_ID), any()); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).list(eq(MockProvider.NON_EXISTING_ID)); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).list(eq(MockProvider.NON_EXISTING_ID), any()); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).listPage(eq(MockProvider.NON_EXISTING_ID), anyInt(), anyInt()); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).listPage(eq(MockProvider.NON_EXISTING_ID), any(), anyInt(), anyInt()); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).count(eq(MockProvider.NON_EXISTING_ID)); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).count(eq(MockProvider.NON_EXISTING_ID), any()); + doThrow(new NullValueException("No filter found with given id")) + .when(filterServiceMock).deleteFilter(eq(MockProvider.NON_EXISTING_ID)); + + authorizationServiceMock = mock(AuthorizationServiceImpl.class); + identityServiceMock = mock(IdentityServiceImpl.class); + processEngineConfigurationMock = mock(ProcessEngineConfiguration.class); + + when(processEngine.getAuthorizationService()).thenReturn(authorizationServiceMock); + when(processEngine.getIdentityService()).thenReturn(identityServiceMock); + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationMock); + + TaskService taskService = processEngine.getTaskService(); + when(taskService.createTaskQuery()).thenReturn(new TaskQueryImpl()); + + variableInstanceQueryMock = mock(VariableInstanceQueryImpl.class); + when(processEngine.getRuntimeService().createVariableInstanceQuery()) + .thenReturn(variableInstanceQueryMock); + + when(variableInstanceQueryMock.variableScopeIdIn(any(String[].class))).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.variableNameIn(any(String[].class))).thenReturn(variableInstanceQueryMock); + + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + } + + @Test + public void testGetFilter() { + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_FILTER_ID)) + .when() + .get(SINGLE_FILTER_URL); + + verify(filterServiceMock).getFilter(eq(EXAMPLE_FILTER_ID)); + } + + @Test + public void testGetNonExistingFilter() { + given() + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .get(SINGLE_FILTER_URL); + + verify(filterServiceMock).getFilter(eq(MockProvider.NON_EXISTING_ID)); + } + + @Test + public void testGetFilterWithTaskQuery() { + TaskQueryImpl query = mock(TaskQueryImpl.class); + when(query.getAssignee()).thenReturn(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME); + when(query.getAssigneeLike()).thenReturn(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME); + when(query.getCaseDefinitionId()).thenReturn(MockProvider.EXAMPLE_CASE_DEFINITION_ID); + when(query.getCaseDefinitionKey()).thenReturn(MockProvider.EXAMPLE_CASE_DEFINITION_KEY); + when(query.getCaseDefinitionName()).thenReturn(MockProvider.EXAMPLE_CASE_DEFINITION_NAME); + when(query.getCaseDefinitionNameLike()).thenReturn(MockProvider.EXAMPLE_CASE_DEFINITION_NAME_LIKE); + when(query.getCaseExecutionId()).thenReturn(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + when(query.getCaseInstanceBusinessKey()).thenReturn(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + when(query.getCaseInstanceBusinessKeyLike()).thenReturn(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY_LIKE); + when(query.getCaseInstanceId()).thenReturn(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + when(query.getCandidateUser()).thenReturn(MockProvider.EXAMPLE_USER_ID); + when(query.getCandidateGroup()).thenReturn(MockProvider.EXAMPLE_GROUP_ID); + when(query.getProcessInstanceBusinessKey()).thenReturn(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + when(query.getProcessInstanceBusinessKeyLike()).thenReturn(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY_LIKE); + when(query.getProcessDefinitionKey()).thenReturn(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + when(query.getProcessDefinitionKeys()).thenReturn(new String[]{MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY}); + when(query.getProcessDefinitionId()).thenReturn(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + when(query.getExecutionId()).thenReturn(MockProvider.EXAMPLE_EXECUTION_ID); + when(query.getProcessDefinitionName()).thenReturn(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME); + when(query.getProcessDefinitionNameLike()).thenReturn(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME_LIKE); + when(query.getProcessInstanceId()).thenReturn(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + when(query.getKey()).thenReturn(MockProvider.EXAMPLE_TASK_DEFINITION_KEY); + when(query.getKeys()).thenReturn(new String[]{MockProvider.EXAMPLE_TASK_DEFINITION_KEY, MockProvider.EXAMPLE_TASK_DEFINITION_KEY}); + when(query.getKeyLike()).thenReturn(MockProvider.EXAMPLE_TASK_DEFINITION_KEY); + when(query.getDescription()).thenReturn(MockProvider.EXAMPLE_TASK_DESCRIPTION); + when(query.getDescriptionLike()).thenReturn(MockProvider.EXAMPLE_TASK_DESCRIPTION); + when(query.getInvolvedUser()).thenReturn(MockProvider.EXAMPLE_USER_ID); + when(query.getPriority()).thenReturn(1); + when(query.getMaxPriority()).thenReturn(2); + when(query.getMinPriority()).thenReturn(3); + when(query.getName()).thenReturn(MockProvider.EXAMPLE_TASK_NAME); + when(query.getNameLike()).thenReturn(MockProvider.EXAMPLE_TASK_NAME); + when(query.getOwner()).thenReturn(MockProvider.EXAMPLE_TASK_OWNER); + when(query.getParentTaskId()).thenReturn(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID); + when(query.getTenantIds()).thenReturn(MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + when(query.isWithoutDueDate()).thenReturn(false); + when(query.isWithoutTenantId()).thenReturn(true); + when(query.isAssignedInternal()).thenReturn(true); + when(query.isUnassignedInternal()).thenReturn(false); + + filterMock = MockProvider.createMockFilter(EXAMPLE_FILTER_ID, query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filterMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("query.assigneeLike", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("query.caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("query.caseDefinitionKey", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_KEY)) + .body("query.caseDefinitionName", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_NAME)) + .body("query.caseDefinitionNameLike", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_NAME_LIKE)) + .body("query.caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("query.caseInstanceBusinessKey", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY)) + .body("query.caseInstanceBusinessKeyLike", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY_LIKE)) + .body("query.caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("query.candidateUser", equalTo(MockProvider.EXAMPLE_USER_ID)) + .body("query.candidateGroup", equalTo(MockProvider.EXAMPLE_GROUP_ID)) + .body("query.processInstanceBusinessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("query.processInstanceBusinessKeyLike", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY_LIKE)) + .body("query.processDefinitionKey", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("query.processDefinitionKeyIn", hasItems(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("query.processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("query.executionId", equalTo(MockProvider.EXAMPLE_EXECUTION_ID)) + .body("query.processDefinitionName", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME)) + .body("query.processDefinitionNameLike", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME_LIKE)) + .body("query.processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("query.taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("query.taskDefinitionKeyIn", hasItems(MockProvider.EXAMPLE_TASK_DEFINITION_KEY, MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("query.taskDefinitionKeyLike", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("query.description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("query.descriptionLike", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("query.involvedUser", equalTo(MockProvider.EXAMPLE_USER_ID)) + .body("query.priority", equalTo(1)) + .body("query.maxPriority", equalTo(2)) + .body("query.minPriority", equalTo(3)) + .body("query.name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("query.nameLike", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("query.owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("query.parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("query.tenantIdIn", hasItems(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID)) + .body("query.withoutDueDate", nullValue()) + .body("query.assigned", equalTo(true)) + .body("query.unassigned", equalTo(false)) + .when() + .get(SINGLE_FILTER_URL); + + } + + @Test + public void shouldReturnWithoutDueDateForFilterWithEnabledOptionInTaskQuery() { + TaskQueryImpl query = mock(TaskQueryImpl.class); + when(query.isWithoutDueDate()).thenReturn(true); + + filterMock = MockProvider.createMockFilter(EXAMPLE_FILTER_ID, query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filterMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.withoutDueDate", equalTo(true)) + .when() + .get(SINGLE_FILTER_URL); + + } + + @Test + public void testGetFilterWithCandidateGroupQuery() { + TaskQueryImpl query = new TaskQueryImpl(); + query.taskCandidateGroup("abc"); + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.candidateGroup", equalTo("abc")) + .body("query.containsKey('candidateGroups')", is(false)) + .body("query.containsKey('includeAssignedTasks')", is(false)) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testGetFilterWithCandidateUserQuery() { + TaskQueryImpl query = new TaskQueryImpl(); + query.taskCandidateUser("abc"); + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.candidateUser", equalTo("abc")) + .body("query.containsKey('candidateGroups')", is(false)) + .body("query.containsKey('includeAssignedTasks')", is(false)) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testGetFilterWithCandidateIncludeAssignedTasks() { + TaskQueryImpl query = new TaskQueryImpl(); + query.taskCandidateUser("abc").includeAssignedTasks(); + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.candidateUser", equalTo("abc")) + .body("query.containsKey('candidateGroups')", is(false)) + .body("query.includeAssignedTasks", is(true)) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testGetFilterWithoutTenantIdQuery() { + TaskQueryImpl query = new TaskQueryImpl(); + query.withoutTenantId(); + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.withoutTenantId", is(true)) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testGetFilterWithoutSorting() { + TaskQuery query = new TaskQueryImpl(); + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.sorting", emptyOrNullString()) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testGetFilterWithSingleSorting() { + TaskQuery query = new TaskQueryImpl() + .orderByTaskName().desc(); + + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_FILTER_URL); + + // validate sorting content + String content = response.asString(); + List> sortings = from(content).getJsonObject("query.sorting"); + assertThat(sortings).hasSize(1); + assertSorting(sortings.get(0), SORT_BY_NAME_VALUE, SORT_ORDER_DESC_VALUE); + } + + @Test + public void testGetFilterWithMultipleSorting() { + TaskQuery query = new TaskQueryImpl() + .orderByDueDate().asc() + .orderByCaseExecutionId().desc(); + + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_FILTER_URL); + + // validate sorting content + String content = response.asString(); + List> sortings = from(content).getJsonObject("query.sorting"); + assertThat(sortings).hasSize(2); + assertSorting(sortings.get(0), SORT_BY_DUE_DATE_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(1), SORT_BY_CASE_EXECUTION_ID_VALUE, SORT_ORDER_DESC_VALUE); + } + + @Test + public void testGetFilterWithAllPropertiesSorting() { + TaskQuery query = new TaskQueryImpl() + .orderByProcessInstanceId().asc() + .orderByCaseInstanceId().asc() + .orderByDueDate().asc() + .orderByFollowUpDate().asc() + .orderByExecutionId().asc() + .orderByCaseExecutionId().asc() + .orderByTaskAssignee().asc() + .orderByTaskCreateTime().asc() + .orderByTaskDescription().asc() + .orderByTaskId().asc() + .orderByTaskName().asc() + .orderByTaskNameCaseInsensitive().asc() + .orderByTaskPriority().asc() + .orderByTenantId().asc(); + + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_FILTER_URL); + + // validate sorting content + String content = response.asString(); + List> sortings = from(content).getJsonObject("query.sorting"); + assertThat(sortings).hasSize(14); + assertSorting(sortings.get(0), SORT_BY_PROCESS_INSTANCE_ID_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(1), SORT_BY_CASE_INSTANCE_ID_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(2), SORT_BY_DUE_DATE_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(3), SORT_BY_FOLLOW_UP_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(4), SORT_BY_EXECUTION_ID_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(5), SORT_BY_CASE_EXECUTION_ID_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(6), SORT_BY_ASSIGNEE_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(7), SORT_BY_CREATE_TIME_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(8), SORT_BY_DESCRIPTION_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(9), SORT_BY_ID_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(10), SORT_BY_NAME_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(11), SORT_BY_NAME_CASE_INSENSITIVE_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(12), SORT_BY_PRIORITY_VALUE, SORT_ORDER_ASC_VALUE); + assertSorting(sortings.get(13), SORT_BY_TENANT_ID_VALUE, SORT_ORDER_ASC_VALUE); + } + + @Test + public void testGetFilterWithVariableTypeSorting() { + TaskQuery query = new TaskQueryImpl() + .orderByExecutionVariable("foo", ValueType.STRING).asc() + .orderByProcessVariable("foo", ValueType.STRING).asc() + .orderByTaskVariable("foo", ValueType.STRING).asc() + .orderByCaseExecutionVariable("foo", ValueType.STRING).asc() + .orderByCaseInstanceVariable("foo", ValueType.STRING).asc(); + + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_FILTER_URL); + + // validate sorting content + String content = response.asString(); + List> sortings = from(content).getJsonObject("query.sorting"); + assertThat(sortings).hasSize(5); + assertSorting(sortings.get(0), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.STRING); + assertSorting(sortings.get(1), SORT_BY_PROCESS_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.STRING); + assertSorting(sortings.get(2), SORT_BY_TASK_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.STRING); + assertSorting(sortings.get(3), SORT_BY_CASE_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.STRING); + assertSorting(sortings.get(4), SORT_BY_CASE_INSTANCE_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.STRING); + } + + @Test + public void testGetFilterWithVariableValueTypeSorting() { + TaskQuery query = new TaskQueryImpl() + .orderByExecutionVariable("foo", ValueType.STRING).asc() + .orderByExecutionVariable("foo", ValueType.INTEGER).asc() + .orderByExecutionVariable("foo", ValueType.SHORT).asc() + .orderByExecutionVariable("foo", ValueType.DATE).asc() + .orderByExecutionVariable("foo", ValueType.BOOLEAN).asc() + .orderByExecutionVariable("foo", ValueType.LONG).asc() + .orderByExecutionVariable("foo", ValueType.DOUBLE).asc(); + + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_FILTER_URL); + + // validate sorting content + String content = response.asString(); + List> sortings = from(content).getJsonObject("query.sorting"); + assertThat(sortings).hasSize(7); + assertSorting(sortings.get(0), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.STRING); + assertSorting(sortings.get(1), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.INTEGER); + assertSorting(sortings.get(2), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.SHORT); + assertSorting(sortings.get(3), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.DATE); + assertSorting(sortings.get(4), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.BOOLEAN); + assertSorting(sortings.get(5), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.LONG); + assertSorting(sortings.get(6), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.DOUBLE); + } + + @Test + public void testGetFilterWithVariableSortOrderSorting() { + TaskQuery query = new TaskQueryImpl() + .orderByExecutionVariable("foo", ValueType.STRING).asc() + .orderByExecutionVariable("foo", ValueType.STRING).desc(); + + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_FILTER_URL); + + // validate sorting content + String content = response.asString(); + List> sortings = from(content).getJsonObject("query.sorting"); + assertThat(sortings).hasSize(2); + assertSorting(sortings.get(0), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_ASC_VALUE, "foo", ValueType.STRING); + assertSorting(sortings.get(1), SORT_BY_EXECUTION_VARIABLE, SORT_ORDER_DESC_VALUE, "foo", ValueType.STRING); + } + + protected void assertSorting(Map sorting, String sortBy, String sortOrder) { + assertSorting(sorting, sortBy, sortOrder, null, null); + } + + @SuppressWarnings("unchecked") + protected void assertSorting(Map sorting, String sortBy, String sortOrder, String parametersVariable, ValueType parametersType) { + assertThat(sorting.get("sortBy")).isEqualTo(sortBy); + assertThat(sorting.get("sortOrder")).isEqualTo(sortOrder); + if (parametersVariable == null) { + assertThat(sorting.containsKey("parameters")).isFalse(); + } + else { + Map parameters = (Map) sorting.get("parameters"); + assertThat(parameters.get("variable")).isEqualTo(parametersVariable); + assertThat(parameters.get("type")).isEqualTo(VariableValueDto.toRestApiTypeName(parametersType.getName())); + } + } + + @Test + public void testGetFilterWithFollowUpBeforeOrNotExistentExpression() { + TaskQueryImpl query = new TaskQueryImpl(); + query.followUpBeforeOrNotExistentExpression("#{now()}"); + Filter filter = new FilterEntity("Task").setName("test").setQuery(query); + when(filterServiceMock.getFilter(EXAMPLE_FILTER_ID)).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("query.followUpBeforeOrNotExistentExpression", equalTo("#{now()}")) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testCreateFilter() { + Map json = toFilterRequest(MockProvider.createMockFilter()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", notNullValue()) + .when() + .post(CREATE_FILTER_URL); + + verify(filterServiceMock).newTaskFilter(); + verify(filterServiceMock).saveFilter(eq(filterMock)); + } + + @Test + public void testCreateInvalidFilter() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(CREATE_FILTER_URL); + } + + @Test + public void testUpdateFilter() { + Map json = toFilterRequest(MockProvider.createMockFilter()); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_FILTER_URL); + + verify(filterServiceMock).getFilter(eq(EXAMPLE_FILTER_ID)); + verify(filterServiceMock).saveFilter(eq(filterMock)); + } + + @Test + public void testInvalidResourceType() { + Map json = toFilterRequest(MockProvider.createMockFilter()); + json.put("resourceType", "invalid"); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(SINGLE_FILTER_URL); + } + + protected Map toFilterRequest(Filter filter) { + Map json = new HashMap<>(); + + json.put("id", filter.getId()); + json.put("name", filter.getName()); + json.put("owner", filter.getOwner()); + json.put("properties", filter.getProperties()); + json.put("resourceType", filter.getResourceType()); + + // should not use the dto classes in client-side tests + json.put("query", TaskQueryDto.fromQuery(filter.getQuery())); + + return json; + } + + @Test + public void testUpdateNonExistingFilter() { + given() + .pathParam("id", MockProvider.NON_EXISTING_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .put(SINGLE_FILTER_URL); + } + + @Test + public void testUpdateInvalidFilter() { + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(SINGLE_FILTER_URL); + } + + @Test + public void testDeleteFilter() { + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_FILTER_URL); + + verify(filterServiceMock).deleteFilter(eq(EXAMPLE_FILTER_ID)); + } + + @Test + public void testDeleteNonExistingFilter() { + given() + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .delete(SINGLE_FILTER_URL); + } + + @Test + public void testExecuteSingleResult() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testEmptySingleResult() { + when(filterServiceMock.singleResult(any(), any())).thenReturn(null); + + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testInvalidSingleResult() { + doThrow(new ProcessEngineException("More than one result found")) + .when(filterServiceMock).singleResult(any(), any()); + + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testExecuteHalSingleResult() { + given() + .header(ACCEPT_HAL_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID),isNull()); + } + + @Test + public void testEmptyHalSingleResult() { + when(filterServiceMock.singleResult(any(), any())).thenReturn(null); + + given() + .header(ACCEPT_HAL_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("_links.size()", equalTo(0)) + .body("_embedded.size()", equalTo(0)) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testInvalidHalSingleResult() { + doThrow(new ProcessEngineException("More than one result found")) + .when(filterServiceMock).singleResult(any(), any()); + + given() + .header(ACCEPT_HAL_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testExecuteSingleResultOfNonExistingFilter() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(MockProvider.NON_EXISTING_ID), isNull()); + } + + @Test + public void testExecuteSingleResultAsPost() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), any()); + } + + @Test + public void testExecuteHalSingleResultAsPost() { + given() + .header(ACCEPT_HAL_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), any()); + } + + @Test + public void testExecuteSingleResultInvalidWithExtendingQuery() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(invalidExtendingQuery) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(EXECUTE_SINGLE_RESULT_FILTER_URL); + } + + @Test + public void testExecuteSingleResultWithExtendingQuery() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(extendingQueryDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), + argThat(hasName(MockProvider.EXAMPLE_TASK_NAME))); + } + + @Test + public void testExecuteSingleResultWithExtendingOrQuery() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(extendingOrQueryDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_SINGLE_RESULT_FILTER_URL); + + ArgumentCaptor argument = ArgumentCaptor.forClass(TaskQueryImpl.class); + verify(filterServiceMock).singleResult(eq(EXAMPLE_FILTER_ID), argument.capture()); + assertEquals(MockProvider.EXAMPLE_TASK_DESCRIPTION, argument.getValue().getQueries().get(1).getDescription()); + assertEquals(MockProvider.EXAMPLE_TASK_NAME, argument.getValue().getQueries().get(2).getName()); + } + + @Test + public void testExecuteList() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(1)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testEmptyList() { + when(filterServiceMock.list(any(), any())).thenReturn(Collections.emptyList()); + + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(0)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testExecuteHalList() { + given() + .header(ACCEPT_HAL_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testEmptyHalList() { + when(filterServiceMock.list(any(), any())).thenReturn(Collections.emptyList()); + when(filterServiceMock.count(any(), any())).thenReturn(0l); + + given() + .header(ACCEPT_HAL_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("_links.size()", equalTo(0)) + .body("_embedded.size()", equalTo(0)) + .body("count", equalTo(0)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testExecuteListOfNonExistingFilter() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(MockProvider.NON_EXISTING_ID), isNull()); + } + + @Test + public void testExecuteListWithPagination() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .queryParams("firstResult", 1) + .queryParams("maxResults", 2) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(1)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).listPage(eq(EXAMPLE_FILTER_ID), isNull(), eq(1), eq(2)); + } + + @Test + public void testExecuteListAsPost() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(1)) + .when() + .post(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), any()); + } + + @Test + public void testExecuteHalListAsPost() { + given() + .header(ACCEPT_HAL_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .post(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), any()); + } + + @Test + public void testExecuteListAsPostWithPagination() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .queryParams("firstResult", 1) + .queryParams("maxResults", 2) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(1)) + .when() + .post(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).listPage(eq(EXAMPLE_FILTER_ID), isNull(), eq(1), eq(2)); + } + + @Test + public void testExecuteListWithExtendingQuery() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(extendingQueryDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(1)) + .when() + .post(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).list(eq(EXAMPLE_FILTER_ID), argThat(hasName(MockProvider.EXAMPLE_TASK_NAME))); + } + + @Test + public void testExecuteListWithExtendingQueryWithPagination() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .queryParams("firstResult", 1) + .queryParams("maxResults", 2) + .contentType(POST_JSON_CONTENT_TYPE) + .body(extendingQueryDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(1)) + .when() + .post(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock).listPage(eq(EXAMPLE_FILTER_ID), argThat(hasName(MockProvider.EXAMPLE_TASK_NAME)), eq(1), eq(2)); + } + + @Test + public void testExecuteListWithInvalidExtendingQuery() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(invalidExtendingQuery) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(EXECUTE_LIST_FILTER_URL); + } + + @Test + public void testExecuteCount() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(EXECUTE_COUNT_FILTER_URL); + + verify(filterServiceMock).count(eq(EXAMPLE_FILTER_ID), isNull()); + } + + @Test + public void testExecuteCountOfNonExistingFilter() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .get(EXECUTE_COUNT_FILTER_URL); + + verify(filterServiceMock).count(MockProvider.NON_EXISTING_ID, null); + } + + @Test + public void testExecuteCountAsPost() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .post(EXECUTE_COUNT_FILTER_URL); + + verify(filterServiceMock).count(eq(EXAMPLE_FILTER_ID), any()); + } + + @Test + public void testExecuteCountWithExtendingQuery() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(extendingQueryDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .post(EXECUTE_COUNT_FILTER_URL); + + verify(filterServiceMock).count(eq(EXAMPLE_FILTER_ID), argThat(hasName(MockProvider.EXAMPLE_TASK_NAME))); + } + + @Test + public void testExecuteCountWithInvalidExtendingQuery() { + given() + .header(ACCEPT_JSON_HEADER) + .pathParam("id", EXAMPLE_FILTER_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(invalidExtendingQuery) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(EXECUTE_COUNT_FILTER_URL); + } + + + @Test + public void testAnonymousFilterOptions() { + String fullFilterUrl = "http://localhost:" + PORT + FILTER_URL; + + // anonymity means the identityService returns a null authentication, so no need to mock here + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links.size()", is(3)) + + .body("links[0].href", equalTo(fullFilterUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullFilterUrl + "/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullFilterUrl + "/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(FILTER_URL); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testRestrictedFilterOptions() { + String fullFilterUrl = "http://localhost:" + PORT + FILTER_URL; + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, FILTER, ANY)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links.size()", is(2)) + + .body("links[0].href", equalTo(fullFilterUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullFilterUrl + "/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .when() + .options(FILTER_URL); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testFilterOptionsWithDisabledAuthorization() { + String fullFilterUrl = "http://localhost:" + PORT + FILTER_URL; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links.size()", is(3)) + + .body("links[0].href", equalTo(fullFilterUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullFilterUrl + "/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullFilterUrl + "/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(FILTER_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testAnonymousFilterResourceOptions() { + String fullFilterUrl = "http://localhost:" + PORT + FILTER_URL + "/" + EXAMPLE_FILTER_ID; + + // anonymity means the identityService returns a null authentication, so no need to mock here + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links.size()", is(9)) + + .body("links[0].href", equalTo(fullFilterUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullFilterUrl + "/singleResult")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("singleResult")) + + .body("links[2].href", equalTo(fullFilterUrl + "/singleResult")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("singleResult")) + + .body("links[3].href", equalTo(fullFilterUrl + "/list")) + .body("links[3].method", equalTo(HttpMethod.GET)) + .body("links[3].rel", equalTo("list")) + + .body("links[4].href", equalTo(fullFilterUrl + "/list")) + .body("links[4].method", equalTo(HttpMethod.POST)) + .body("links[4].rel", equalTo("list")) + + .body("links[5].href", equalTo(fullFilterUrl + "/count")) + .body("links[5].method", equalTo(HttpMethod.GET)) + .body("links[5].rel", equalTo("count")) + + .body("links[6].href", equalTo(fullFilterUrl + "/count")) + .body("links[6].method", equalTo(HttpMethod.POST)) + .body("links[6].rel", equalTo("count")) + + .body("links[7].href", equalTo(fullFilterUrl)) + .body("links[7].method", equalTo(HttpMethod.DELETE)) + .body("links[7].rel", equalTo("delete")) + + .body("links[8].href", equalTo(fullFilterUrl)) + .body("links[8].method", equalTo(HttpMethod.PUT)) + .body("links[8].rel", equalTo("update")) + + .when() + .options(SINGLE_FILTER_URL); + + verify(identityServiceMock, times(3)).getCurrentAuthentication(); + + } + + @Test + public void testFilterResourceOptionsUnauthorized() { + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, READ, FILTER, EXAMPLE_FILTER_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, FILTER, EXAMPLE_FILTER_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, FILTER, EXAMPLE_FILTER_ID)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links.size()", is(0)) + + .when() + .options(SINGLE_FILTER_URL); + + verify(identityServiceMock, times(3)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, READ, FILTER, EXAMPLE_FILTER_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, FILTER, EXAMPLE_FILTER_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, FILTER, EXAMPLE_FILTER_ID); + + } + + @Test + public void testFilterResourceOptionsUpdateUnauthorized() { + String fullFilterUrl = "http://localhost:" + PORT + FILTER_URL + "/" + EXAMPLE_FILTER_ID; + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, READ, FILTER, EXAMPLE_FILTER_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, FILTER, EXAMPLE_FILTER_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, FILTER, EXAMPLE_FILTER_ID)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links.size()", is(8)) + + .body("links[0].href", equalTo(fullFilterUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullFilterUrl + "/singleResult")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("singleResult")) + + .body("links[2].href", equalTo(fullFilterUrl + "/singleResult")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("singleResult")) + + .body("links[3].href", equalTo(fullFilterUrl + "/list")) + .body("links[3].method", equalTo(HttpMethod.GET)) + .body("links[3].rel", equalTo("list")) + + .body("links[4].href", equalTo(fullFilterUrl + "/list")) + .body("links[4].method", equalTo(HttpMethod.POST)) + .body("links[4].rel", equalTo("list")) + + .body("links[5].href", equalTo(fullFilterUrl + "/count")) + .body("links[5].method", equalTo(HttpMethod.GET)) + .body("links[5].rel", equalTo("count")) + + .body("links[6].href", equalTo(fullFilterUrl + "/count")) + .body("links[6].method", equalTo(HttpMethod.POST)) + .body("links[6].rel", equalTo("count")) + + .body("links[7].href", equalTo(fullFilterUrl)) + .body("links[7].method", equalTo(HttpMethod.DELETE)) + .body("links[7].rel", equalTo("delete")) + + .when() + .options(SINGLE_FILTER_URL); + + verify(identityServiceMock, times(3)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, READ, FILTER, EXAMPLE_FILTER_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, FILTER, EXAMPLE_FILTER_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, FILTER, EXAMPLE_FILTER_ID); + + } + + @Test + public void testFilterResourceOptionsWithAuthorizationDisabled() { + String fullFilterUrl = "http://localhost:" + PORT + FILTER_URL + "/" + EXAMPLE_FILTER_ID; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links.size()", is(9)) + + .body("links[0].href", equalTo(fullFilterUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullFilterUrl + "/singleResult")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("singleResult")) + + .body("links[2].href", equalTo(fullFilterUrl + "/singleResult")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("singleResult")) + + .body("links[3].href", equalTo(fullFilterUrl + "/list")) + .body("links[3].method", equalTo(HttpMethod.GET)) + .body("links[3].rel", equalTo("list")) + + .body("links[4].href", equalTo(fullFilterUrl + "/list")) + .body("links[4].method", equalTo(HttpMethod.POST)) + .body("links[4].rel", equalTo("list")) + + .body("links[5].href", equalTo(fullFilterUrl + "/count")) + .body("links[5].method", equalTo(HttpMethod.GET)) + .body("links[5].rel", equalTo("count")) + + .body("links[6].href", equalTo(fullFilterUrl + "/count")) + .body("links[6].method", equalTo(HttpMethod.POST)) + .body("links[6].rel", equalTo("count")) + + .body("links[7].href", equalTo(fullFilterUrl)) + .body("links[7].method", equalTo(HttpMethod.DELETE)) + .body("links[7].rel", equalTo("delete")) + + .body("links[8].href", equalTo(fullFilterUrl)) + .body("links[8].method", equalTo(HttpMethod.PUT)) + .body("links[8].rel", equalTo("update")) + + .when() + .options(SINGLE_FILTER_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testHalTaskQueryWithWrongFormatVariablesProperties() { + // mock properties with variable name list in wrong format + Map properties = new HashMap<>(); + properties.put("variables", "foo"); + Filter filter = mockFilter().properties(properties).build(); + when(filterServiceMock.getFilter(eq(EXAMPLE_FILTER_ID))).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .header(ACCEPT_HAL_HEADER) + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock, times(1)).getFilter(eq(EXAMPLE_FILTER_ID)); + verify(variableInstanceQueryMock, never()).variableScopeIdIn(any()); + verify(variableInstanceQueryMock, never()).variableNameIn(any()); + verify(variableInstanceQueryMock, never()).list(); + + } + + @Test + public void testHalTaskQueryWithEmptyVariablesProperties() { + // mock properties with variable name list in wrong format + Map properties = new HashMap<>(); + properties.put("variables", Collections.emptyList()); + Filter filter = mockFilter().properties(properties).build(); + when(filterServiceMock.getFilter(eq(EXAMPLE_FILTER_ID))).thenReturn(filter); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .header(ACCEPT_HAL_HEADER) + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("_embedded", equalTo(null)) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock, times(1)).getFilter(eq(EXAMPLE_FILTER_ID)); + verify(variableInstanceQueryMock, never()).variableScopeIdIn(any()); + verify(variableInstanceQueryMock, never()).variableNameIn(any()); + verify(variableInstanceQueryMock, never()).list(); + } + + @Test + public void testHalTaskQueryWithVariableNotSetOnTask() { + // mock filter with variable names set + mockFilterWithVariableNames(); + + // mock resulting task + Task task = createTaskMock(TASK_A_ID, PROCESS_INSTANCE_A_ID, EXECUTION_A_ID, null, null); + when(filterServiceMock.singleResult(eq(EXAMPLE_FILTER_ID), any())).thenReturn(task); + + // mock variable instances + List variableInstances = Arrays.asList( + createExecutionVariableInstanceMock("foo", stringValue("execution"), EXECUTION_B_ID), + createExecutionVariableInstanceMock("execution", stringValue("bar"), EXECUTION_B_ID), + createTaskVariableInstanceMock("foo", stringValue("task"), TASK_B_ID), + createTaskVariableInstanceMock("task", stringValue("bar"), TASK_B_ID) + ); + when(variableInstanceQueryMock.unlimitedList()).thenReturn(variableInstances); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .header(ACCEPT_HAL_HEADER) + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("_embedded.containsKey('variable')", is(true)) + .body("_embedded.variable.size()", equalTo(0)) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock, times(1)).getFilter(eq(EXAMPLE_FILTER_ID)); + verify(variableInstanceQueryMock, times(1)).variableScopeIdIn(any(String[].class)); + verify(variableInstanceQueryMock).variableScopeIdIn(TASK_A_ID, EXECUTION_A_ID, PROCESS_INSTANCE_A_ID); + verify(variableInstanceQueryMock, times(1)).variableNameIn(any(String[].class)); + verify(variableInstanceQueryMock).variableNameIn("foo", "bar"); + verify(variableInstanceQueryMock, times(1)).unlimitedList(); + } + + @Test + public void testHalTaskQueryWithAdditionalVariables() { + // mock filter with variable names set + mockFilterWithVariableNames(); + + // mock resulting task + Task task = createTaskMock(TASK_A_ID, PROCESS_INSTANCE_A_ID, EXECUTION_A_ID, CASE_INSTANCE_A_ID, CASE_EXECUTION_A_ID); + when(filterServiceMock.singleResult(eq(EXAMPLE_FILTER_ID), any())).thenReturn(task); + + // mock variable instances + List variableInstances = Arrays.asList( + createProcessInstanceVariableInstanceMock("foo", stringValue("processInstance"), PROCESS_INSTANCE_A_ID), + createProcessInstanceVariableInstanceMock("processInstance", stringValue("bar"), PROCESS_INSTANCE_A_ID), + createExecutionVariableInstanceMock("foo", stringValue("execution"), EXECUTION_A_ID), + createExecutionVariableInstanceMock("execution", stringValue("bar"), EXECUTION_A_ID), + createTaskVariableInstanceMock("foo", stringValue("task"), TASK_A_ID), + createTaskVariableInstanceMock("task", stringValue("bar"), TASK_A_ID), + createCaseInstanceVariableInstanceMock("foo", stringValue("caseInstance"), CASE_INSTANCE_A_ID), + createCaseInstanceVariableInstanceMock("caseInstance", stringValue("bar"), CASE_INSTANCE_A_ID), + createCaseExecutionVariableInstanceMock("foo", stringValue("caseExecution"), CASE_EXECUTION_A_ID), + createCaseExecutionVariableInstanceMock("caseExecution", stringValue("bar"), CASE_EXECUTION_A_ID) + ); + when(variableInstanceQueryMock.unlimitedList()).thenReturn(variableInstances); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .header(ACCEPT_HAL_HEADER) + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("_embedded.containsKey('variable')", is(true)) + .body("_embedded.variable.size()", equalTo(6)) + .when() + .get(EXECUTE_SINGLE_RESULT_FILTER_URL); + + verify(filterServiceMock, times(1)).getFilter(eq(EXAMPLE_FILTER_ID)); + verify(variableInstanceQueryMock, times(1)).variableScopeIdIn(any(String[].class)); + verify(variableInstanceQueryMock).variableScopeIdIn(TASK_A_ID, EXECUTION_A_ID, PROCESS_INSTANCE_A_ID, CASE_EXECUTION_A_ID, CASE_INSTANCE_A_ID); + verify(variableInstanceQueryMock, times(1)).variableNameIn(any(String[].class)); + verify(variableInstanceQueryMock).variableNameIn("foo", "bar"); + verify(variableInstanceQueryMock, times(1)).unlimitedList(); + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + verify(variableInstanceQueryMock, times(1)).disableCustomObjectDeserialization(); + + String content = response.asString(); + List> variables = from(content).getJsonObject("_embedded.variable"); + + // task variable 'foo' + verifyTaskVariableValue(variables.get(0), "foo", "task", TASK_A_ID); + // task variable 'task' + verifyTaskVariableValue(variables.get(1), "task", "bar", TASK_A_ID); + // execution variable 'execution' + verifyExecutionVariableValue(variables.get(2), "execution", "bar", EXECUTION_A_ID); + // process instance variable 'processInstance' + verifyProcessInstanceVariableValue(variables.get(3), "processInstance", "bar", PROCESS_INSTANCE_A_ID); + // caseExecution variable 'caseExecution' + verifyCaseExecutionVariableValue(variables.get(4), "caseExecution", "bar", CASE_EXECUTION_A_ID); + // case instance variable 'caseInstance' + verifyCaseInstanceVariableValue(variables.get(5), "caseInstance", "bar", CASE_INSTANCE_A_ID); + } + + @Test + public void testHalTaskListQueryWithAdditionalVariables() { + // mock filter with variable names set + mockFilterWithVariableNames(); + + // mock resulting task + List tasks = Arrays.asList( + createTaskMock(TASK_A_ID, PROCESS_INSTANCE_A_ID, EXECUTION_A_ID, null, null), + createTaskMock(TASK_B_ID, PROCESS_INSTANCE_A_ID, EXECUTION_B_ID, null, null), + createTaskMock(TASK_C_ID, null, null, CASE_INSTANCE_A_ID, CASE_EXECUTION_A_ID) + ); + when(filterServiceMock.list(eq(EXAMPLE_FILTER_ID), Mockito.>any())).thenReturn(tasks); + + // mock variable instances + List variableInstances = Arrays.asList( + createProcessInstanceVariableInstanceMock("foo", stringValue(PROCESS_INSTANCE_A_ID), PROCESS_INSTANCE_A_ID), + createProcessInstanceVariableInstanceMock(PROCESS_INSTANCE_A_ID, stringValue("bar"), PROCESS_INSTANCE_A_ID), + createExecutionVariableInstanceMock("foo", stringValue(EXECUTION_A_ID), EXECUTION_A_ID), + createExecutionVariableInstanceMock(EXECUTION_A_ID, stringValue("bar"), EXECUTION_A_ID), + createExecutionVariableInstanceMock("foo", stringValue(EXECUTION_B_ID), EXECUTION_B_ID), + createExecutionVariableInstanceMock(EXECUTION_B_ID, stringValue("bar"), EXECUTION_B_ID), + createTaskVariableInstanceMock("foo", stringValue(TASK_A_ID), TASK_A_ID), + createTaskVariableInstanceMock(TASK_A_ID, stringValue("bar"), TASK_A_ID), + createTaskVariableInstanceMock("foo", stringValue(TASK_B_ID), TASK_B_ID), + createTaskVariableInstanceMock(TASK_B_ID, stringValue("bar"), TASK_B_ID), + createTaskVariableInstanceMock("foo", stringValue(TASK_C_ID), TASK_C_ID), + createTaskVariableInstanceMock(TASK_C_ID, stringValue("bar"), TASK_C_ID), + createCaseInstanceVariableInstanceMock("foo", stringValue(CASE_INSTANCE_A_ID), CASE_INSTANCE_A_ID), + createCaseInstanceVariableInstanceMock(CASE_INSTANCE_A_ID, stringValue("bar"), CASE_INSTANCE_A_ID), + createCaseExecutionVariableInstanceMock("foo", stringValue(CASE_EXECUTION_A_ID), CASE_EXECUTION_A_ID), + createCaseExecutionVariableInstanceMock(CASE_EXECUTION_A_ID, stringValue("bar"), CASE_EXECUTION_A_ID) + ); + when(variableInstanceQueryMock.unlimitedList()).thenReturn(variableInstances); + + Response response = given() + .pathParam("id", EXAMPLE_FILTER_ID) + .header(ACCEPT_HAL_HEADER) + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("_embedded.task.size()", equalTo(3)) + .body("_embedded.task.any { it._embedded.containsKey('variable') }", is(true)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + verify(filterServiceMock, times(1)).getFilter(eq(EXAMPLE_FILTER_ID)); + verify(variableInstanceQueryMock, times(1)).variableScopeIdIn(any(String[].class)); + verify(variableInstanceQueryMock).variableScopeIdIn(TASK_A_ID, EXECUTION_A_ID, PROCESS_INSTANCE_A_ID, TASK_B_ID, EXECUTION_B_ID, TASK_C_ID, CASE_EXECUTION_A_ID, CASE_INSTANCE_A_ID); + verify(variableInstanceQueryMock, times(1)).variableNameIn(any(String[].class)); + verify(variableInstanceQueryMock).variableNameIn("foo", "bar"); + verify(variableInstanceQueryMock, times(1)).unlimitedList(); + + String content = response.asString(); + List> taskList = from(content).getList("_embedded.task"); + + // task A + List> variables = getEmbeddedTaskVariables(taskList.get(0)); + assertThat(variables).hasSize(4); + + // task variable 'foo' + verifyTaskVariableValue(variables.get(0), "foo", TASK_A_ID, TASK_A_ID); + // task variable 'taskA' + verifyTaskVariableValue(variables.get(1), TASK_A_ID, "bar", TASK_A_ID); + // execution variable 'executionA' + verifyExecutionVariableValue(variables.get(2), EXECUTION_A_ID, "bar", EXECUTION_A_ID); + // process instance variable 'processInstanceA' + verifyProcessInstanceVariableValue(variables.get(3), PROCESS_INSTANCE_A_ID, "bar", PROCESS_INSTANCE_A_ID); + + // task B + variables = getEmbeddedTaskVariables(taskList.get(1)); + assertThat(variables).hasSize(4); + + // task variable 'foo' + verifyTaskVariableValue(variables.get(0), "foo", TASK_B_ID, TASK_B_ID); + // task variable 'taskA' + verifyTaskVariableValue(variables.get(1), TASK_B_ID, "bar", TASK_B_ID); + // execution variable 'executionA' + verifyExecutionVariableValue(variables.get(2), EXECUTION_B_ID, "bar", EXECUTION_B_ID); + // process instance variable 'processInstanceA' + verifyProcessInstanceVariableValue(variables.get(3), PROCESS_INSTANCE_A_ID, "bar", PROCESS_INSTANCE_A_ID); + + // task C + variables = getEmbeddedTaskVariables(taskList.get(2)); + assertThat(variables).hasSize(4); + + // task variable 'foo' + verifyTaskVariableValue(variables.get(0), "foo", TASK_C_ID, TASK_C_ID); + // task variable 'taskC' + verifyTaskVariableValue(variables.get(1), TASK_C_ID, "bar", TASK_C_ID); + // case execution variable 'caseExecutionA' + verifyCaseExecutionVariableValue(variables.get(2), CASE_EXECUTION_A_ID, "bar", CASE_EXECUTION_A_ID); + // case instance variable 'caseInstanceA' + verifyCaseInstanceVariableValue(variables.get(3), CASE_INSTANCE_A_ID, "bar", CASE_INSTANCE_A_ID); + + } + + @Test + public void testHalTaskListCount() { + // mock resulting task + List tasks = Arrays.asList( + createTaskMock(TASK_A_ID, PROCESS_INSTANCE_A_ID, EXECUTION_A_ID, null, null), + createTaskMock(TASK_B_ID, PROCESS_INSTANCE_A_ID, EXECUTION_A_ID, null, null), + createTaskMock(TASK_C_ID, PROCESS_INSTANCE_A_ID, EXECUTION_B_ID, null, null) + ); + when(filterServiceMock.list(eq(EXAMPLE_FILTER_ID), Mockito.>any())).thenReturn(tasks); + when(filterServiceMock.listPage(eq(EXAMPLE_FILTER_ID), Mockito.>any(), eq(0), eq(2))).thenReturn(tasks.subList(0, 2)); + when(filterServiceMock.listPage(eq(EXAMPLE_FILTER_ID), any(), eq(5), eq(2))).thenReturn(Collections.emptyList()); + when(filterServiceMock.count(eq(EXAMPLE_FILTER_ID), any())).thenReturn((long) tasks.size()); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .header(ACCEPT_HAL_HEADER) + .then().expect() + .body("_embedded.task.size()", equalTo(3)) + .body("count", equalTo(3)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .queryParam("firstResult", 0) + .queryParam("maxResults", 2) + .header(ACCEPT_HAL_HEADER) + .then().expect() + .body("_embedded.task.size()", equalTo(2)) + .body("count", equalTo(3)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + + given() + .pathParam("id", EXAMPLE_FILTER_ID) + .queryParam("firstResult", 5) + .queryParam("maxResults", 2) + .header(ACCEPT_HAL_HEADER) + .then().expect() + .body("_embedded.containsKey('task')", is(false)) + .body("count", equalTo(3)) + .when() + .get(EXECUTE_LIST_FILTER_URL); + } + + @SuppressWarnings("unchecked") + protected List> getEmbeddedTaskVariables(Map task) { + Map embedded = (Map) task.get("_embedded"); + assertThat(embedded).isNotNull(); + return (List>) embedded.get("variable"); + } + + protected Filter mockFilterWithVariableNames() { + // mock properties with variable name list (names are ignored but variable names list must not be empty) + List> variables = new ArrayList<>(); + Map foo = new HashMap<>(); + foo.put("name", "foo"); + foo.put("label", "Foo"); + variables.add(foo); + Map bar = new HashMap<>(); + bar.put("name", "bar"); + bar.put("label", "Bar"); + variables.add(bar); + + Map properties = new HashMap<>(); + properties.put("variables", variables); + + Filter filter = mockFilter().properties(properties).build(); + when(filterServiceMock.getFilter(eq(EXAMPLE_FILTER_ID))).thenReturn(filter); + + return filter; + } + + protected Task createTaskMock(String taskId, String processInstanceId, String executionId, String caseInstanceId, String caseExecutionId) { + return new MockTaskBuilder() + .id(taskId) + .processInstanceId(processInstanceId) + .executionId(executionId) + .caseInstanceId(caseInstanceId) + .caseExecutionId(caseExecutionId) + .build(); + } + + protected VariableInstance createTaskVariableInstanceMock(String name, TypedValue value, String taskId) { + return createVariableInstanceMock(name, value, taskId, null, null, null, null); + } + + protected VariableInstance createExecutionVariableInstanceMock(String name, TypedValue value, String executionId) { + return createVariableInstanceMock(name, value, null, executionId, null, null, null); + } + + protected VariableInstance createProcessInstanceVariableInstanceMock(String name, TypedValue value, String processInstanceId) { + return createVariableInstanceMock(name, value, null, processInstanceId, processInstanceId, null, null); + } + + protected VariableInstance createCaseExecutionVariableInstanceMock(String name, TypedValue value, String caseExecutionId) { + return createVariableInstanceMock(name, value, null, null, null, caseExecutionId, null); + } + + protected VariableInstance createCaseInstanceVariableInstanceMock(String name, TypedValue value, String caseInstanceId) { + return createVariableInstanceMock(name, value, null, null, null, caseInstanceId, caseInstanceId); + } + + protected VariableInstance createVariableInstanceMock(String name, TypedValue value, String taskId, String executionId, String processInstanceId, String caseExecutionId, String caseInstanceId) { + return mockVariableInstance().name(name).typedValue(value).taskId(taskId) + .executionId(executionId).processInstanceId(processInstanceId).caseExecutionId(caseExecutionId).caseInstanceId(caseInstanceId) + .buildEntity(); + } + + protected void verifyTaskVariableValue(Map variable, String name, String value, String taskId) { + verifyVariableValue(variable, name, value, TaskRestService.PATH, taskId, "localVariables"); + } + + protected void verifyExecutionVariableValue(Map variable, String name, String value, String executionId) { + verifyVariableValue(variable, name, value, ExecutionRestService.PATH, executionId, "localVariables"); + } + + protected void verifyCaseExecutionVariableValue(Map variable, String name, String value, String caseExecutionId) { + verifyVariableValue(variable, name, value, CaseExecutionRestService.PATH, caseExecutionId, "localVariables"); + } + + protected void verifyProcessInstanceVariableValue(Map variable, String name, String value, String processInstanceId) { + verifyVariableValue(variable, name, value, ProcessInstanceRestService.PATH, processInstanceId, "variables"); + } + + protected void verifyCaseInstanceVariableValue(Map variable, String name, String value, String caseInstanceId) { + verifyVariableValue(variable, name, value, CaseInstanceRestService.PATH, caseInstanceId, "variables"); + } + + @SuppressWarnings("unchecked") + protected void verifyVariableValue(Map variable, String name, String value, String scopeResourcePath, String scopeId, String variablesName) { + assertThat(variable.get("name")).isEqualTo(name); + assertThat(variable.get("value")).isEqualTo(value); + assertThat(variable.get("type")).isEqualTo("String"); + assertThat(variable.get("valueInfo")).isEqualTo(Collections.emptyMap()); + assertThat(variable.get("_embedded")).isNull(); + Map> links = (Map>) variable.get("_links"); + assertThat(links).hasSize(1); + assertThat(links.get("self")).hasSize(1); + assertThat(links.get("self").get("href")).isEqualTo(scopeResourcePath + "/" + scopeId + "/" + variablesName + "/" + name); + } + + protected void verifyNoAuthorizationCheckPerformed() { + verify(identityServiceMock, times(0)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(0)).isUserAuthorized(any(), any(), any(), any()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/FilterRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/FilterRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..62942342d3c4bac5d6f400210c0db1aac49ce7cc --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/FilterRestServiceQueryTest.java @@ -0,0 +1,379 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static javax.ws.rs.core.Response.Status; +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.FilterService; +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.filter.FilterQuery; +import org.camunda.bpm.engine.impl.AbstractQuery; +import org.camunda.bpm.engine.rest.dto.runtime.FilterQueryDto; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import io.restassured.response.Response; + +/** + * @author Sebastian Menski + */ +public class FilterRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String FILTER_QUERY_URL = TEST_RESOURCE_ROOT_PATH + FilterRestService.PATH; + protected static final String SINGLE_FILTER_URL = FILTER_QUERY_URL + "/{id}"; + protected static final String FILTER_COUNT_QUERY_URL = FILTER_QUERY_URL + "/count"; + + protected FilterQuery mockedQuery; + protected Filter mockedFilter; + protected int mockedFilterItemCount; + protected Filter anotherMockedFilter; + protected int anotherMockedFilterItemCount; + + @Before + public void setUpRuntimeData() { + mockedQuery = MockProvider.createMockFilterQuery(); + mockedFilter = MockProvider.createMockFilter(MockProvider.EXAMPLE_FILTER_ID); + mockedFilterItemCount = 13; + anotherMockedFilter = MockProvider.createMockFilter(MockProvider.ANOTHER_EXAMPLE_FILTER_ID); + anotherMockedFilterItemCount = 42; + + FilterService filterService = processEngine.getFilterService(); + + when(filterService.createFilterQuery()).thenReturn(mockedQuery); + when(filterService.getFilter(eq(MockProvider.EXAMPLE_FILTER_ID))).thenReturn(mockedFilter); + when(filterService.count(eq(MockProvider.EXAMPLE_FILTER_ID))).thenReturn((long) mockedFilterItemCount); + when(filterService.getFilter(eq(MockProvider.ANOTHER_EXAMPLE_FILTER_ID))).thenReturn(anotherMockedFilter); + when(filterService.count(eq(MockProvider.ANOTHER_EXAMPLE_FILTER_ID))).thenReturn((long) anotherMockedFilterItemCount); + } + + @Test + public void testEmptyQuery() { + String queryFilterId = ""; + + given() + .queryParam("filterId", queryFilterId) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testCountyQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(FILTER_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testFilterRetrieval() { + Response response = given() + .queryParam("filterId", MockProvider.EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + + verifyFilterMock(response); + } + + @Test + public void testMultipleParameters() { + given() + .queryParams(getQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + + verifyQueryMockMultipleParameters(); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("filterId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "filterId") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + } + + @Test + public void testSuccessfulPagination() { + executeAndVerifyPagination(0, 10, Status.OK); + } + + @Test + public void testMissingFirstResultParameter() { + executeAndVerifyPagination(null, 10, Status.OK); + } + + @Test + public void testMissingMaxResultsParameter() { + executeAndVerifyPagination(0, null, Status.OK); + } + + @Test + public void testSingleFilterWithItemCount() { + given() + .pathParam("id", MockProvider.EXAMPLE_FILTER_ID) + .queryParam("itemCount", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("containsKey('itemCount')", is(true)) + .body("itemCount", equalTo(mockedFilterItemCount)) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testSingleFilterWithoutItemCount() { + given() + .pathParam("id", MockProvider.EXAMPLE_FILTER_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("containsKey('itemCount')", is(false)) + .when() + .get(SINGLE_FILTER_URL); + } + + @Test + public void testFilterQueryWithItemCount() { + given() + .queryParam("itemCount", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(2)) + .body("any { it.containsKey('itemCount') }", is(true)) + .body("[0].itemCount", equalTo(mockedFilterItemCount)) + .body("[1].itemCount", equalTo(anotherMockedFilterItemCount)) + .when() + .get(FILTER_QUERY_URL); + } + + @Test + public void testFilterQueryWithoutItemCount() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", equalTo(2)) + .body("any { it.containsKey('itemCount') }", is(false)) + .when() + .get(FILTER_QUERY_URL); + } + + protected Map getQueryParameters() { + Map params = new HashMap(); + + params.put("filterId", MockProvider.EXAMPLE_FILTER_ID); + params.put("resourceType", MockProvider.EXAMPLE_FILTER_RESOURCE_TYPE); + params.put("name", MockProvider.EXAMPLE_FILTER_NAME); + params.put("nameLike", MockProvider.EXAMPLE_FILTER_NAME); + params.put("owner", MockProvider.EXAMPLE_FILTER_OWNER); + + return params; + } + + @SuppressWarnings("unchecked") + protected void verifyFilterMock(Response response) { + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).filterId(MockProvider.EXAMPLE_FILTER_ID); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> filters = from(content).getList(""); + + assertThat(filters).hasSize(2); + + assertThat(filters.get(0)).isNotNull(); + + String returnedFilterId = from(content).getString("[0].id"); + String returnedResourceType = from(content).getString("[0].resourceType"); + String returnedName = from(content).getString("[0].name"); + String returnedOwner = from(content).getString("[0].owner"); + Map returnedQuery = from(content).getJsonObject("[0].query"); + Map returnedProperties = from(content).getJsonObject("[0].properties"); + + Map expectedVariable = new HashMap(); + expectedVariable.put("name", "foo"); + expectedVariable.put("value", "bar"); + expectedVariable.put("operator", "eq"); + + assertThat(returnedFilterId).isEqualTo(MockProvider.EXAMPLE_FILTER_ID); + assertThat(returnedResourceType).isEqualTo(MockProvider.EXAMPLE_FILTER_RESOURCE_TYPE); + assertThat(returnedName).isEqualTo(MockProvider.EXAMPLE_FILTER_NAME); + assertThat(returnedOwner).isEqualTo(MockProvider.EXAMPLE_FILTER_OWNER); + assertThat(returnedQuery.get("name")).isEqualTo(MockProvider.EXAMPLE_FILTER_QUERY_DTO.getName()); + assertThat((List>) returnedQuery.get("processVariables")).hasSize(1).containsExactly(expectedVariable); + assertThat((List>) returnedQuery.get("taskVariables")).hasSize(1).containsExactly(expectedVariable); + assertThat((List>) returnedQuery.get("caseInstanceVariables")).hasSize(1).containsExactly(expectedVariable); + assertThat(returnedProperties).isEqualTo(MockProvider.EXAMPLE_FILTER_PROPERTIES); + + assertThat(filters.get(1)).isNotNull(); + + returnedFilterId = from(content).getString("[1].id"); + returnedResourceType = from(content).getString("[1].resourceType"); + returnedName = from(content).getString("[1].name"); + returnedOwner = from(content).getString("[1].owner"); + returnedQuery = from(content).getJsonObject("[1].query"); + returnedProperties = from(content).getJsonObject("[1].properties"); + + assertThat(returnedFilterId).isEqualTo(MockProvider.ANOTHER_EXAMPLE_FILTER_ID); + assertThat(returnedResourceType).isEqualTo(MockProvider.EXAMPLE_FILTER_RESOURCE_TYPE); + assertThat(returnedName).isEqualTo(MockProvider.EXAMPLE_FILTER_NAME); + assertThat(returnedOwner).isEqualTo(MockProvider.EXAMPLE_FILTER_OWNER); + assertThat(returnedQuery.get("name")).isEqualTo(MockProvider.EXAMPLE_FILTER_QUERY_DTO.getName()); + assertThat(returnedProperties).isEqualTo(MockProvider.EXAMPLE_FILTER_PROPERTIES); + } + + protected void verifyQueryMockMultipleParameters() { + verify(mockedQuery).filterId(MockProvider.EXAMPLE_FILTER_ID); + verify(mockedQuery).filterResourceType(MockProvider.EXAMPLE_FILTER_RESOURCE_TYPE); + verify(mockedQuery).filterName(MockProvider.EXAMPLE_FILTER_NAME); + verify(mockedQuery).filterNameLike(MockProvider.EXAMPLE_FILTER_NAME); + verify(mockedQuery).filterOwner(MockProvider.EXAMPLE_FILTER_OWNER); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + Map params = new HashMap(); + params.put("sortBy", sortBy); + params.put("sortOrder", sortOrder); + + given() + .queryParams(params) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + + if (expectedStatus.equals(Status.OK)) { + verifyQueryMockSorting(sortBy, sortOrder); + } + } + + protected void verifyQueryMockSorting(String sortBy, String sortOrder) { + InOrder inOrder = inOrder(mockedQuery); + if (sortBy.equals(FilterQueryDto.SORT_BY_ID_VALUE)) { + inOrder.verify(mockedQuery).orderByFilterId(); + } + else if (sortBy.equals(FilterQueryDto.SORT_BY_RESOURCE_TYPE_VALUE)) { + inOrder.verify(mockedQuery).orderByFilterResourceType(); + } + else if (sortBy.equals(FilterQueryDto.SORT_BY_NAME_VALUE)) { + inOrder.verify(mockedQuery).orderByFilterName(); + } + else if (sortBy.equals(FilterQueryDto.SORT_BY_OWNER_VALUE)) { + inOrder.verify(mockedQuery).orderByFilterOwner(); + } + + if (sortOrder.equals(AbstractQuery.SORTORDER_ASC)) { + inOrder.verify(mockedQuery).asc(); + } + else if (sortOrder.equals(AbstractQuery.SORTORDER_DESC)) { + inOrder.verify(mockedQuery).desc(); + } + } + + protected void executeAndVerifyPagination(Integer firstResult, Integer maxResults, Status expectedStatus) { + Map params = new HashMap(); + if (firstResult != null) { + params.put("firstResult", firstResult.toString()); + } + if (maxResults != null) { + params.put("maxResults", maxResults.toString()); + } + + given() + .queryParams(params) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(FILTER_QUERY_URL); + + verifyQueryMockPagination(firstResult, maxResults); + + } + + protected void verifyQueryMockPagination(Integer firstResult, Integer maxResults) { + if (firstResult == null) { + firstResult = 0; + } + if (maxResults == null) { + maxResults = Integer.MAX_VALUE; + } + + verify(mockedQuery).listPage(firstResult, maxResults); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/GroupRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/GroupRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..42de2f5ab0059b58098f990c88bde7f1611c5809 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/GroupRestServiceInteractionTest.java @@ -0,0 +1,752 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.GROUP; +import static org.camunda.bpm.engine.authorization.Resources.GROUP_MEMBERSHIP; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.dto.identity.GroupDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; + +/** + * @author Daniel Meyer + * + */ +public class GroupRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/group"; + protected static final String GROUP_URL = SERVICE_URL + "/{id}"; + protected static final String GROUP_MEMBERS_URL = GROUP_URL + "/members"; + protected static final String GROUP_MEMBER_URL = GROUP_MEMBERS_URL + "/{userId}"; + protected static final String GROUP_CREATE_URL = TEST_RESOURCE_ROOT_PATH + "/group/create"; + + protected IdentityService identityServiceMock; + protected AuthorizationService authorizationServiceMock; + protected ProcessEngineConfiguration processEngineConfigurationMock; + + @Before + public void setupGroupData() { + + identityServiceMock = mock(IdentityService.class); + authorizationServiceMock = mock(AuthorizationService.class); + processEngineConfigurationMock = mock(ProcessEngineConfiguration.class); + + // mock identity service + when(processEngine.getIdentityService()).thenReturn(identityServiceMock); + // authorization service + when(processEngine.getAuthorizationService()).thenReturn(authorizationServiceMock); + // process engine configuration + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationMock); + } + + @Test + public void testGetSingleGroup() { + Group sampleGroup = MockProvider.createMockGroup(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(sampleGroup); + + given().pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_GROUP_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_GROUP_NAME)) + .when().get(GROUP_URL); + } + + @Test + public void testUserRestServiceOptions() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + GroupRestService.PATH; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl+"/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl+"/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_URL); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testUserRestServiceOptionsWithAuthorizationDisabled() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + GroupRestService.PATH; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl+"/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl+"/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testGroupResourceOptionsUnauthenticated() { + String fullGroupUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/group/" + MockProvider.EXAMPLE_GROUP_ID; + + Group sampleGroup = MockProvider.createMockGroup(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(sampleGroup); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullGroupUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullGroupUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullGroupUrl)) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when().options(GROUP_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + } + + @Test + public void testGroupResourceOptionsUnauthorized() { + String fullGroupUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/group/" + MockProvider.EXAMPLE_GROUP_ID; + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, GROUP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(false); + + Group sampleGroup = MockProvider.createMockGroup(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(sampleGroup); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullGroupUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1]", nullValue()) + .body("links[2]", nullValue()) + + .when().options(GROUP_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP, MockProvider.EXAMPLE_GROUP_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, GROUP, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testGroupResourceOptionsAuthorized() { + String fullGroupUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/group/" + MockProvider.EXAMPLE_GROUP_ID; + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, GROUP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(false); + + Group sampleGroup = MockProvider.createMockGroup(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(sampleGroup); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullGroupUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullGroupUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2]", nullValue()) + + .when().options(GROUP_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP, MockProvider.EXAMPLE_GROUP_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, GROUP, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testGroupResourceOptionsWithAuthorizationDisabled() { + String fullGroupUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/group/" + MockProvider.EXAMPLE_GROUP_ID; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullGroupUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullGroupUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullGroupUrl)) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when() + .options(GROUP_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testGroupMembersResourceOptions() { + String fullMembersUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/group/" + MockProvider.EXAMPLE_GROUP_ID + "/members"; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullMembersUrl)) + .body("links[0].method", equalTo(HttpMethod.DELETE)) + .body("links[0].rel", equalTo("delete")) + + .body("links[1].href", equalTo(fullMembersUrl)) + .body("links[1].method", equalTo(HttpMethod.PUT)) + .body("links[1].rel", equalTo("create")) + + .when() + .options(GROUP_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + } + + @Test + public void testGroupMembersResourceOptionsAuthorized() { + String fullMembersUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/group/" + MockProvider.EXAMPLE_GROUP_ID + "/members"; + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(true); + + Group sampleGroup = MockProvider.createMockGroup(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(sampleGroup); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullMembersUrl)) + .body("links[0].method", equalTo(HttpMethod.DELETE)) + .body("links[0].rel", equalTo("delete")) + + .body("links[1].href", equalTo(fullMembersUrl)) + .body("links[1].method", equalTo(HttpMethod.PUT)) + .body("links[1].rel", equalTo("create")) + + .when() + .options(GROUP_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testGroupMembersResourceOptionsUnauthorized() { + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID)).thenReturn(false); + + Group sampleGroup = MockProvider.createMockGroup(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(sampleGroup); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0]", nullValue()) + + .body("links[1]", nullValue()) + + .when() + .options(GROUP_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, GROUP_MEMBERSHIP, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testGroupMembersResourceOptionsWithAuthorizationDisabled() { + String fullMembersUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/group/" + MockProvider.EXAMPLE_GROUP_ID + "/members"; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullMembersUrl)) + .body("links[0].method", equalTo(HttpMethod.DELETE)) + .body("links[0].rel", equalTo("delete")) + + .body("links[1].href", equalTo(fullMembersUrl)) + .body("links[1].method", equalTo(HttpMethod.PUT)) + .body("links[1].rel", equalTo("create")) + + .when() + .options(GROUP_MEMBERS_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testGetNonExistingGroup() { + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(anyString())).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(null); + + given().pathParam("id", "aNonExistingGroup") + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Group with id aNonExistingGroup does not exist")) + .when().get(GROUP_URL); + } + + @Test + public void testDeleteGroup() { + given().pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(GROUP_URL); + } + + @Test + public void testDeleteNonExistingGroup() { + given().pathParam("id", "non-existing") + .expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(GROUP_URL); + } + + @Test + public void testDeleteGroupThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).deleteGroup(MockProvider.EXAMPLE_GROUP_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(GROUP_URL); + } + + @Test + public void testUpdateExistingGroup() { + Group initialGroup = MockProvider.createMockGroup(); + Group groupUpdate = MockProvider.createMockGroupUpdate(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(initialGroup); + + given().pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .body(GroupDto.fromGroup(groupUpdate)).contentType(ContentType.JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(GROUP_URL); + + // initial group was updated + verify(initialGroup).setName(groupUpdate.getName()); + + // and then saved + verify(identityServiceMock).saveGroup(initialGroup); + } + + @Test + public void testUpdateNonExistingGroup() { + Group groupUpdate = MockProvider.createMockGroupUpdate(); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId("aNonExistingGroup")).thenReturn(sampleGroupQuery); + // this time the query returns null + when(sampleGroupQuery.singleResult()).thenReturn(null); + + given().pathParam("id", "aNonExistingGroup") + .body(GroupDto.fromGroup(groupUpdate)).contentType(ContentType.JSON) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Group with id aNonExistingGroup does not exist")) + .when().put(GROUP_URL); + + verify(identityServiceMock, never()).saveGroup(any(Group.class)); + } + + @Test + public void testUpdateGroupThrowsAuthorizationException() { + Group initialGroup = MockProvider.createMockGroup(); + Group groupUpdate = MockProvider.createMockGroupUpdate(); + + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(identityServiceMock.createGroupQuery()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupId(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.singleResult()).thenReturn(initialGroup); + + String message = "exception expected"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).saveGroup(any(Group.class)); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .body(GroupDto.fromGroup(groupUpdate)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(GROUP_URL); + + // initial group was updated + verify(initialGroup).setName(groupUpdate.getName()); + } + + @Test + public void testGroupCreate() { + Group newGroup = MockProvider.createMockGroup(); + when(identityServiceMock.newGroup(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(newGroup); + + given() + .body(GroupDto.fromGroup(newGroup)).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(GROUP_CREATE_URL); + + verify(identityServiceMock).newGroup(MockProvider.EXAMPLE_GROUP_ID); + verify(newGroup).setName(MockProvider.EXAMPLE_GROUP_NAME); + verify(identityServiceMock).saveGroup(newGroup); + } + + @Test + public void testGroupCreateExistingFails() { + Group newGroup = MockProvider.createMockGroup(); + when(identityServiceMock.newGroup(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(newGroup); + doThrow(new ProcessEngineException("")).when(identityServiceMock).saveGroup(newGroup); + + given().body(GroupDto.fromGroup(newGroup)).contentType(ContentType.JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .when().post(GROUP_CREATE_URL); + + verify(identityServiceMock).newGroup(MockProvider.EXAMPLE_GROUP_ID); + verify(identityServiceMock).saveGroup(newGroup); + } + + @Test + public void testGroupCreateThrowsAuthorizationException() { + Group newGroup = MockProvider.createMockGroup(); + String message = "exception expected"; + when(identityServiceMock.newGroup(newGroup.getId())).thenThrow(new AuthorizationException(message)); + + given() + .body(GroupDto.fromGroup(newGroup)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(GROUP_CREATE_URL); + } + + @Test + public void testSaveGroupThrowsAuthorizationException() { + Group newGroup = MockProvider.createMockGroup(); + + String message = "exception expected"; + when(identityServiceMock.newGroup(newGroup.getId())).thenReturn(newGroup); + doThrow(new AuthorizationException(message)).when(identityServiceMock).saveGroup(newGroup); + + given() + .body(GroupDto.fromGroup(newGroup)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(GROUP_CREATE_URL); + } + + @Test + public void testCreateGroupMember() { + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(GROUP_MEMBER_URL); + + verify(identityServiceMock).createMembership(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testCreateGroupMemberThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).createMembership(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_GROUP_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(GROUP_MEMBER_URL); + } + + @Test + public void testDeleteGroupMember() { + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(GROUP_MEMBER_URL); + + verify(identityServiceMock).deleteMembership(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testDeleteGroupMemberThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).deleteMembership(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_GROUP_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(GROUP_MEMBER_URL); + } + + @Test + public void testReadOnlyGroupCreateFails() { + Group newGroup = MockProvider.createMockGroup(); + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given().body(GroupDto.fromGroup(newGroup)).contentType(ContentType.JSON) + .then().expect().statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when().post(GROUP_CREATE_URL); + + verify(identityServiceMock, never()).newGroup(MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testReadOnlyGroupUpdateFails() { + Group groupUdpdate = MockProvider.createMockGroup(); + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .body(GroupDto.fromGroup(groupUdpdate)).contentType(ContentType.JSON) + .then().expect().statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when().put(GROUP_URL); + + verify(identityServiceMock, never()).saveGroup(groupUdpdate); + } + + @Test + public void testReadOnlyGroupDeleteFails() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .then().expect().statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when().delete(GROUP_URL); + + verify(identityServiceMock, never()).deleteGroup(MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testReadOnlyCreateGroupMemberFails() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .put(GROUP_MEMBER_URL); + + verify(identityServiceMock, never()).createMembership(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void testReadOnlyGroupMemberDeleteFails() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_GROUP_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .delete(GROUP_MEMBER_URL); + + verify(identityServiceMock, never()).deleteMembership(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + protected void verifyNoAuthorizationCheckPerformed() { + verify(identityServiceMock, times(0)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(0)).isUserAuthorized(anyString(), anyList(), any(Permission.class), any(Resource.class)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/GroupRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/GroupRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a5b5f1121c8194f1283990b8a92a5256f151fd84 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/GroupRestServiceQueryTest.java @@ -0,0 +1,267 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.assertj.core.util.Arrays; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +public class GroupRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String GROUP_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/group"; + protected static final String GROUP_COUNT_QUERY_URL = GROUP_QUERY_URL + "/count"; + + private GroupQuery mockQuery; + + @Before + public void setUpRuntimeData() { + mockQuery = setUpMockGroupQuery(MockProvider.createMockGroups()); + } + + private GroupQuery setUpMockGroupQuery(List list) { + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(sampleGroupQuery.list()).thenReturn(list); + when(sampleGroupQuery.count()).thenReturn((long) list.size()); + + when(processEngine.getIdentityService().createGroupQuery()).thenReturn(sampleGroupQuery); + + return sampleGroupQuery; + } + + @Test + public void testEmptyQuery() { + + String queryKey = ""; + given().queryParam("name", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(GROUP_QUERY_URL); + + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "name") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(GROUP_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(GROUP_QUERY_URL); + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(GROUP_QUERY_URL); + + verify(mockQuery).list(); + verifyNoMoreInteractions(mockQuery); + } + + @Test + public void testSimpleGroupQuery() { + String queryName = MockProvider.EXAMPLE_GROUP_NAME; + + Response response = given().queryParam("name", queryName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(GROUP_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).groupName(queryName); + inOrder.verify(mockQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one group returned.", 1, instances.size()); + Assert.assertNotNull("The returned group should not be null.", instances.get(0)); + + String returendName = from(content).getString("[0].name"); + String returendType = from(content).getString("[0].type"); + + Assert.assertEquals(MockProvider.EXAMPLE_GROUP_NAME, returendName); + Assert.assertEquals(MockProvider.EXAMPLE_GROUP_TYPE, returendType); + + } + + @Test + public void testCompleteGetParameters() { + + Map queryParameters = getCompleteStringQueryParameters(); + + RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE); + for (Entry paramEntry : queryParameters.entrySet()) { + requestSpecification.param(paramEntry.getKey(), paramEntry.getValue()); + } + + requestSpecification.expect().statusCode(Status.OK.getStatusCode()) + .when().get(GROUP_QUERY_URL); + + verify(mockQuery).groupName(MockProvider.EXAMPLE_GROUP_NAME); + verify(mockQuery).groupNameLike("%" + MockProvider.EXAMPLE_GROUP_NAME + "%"); + verify(mockQuery).groupType(MockProvider.EXAMPLE_GROUP_TYPE); + verify(mockQuery).groupMember(MockProvider.EXAMPLE_USER_ID); + verify(mockQuery).memberOfTenant(MockProvider.EXAMPLE_TENANT_ID); + verify(mockQuery).groupId(MockProvider.EXAMPLE_GROUP_ID); + verify(mockQuery).groupIdIn(MockProvider.EXAMPLE_GROUP_ID, MockProvider.EXAMPLE_GROUP_ID2); + + verify(mockQuery).list(); + + } + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("name", MockProvider.EXAMPLE_GROUP_NAME); + parameters.put("nameLike", "%" + MockProvider.EXAMPLE_GROUP_NAME + "%"); + parameters.put("type", MockProvider.EXAMPLE_GROUP_TYPE); + parameters.put("member", MockProvider.EXAMPLE_USER_ID); + parameters.put("memberOfTenant", MockProvider.EXAMPLE_TENANT_ID); + parameters.put("id", MockProvider.EXAMPLE_GROUP_ID); + parameters.put("idIn", MockProvider.EXAMPLE_GROUP_ID + "," + MockProvider.EXAMPLE_GROUP_ID2); + + return parameters; + } + + private Map getCompletePostParameters() { + Map parameters = getCompleteStringQueryParameters(); + + parameters.put("idIn", Arrays.array(MockProvider.EXAMPLE_GROUP_ID, MockProvider.EXAMPLE_GROUP_ID2)); + + return parameters; + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(GROUP_COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(GROUP_QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + + @Test + public void testQueryCountForPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(GROUP_COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void testCompletePostParameters() { + + Map requestBody = getCompletePostParameters(); + + given().contentType(POST_JSON_CONTENT_TYPE).body(requestBody) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(GROUP_QUERY_URL); + + verify(mockQuery).groupName(MockProvider.EXAMPLE_GROUP_NAME); + verify(mockQuery).groupNameLike("%" + MockProvider.EXAMPLE_GROUP_NAME + "%"); + verify(mockQuery).groupType(MockProvider.EXAMPLE_GROUP_TYPE); + verify(mockQuery).groupMember(MockProvider.EXAMPLE_USER_ID); + verify(mockQuery).memberOfTenant(MockProvider.EXAMPLE_TENANT_ID); + verify(mockQuery).groupId(MockProvider.EXAMPLE_GROUP_ID); + verify(mockQuery).groupIdIn(MockProvider.EXAMPLE_GROUP_ID, MockProvider.EXAMPLE_GROUP_ID2); + + verify(mockQuery).list(); + } + + + @Test + public void testPaginationGet() { + + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(GROUP_QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + @Test + public void testPaginationPost() { + + int firstResult = 0; + int maxResults = 10; + given().contentType(POST_JSON_CONTENT_TYPE) + .queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(GROUP_QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IdentityRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IdentityRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5d190725441870dda6aeb3ee5dec7783bd2590c6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IdentityRestServiceQueryTest.java @@ -0,0 +1,138 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.rest.dto.identity.BasicUserCredentialsDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; + +public class IdentityRestServiceQueryTest extends AbstractRestServiceTest { + + protected static final String TEST_USERNAME = "testUsername"; + protected static final String TEST_PASSWORD = "testPassword"; + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String IDENTITY_URL = TEST_RESOURCE_ROOT_PATH + "/identity"; + protected static final String TASK_GROUPS_URL = IDENTITY_URL + "/groups"; + protected static final String VERIFY_USER_URL = IDENTITY_URL + "/verify"; + + private User mockUser; + + @Before + public void setUpRuntimeData() { + createMockIdentityQueries(); + } + + private void createMockIdentityQueries() { + UserQuery sampleUserQuery = mock(UserQuery.class); + + List mockUsers = new ArrayList(); + + mockUser = MockProvider.createMockUser(); + mockUsers.add(mockUser); + + when(sampleUserQuery.unlimitedList()).thenReturn(mockUsers); + when(sampleUserQuery.memberOfGroup(anyString())).thenReturn(sampleUserQuery); + when(sampleUserQuery.count()).thenReturn((long) mockUsers.size()); + + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + + List mockGroups = MockProvider.createMockGroups(); + when(sampleGroupQuery.unlimitedList()).thenReturn(mockGroups); + when(sampleGroupQuery.groupMember(anyString())).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.orderByGroupName()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.orderByGroupId()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.orderByGroupType()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.asc()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.desc()).thenReturn(sampleGroupQuery); + + when(processEngine.getIdentityService().createGroupQuery()).thenReturn(sampleGroupQuery); + when(processEngine.getIdentityService().createUserQuery()).thenReturn(sampleUserQuery); + } + + + @Test + public void testGroupInfoQuery() { + given().queryParam("userId", "name") + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("groups.size()", is(1)) + .body("groups[0].id", equalTo(MockProvider.EXAMPLE_GROUP_ID)) + .body("groups[0].name", equalTo(MockProvider.EXAMPLE_GROUP_NAME)) + .body("groupUsers.size()", is(1)) + .body("groupUsers[0].id", equalTo(mockUser.getId())) + .when().get(TASK_GROUPS_URL); + } + + @Test + public void testGroupInfoQueryWithMissingUserParameter() { + expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No user id was supplied")) + .when().get(TASK_GROUPS_URL); + } + + @Test + public void verifyUserWithMissingParameter () { + given() + .body(new BasicUserCredentialsDto()).contentType(ContentType.JSON). + expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Username and password are required")) + .when().post(VERIFY_USER_URL); + } + + @Test + public void verifyUser () { + when(processEngine.getIdentityService() + .checkPassword(TEST_USERNAME, TEST_PASSWORD)) + .thenReturn(true); + + BasicUserCredentialsDto userCredentialsDto = new BasicUserCredentialsDto(); + userCredentialsDto.setUsername(TEST_USERNAME); + userCredentialsDto.setUsername(TEST_PASSWORD); + given() + .body(userCredentialsDto).contentType(ContentType.JSON). + expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Username and password are required")) + .when().post(VERIFY_USER_URL); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IncidentRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IncidentRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a5697226010aa3b0fe28330d40e9471e66dcb1a5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IncidentRestServiceInteractionTest.java @@ -0,0 +1,252 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_USER_OPERATION_ANNOTATION; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.runtime.IncidentQuery; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + + +public class IncidentRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String INCIDENT_URL = TEST_RESOURCE_ROOT_PATH + "/incident"; + protected static final String SINGLE_INCIDENT_URL = INCIDENT_URL + "/{id}"; + protected static final String INCIDENT_ANNOTATION_URL = SINGLE_INCIDENT_URL + "/annotation"; + + private RuntimeServiceImpl mockRuntimeService; + private IncidentQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + List incidents = MockProvider.createMockIncidents(); + + mockedQuery = setupMockIncidentQuery(incidents); + } + + private IncidentQuery setupMockIncidentQuery(List incidents) { + IncidentQuery sampleQuery = mock(IncidentQuery.class); + + when(sampleQuery.incidentId(anyString())).thenReturn(sampleQuery); + when(sampleQuery.singleResult()).thenReturn(mock(Incident.class)); + + mockRuntimeService = mock(RuntimeServiceImpl.class); + when(processEngine.getRuntimeService()).thenReturn(mockRuntimeService); + when(mockRuntimeService.createIncidentQuery()).thenReturn(sampleQuery); + + return sampleQuery; + } + + @Test + public void testGetIncident() { + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(SINGLE_INCIDENT_URL); + + verify(mockRuntimeService).createIncidentQuery(); + verify(mockedQuery).incidentId(EXAMPLE_INCIDENT_ID); + verify(mockedQuery).singleResult(); + } + + @Test + public void testGetUnexistingIncident() { + when(mockedQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .get(SINGLE_INCIDENT_URL); + + verify(mockRuntimeService).createIncidentQuery(); + verify(mockedQuery).incidentId(EXAMPLE_INCIDENT_ID); + verify(mockedQuery).singleResult(); + } + + @Test + public void testResolveIncident() { + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_INCIDENT_URL); + + verify(mockRuntimeService).resolveIncident(EXAMPLE_INCIDENT_ID); + } + + @Test + public void testResolveUnexistingIncident() { + doThrow(new NotFoundException()).when(mockRuntimeService).resolveIncident(anyString()); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .delete(SINGLE_INCIDENT_URL); + + verify(mockRuntimeService).resolveIncident(EXAMPLE_INCIDENT_ID); + } + + @Test + public void shouldSetAnnotation() { + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .contentType(MediaType.APPLICATION_JSON) + .body("{ \"annotation\": \"" + EXAMPLE_USER_OPERATION_ANNOTATION + "\" }") + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(INCIDENT_ANNOTATION_URL); + + verify(mockRuntimeService) + .setAnnotationForIncidentById(EXAMPLE_INCIDENT_ID, EXAMPLE_USER_OPERATION_ANNOTATION); + } + + @Test + public void shouldThrowNotValidExceptionWhenSetAnnotation() { + doThrow(new NotValidException("expected")) + .when(mockRuntimeService) + .setAnnotationForIncidentById(anyString(), anyString()); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .contentType(MediaType.APPLICATION_JSON) + .body("{ \"annotation\": \"" + EXAMPLE_USER_OPERATION_ANNOTATION + "\" }") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(INCIDENT_ANNOTATION_URL); + } + + @Test + public void shouldThrowAuthorizationExceptionWhenSetAnnotation() { + doThrow(new AuthorizationException("expected")) + .when(mockRuntimeService) + .setAnnotationForIncidentById(anyString(), anyString()); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .contentType(MediaType.APPLICATION_JSON) + .body("{ \"annotation\": \"" + EXAMPLE_USER_OPERATION_ANNOTATION + "\" }") + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .when() + .put(INCIDENT_ANNOTATION_URL); + } + + @Test + public void shouldThrowBadRequestExceptionWhenSetAnnotation() { + doThrow(new BadUserRequestException("expected")) + .when(mockRuntimeService) + .setAnnotationForIncidentById(anyString(), anyString()); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .contentType(MediaType.APPLICATION_JSON) + .body("{ \"annotation\": \"" + EXAMPLE_USER_OPERATION_ANNOTATION + "\" }") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(INCIDENT_ANNOTATION_URL); + } + + @Test + public void shouldClearAnnotation() { + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(INCIDENT_ANNOTATION_URL); + + verify(mockRuntimeService).clearAnnotationForIncidentById(EXAMPLE_INCIDENT_ID); + } + + @Test + public void shouldThrowNotValidExceptionWhenClearAnnotation() { + doThrow(new NotValidException("expected")) + .when(mockRuntimeService) + .clearAnnotationForIncidentById(anyString()); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .delete(INCIDENT_ANNOTATION_URL); + } + + @Test + public void shouldThrowAuthorizationExceptionWhenClearAnnotation() { + doThrow(new AuthorizationException("expected")) + .when(mockRuntimeService) + .clearAnnotationForIncidentById(anyString()); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .when() + .delete(INCIDENT_ANNOTATION_URL); + } + + @Test + public void shouldThrowBadRequestExceptionWhenClearAnnotation() { + doThrow(new BadUserRequestException("expected")) + .when(mockRuntimeService) + .clearAnnotationForIncidentById(anyString()); + + given() + .pathParam("id", EXAMPLE_INCIDENT_ID) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .delete(INCIDENT_ANNOTATION_URL); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IncidentRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IncidentRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ce334322f780612499b13da902c368934117b7c4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/IncidentRestServiceQueryTest.java @@ -0,0 +1,591 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_JOB_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TENANT_ID_LIST; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_JOB_DEFINITION_ID; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.runtime.IncidentQuery; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + + +/** + * + * @author Roman Smirnov + * + */ +public class IncidentRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String INCIDENT_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/incident"; + protected static final String INCIDENT_COUNT_QUERY_URL = INCIDENT_QUERY_URL + "/count"; + + private IncidentQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + List incidents = MockProvider.createMockIncidents(); + + mockedQuery = setupMockIncidentQuery(incidents); + } + + private IncidentQuery setupMockIncidentQuery(List incidents) { + IncidentQuery sampleQuery = mock(IncidentQuery.class); + + when(sampleQuery.list()).thenReturn(incidents); + when(sampleQuery.count()).thenReturn((long) incidents.size()); + + when(processEngine.getRuntimeService().createIncidentQuery()).thenReturn(sampleQuery); + + return sampleQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processInstanceId", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("processInstanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(INCIDENT_QUERY_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentMessage", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentMessage(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentMessage", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentMessage(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentTimestamp", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentTimestamp(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentTimestamp", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentTimestamp(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentType", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentType(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("causeIncidentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCauseIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("causeIncidentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCauseIncidentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("rootCauseIncidentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByRootCauseIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("rootCauseIncidentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByRootCauseIncidentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("configuration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByConfiguration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("configuration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByConfiguration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(INCIDENT_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleIncidentQuery() { + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List incidents = from(content).getList(""); + Assert.assertEquals("There should be one incident returned.", 1, incidents.size()); + Assert.assertNotNull("The returned incident should not be null.", incidents.get(0)); + + String returnedId = from(content).getString("[0].id"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedExecutionId = from(content).getString("[0].executionId"); + Date returnedIncidentTimestamp = DateTimeUtil.parseDate(from(content).getString("[0].incidentTimestamp")); + String returnedIncidentType = from(content).getString("[0].incidentType"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedFailedActivityId = from(content).getString("[0].failedActivityId"); + String returnedCauseIncidentId = from(content).getString("[0].causeIncidentId"); + String returnedRootCauseIncidentId = from(content).getString("[0].rootCauseIncidentId"); + String returnedConfiguration = from(content).getString("[0].configuration"); + String returnedIncidentMessage = from(content).getString("[0].incidentMessage"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedJobDefinitionId = from(content).getString("[0].jobDefinitionId"); + String returnedAnnotation = from(content).getString("[0].annotation"); + + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_PROC_INST_ID, returnedProcessInstanceId); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_INCIDENT_TIMESTAMP), returnedIncidentTimestamp); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_PROC_DEF_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_TYPE, returnedIncidentType); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_ACTIVITY_ID, returnedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_FAILED_ACTIVITY_ID, returnedFailedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_CAUSE_INCIDENT_ID, returnedCauseIncidentId); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_ROOT_CAUSE_INCIDENT_ID, returnedRootCauseIncidentId); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_CONFIGURATION, returnedConfiguration); + Assert.assertEquals(MockProvider.EXAMPLE_INCIDENT_MESSAGE, returnedIncidentMessage); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_DEFINITION_ID, returnedJobDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_USER_OPERATION_ANNOTATION, returnedAnnotation); + } + + @Test + public void testQueryByIncidentId() { + String incidentId = MockProvider.EXAMPLE_INCIDENT_ID; + + given() + .queryParam("incidentId", incidentId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentId(incidentId); + } + + @Test + public void testQueryByIncidentType() { + String incidentType = MockProvider.EXAMPLE_INCIDENT_TYPE; + + given() + .queryParam("incidentType", incidentType) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentType(incidentType); + } + + @Test + public void testQueryByIncidentMessage() { + String incidentMessage = MockProvider.EXAMPLE_INCIDENT_MESSAGE; + + given() + .queryParam("incidentMessage", incidentMessage) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentMessage(incidentMessage); + } + + @Test + public void testQueryByIncidentMessageLike() { + String incidentMessage = MockProvider.EXAMPLE_INCIDENT_MESSAGE; + + given() + .queryParam("incidentMessageLike", incidentMessage) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentMessageLike(incidentMessage); + } + + @Test + public void testQueryByIncidentTimestampBeforeAndAfter() { + given() + .queryParam("incidentTimestampBefore", MockProvider.EXAMPLE_INCIDENT_TIMESTAMP_BEFORE) + .queryParam("incidentTimestampAfter", MockProvider.EXAMPLE_INCIDENT_TIMESTAMP_AFTER) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentTimestampBefore(DateTimeUtil.parseDate(MockProvider.EXAMPLE_INCIDENT_TIMESTAMP_BEFORE)); + verify(mockedQuery).incidentTimestampAfter(DateTimeUtil.parseDate(MockProvider.EXAMPLE_INCIDENT_TIMESTAMP_AFTER)); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessDefinitionId() { + String processDefinitionId = MockProvider.EXAMPLE_INCIDENT_PROC_DEF_ID; + + given() + .queryParam("processDefinitionId", processDefinitionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).processDefinitionId(processDefinitionId); + } + + @Test + public void testQueryByProcessDefinitionKey() { + String key1 = "foo"; + String key2 = "bar"; + + given() + .queryParam("processDefinitionKeyIn", key1 + "," + key2) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + InOrder inOrder = inOrder(mockedQuery); + + inOrder.verify(mockedQuery).processDefinitionKeyIn("foo", "bar"); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessInstanceId() { + String processInstanceId = MockProvider.EXAMPLE_INCIDENT_PROC_INST_ID; + + given() + .queryParam("processInstanceId", processInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).processInstanceId(processInstanceId); + } + + @Test + public void testQueryByExecutionId() { + String executionId = MockProvider.EXAMPLE_INCIDENT_EXECUTION_ID; + + given() + .queryParam("executionId", executionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).executionId(executionId); + } + + @Test + public void testQueryByActivityId() { + String activityId = MockProvider.EXAMPLE_INCIDENT_ACTIVITY_ID; + + given() + .queryParam("activityId", activityId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).activityId(activityId); + } + + @Test + public void testQueryByFailedActivityId() { + String activityId = MockProvider.EXAMPLE_INCIDENT_FAILED_ACTIVITY_ID; + + given() + .queryParam("failedActivityId", activityId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).failedActivityId(activityId); + } + + @Test + public void testQueryByCauseIncidentId() { + String causeIncidentId = MockProvider.EXAMPLE_INCIDENT_CAUSE_INCIDENT_ID; + + given() + .queryParam("causeIncidentId", causeIncidentId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).causeIncidentId(causeIncidentId); + } + + @Test + public void testQueryByRootCauseIncidentId() { + String rootCauseIncidentId = MockProvider.EXAMPLE_INCIDENT_ROOT_CAUSE_INCIDENT_ID; + + given() + .queryParam("rootCauseIncidentId", rootCauseIncidentId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).rootCauseIncidentId(rootCauseIncidentId); + } + + @Test + public void testQueryByConfiguration() { + String configuration = MockProvider.EXAMPLE_INCIDENT_CONFIGURATION; + + given() + .queryParam("configuration", configuration) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(INCIDENT_QUERY_URL); + + verify(mockedQuery).configuration(configuration); + } + + @Test + public void testQueryByTenantIds() { + mockedQuery = setupMockIncidentQuery(Arrays.asList( + MockProvider.createMockIncident(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockIncident(MockProvider.ANOTHER_EXAMPLE_TENANT_ID))); + + Response response = given() + .queryParam("tenantIdIn", EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryByJobDefinitionIds() { + String jobDefinitionIds = EXAMPLE_JOB_DEFINITION_ID + "," + NON_EXISTING_JOB_DEFINITION_ID; + + given() + .queryParam("jobDefinitionIdIn", jobDefinitionIds) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_QUERY_URL); + + verify(mockedQuery).jobDefinitionIdIn(EXAMPLE_JOB_DEFINITION_ID, NON_EXISTING_JOB_DEFINITION_ID); + verify(mockedQuery).list(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobDefinitionRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobDefinitionRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..33e65a9acd6590b007b091eeab2f6f0d40b8486f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobDefinitionRestServiceInteractionTest.java @@ -0,0 +1,1739 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.management.JobDefinition; +import org.camunda.bpm.engine.management.JobDefinitionQuery; +import org.camunda.bpm.engine.management.SetJobRetriesBuilder; +import org.camunda.bpm.engine.management.UpdateJobDefinitionSuspensionStateSelectBuilder; +import org.camunda.bpm.engine.management.UpdateJobDefinitionSuspensionStateTenantBuilder; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.MockJobDefinitionBuilder; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +public class JobDefinitionRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String JOB_DEFINITION_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/job-definition"; + protected static final String SINGLE_JOB_DEFINITION_RESOURCE_URL = JOB_DEFINITION_RESOURCE_URL + "/{id}"; + protected static final String SINGLE_JOB_DEFINITION_SUSPENDED_URL = SINGLE_JOB_DEFINITION_RESOURCE_URL + "/suspended"; + protected static final String JOB_DEFINITION_SUSPENDED_URL = JOB_DEFINITION_RESOURCE_URL + "/suspended"; + protected static final String JOB_DEFINITION_RETRIES_URL = SINGLE_JOB_DEFINITION_RESOURCE_URL + "/retries"; + protected static final String JOB_DEFINITION_PRIORITY_URL = SINGLE_JOB_DEFINITION_RESOURCE_URL + "/jobPriority"; + + private ProcessEngine namedProcessEngine; + private ManagementService mockManagementService; + + private UpdateJobDefinitionSuspensionStateTenantBuilder mockSuspensionStateBuilder; + private UpdateJobDefinitionSuspensionStateSelectBuilder mockSuspensionStateSelectBuilder; + + private JobDefinitionQuery mockQuery; + + private SetJobRetriesBuilder mockSetJobRetriesBuilder; + + @Before + public void setUpRuntimeData() { + mockManagementService = mock(ManagementService.class); + + namedProcessEngine = getProcessEngine(MockProvider.EXAMPLE_PROCESS_ENGINE_NAME); + when(namedProcessEngine.getManagementService()).thenReturn(mockManagementService); + + List mockJobDefinitions = Collections.singletonList(MockProvider.createMockJobDefinition()); + mockQuery = setUpMockJobDefinitionQuery(mockJobDefinitions); + + mockSuspensionStateSelectBuilder = mock(UpdateJobDefinitionSuspensionStateSelectBuilder.class); + when(mockManagementService.updateJobDefinitionSuspensionState()).thenReturn(mockSuspensionStateSelectBuilder); + + mockSuspensionStateBuilder = mock(UpdateJobDefinitionSuspensionStateTenantBuilder.class); + when(mockSuspensionStateSelectBuilder.byJobDefinitionId(anyString())).thenReturn(mockSuspensionStateBuilder); + when(mockSuspensionStateSelectBuilder.byProcessDefinitionId(anyString())).thenReturn(mockSuspensionStateBuilder); + when(mockSuspensionStateSelectBuilder.byProcessDefinitionKey(anyString())).thenReturn(mockSuspensionStateBuilder); + + mockSetJobRetriesBuilder = mock(SetJobRetriesBuilder.class); + when(mockManagementService.setJobRetries(anyInt())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.jobId(any())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.jobIds(any())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.jobDefinitionId(any())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.dueDate(any())).thenReturn(mockSetJobRetriesBuilder); + } + + private JobDefinitionQuery setUpMockJobDefinitionQuery(List mockedJobDefinitions) { + JobDefinitionQuery sampleJobDefinitionQuery = mock(JobDefinitionQuery.class); + + when(sampleJobDefinitionQuery.list()).thenReturn(mockedJobDefinitions); + when(sampleJobDefinitionQuery.count()).thenReturn((long) mockedJobDefinitions.size()); + if(mockedJobDefinitions.size() == 1) { + when(sampleJobDefinitionQuery.singleResult()).thenReturn(mockedJobDefinitions.get(0)); + } + + when(sampleJobDefinitionQuery.jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID)).thenReturn(sampleJobDefinitionQuery); + + when(processEngine.getManagementService().createJobDefinitionQuery()).thenReturn(sampleJobDefinitionQuery); + when(mockManagementService.createJobDefinitionQuery()).thenReturn(sampleJobDefinitionQuery); + + return sampleJobDefinitionQuery; + } + + @Test + public void testSimpleJobDefinitionGet() { + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_JOB_DEFINITION_ID)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processDefinitionKey", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("jobType", equalTo(MockProvider.EXAMPLE_JOB_TYPE)) + .body("jobConfiguration", equalTo(MockProvider.EXAMPLE_JOB_CONFIG)) + .body("activityId", equalTo(MockProvider.EXAMPLE_ACTIVITY_ID)) + .body("suspended", equalTo(MockProvider.EXAMPLE_JOB_DEFINITION_IS_SUSPENDED)) + .body("overridingJobPriority", equalTo(MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY)) + .body("tenantId", equalTo(null)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_JOB_DEFINITION_DEPLOYMENT_ID)) + .when() + .get(SINGLE_JOB_DEFINITION_RESOURCE_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + inOrder.verify(mockQuery).singleResult(); + } + + @Test + public void testJobDefinitionGetNullJobPriority() { + // given + JobDefinition mockJobDefinition = new MockJobDefinitionBuilder() + .id(MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .jobPriority(null) + .build(); + + when(mockQuery.singleResult()).thenReturn(mockJobDefinition); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_JOB_DEFINITION_ID)) + .body("jobPriority", nullValue()) + .when() + .get(SINGLE_JOB_DEFINITION_RESOURCE_URL); + } + + @Test + public void testJobDefinitionGetIdDoesntExist() { + JobDefinitionQuery invalidQueryNonExistingJobDefinition; + invalidQueryNonExistingJobDefinition = mock(JobDefinitionQuery.class); + + when(mockManagementService.createJobDefinitionQuery() + .jobDefinitionId(MockProvider.NON_EXISTING_JOB_DEFINITION_ID)) + .thenReturn(invalidQueryNonExistingJobDefinition); + + when(invalidQueryNonExistingJobDefinition.singleResult()).thenReturn(null); + + String jobDefinitionId = MockProvider.NON_EXISTING_JOB_DEFINITION_ID; + + given() + .pathParam("id", jobDefinitionId) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Job Definition with id " + jobDefinitionId + " does not exist")) + .when() + .get(SINGLE_JOB_DEFINITION_RESOURCE_URL); + } + + @Test + public void testActivateJobDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", false); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testDelayedActivateJobDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", false); + params.put("executionDate", MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(false); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testDelayedActivateJobDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", true); + params.put("executionDate", MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateThrowProcessEngineException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateNonParseableDateFormat() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", false); + params.put("executionDate", "a"); + + String expectedMessage = "Invalid format: \"a\""; + String exceptionMessage = "The suspension state of Job Definition with id " + MockProvider.NON_EXISTING_JOB_DEFINITION_ID + " could not be updated due to: " + expectedMessage; + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(exceptionMessage)) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", false); + + String expectedMessage = "expectedMessage"; + doThrow(new AuthorizationException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", false); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).includeJobs(false); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testDelayedSuspendJobDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", false); + params.put("executionDate", MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(false); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testDelayedSuspendJobDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", true); + params.put("executionDate", MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendThrowsProcessEngineException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendNonParseableDateFormat() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", false); + params.put("executionDate", "a"); + + String expectedMessage = "Invalid format: \"a\""; + String exceptionMessage = "The suspension state of Job Definition with id " + MockProvider.NON_EXISTING_JOB_DEFINITION_ID + " could not be updated due to: " + expectedMessage; + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(exceptionMessage)) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendWithMultipleByParameters() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "Only one of jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", false); + + String expectedMessage = "expectedMessage"; + doThrow(new AuthorizationException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testDelayedActivateJobDefinitionByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testDelayedActivateJobDefinitionByProcessDefinitionKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionKeyWithUnparseableDate() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", "a"); + + String message = "Could not update the suspension state of Job Definitions due to: Invalid format: \"a\""; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionKeyWithAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionKeyAndTenantId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionKeyWithoutTenantId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionWithoutTenantId", true); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionWithoutTenantId(); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testDelayedSuspendJobDefinitionByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testDelayedSuspendJobDefinitionByProcessDefinitionKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionKeyWithUnparseableDate() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", "a"); + + String message = "Could not update the suspension state of Job Definitions due to: Invalid format: \"a\""; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionKeyWithAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionKeyAndTenantId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionKeyWithoutTenantId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionWithoutTenantId", true); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionWithoutTenantId(); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionIdIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testDelayedActivateJobDefinitionByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testDelayedActivateJobDefinitionByProcessDefinitionIdIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeJobs", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionIdWithUnparseableDate() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("executionDate", "a"); + + String message = "Could not update the suspension state of Job Definitions due to: Invalid format: \"a\""; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByProcessDefinitionIdWithAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionIdIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testDelayedSuspendJobDefinitionByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testDelayedSuspendJobDefinitionByProcessDefinitionIdIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeJobs", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).executionDate(executionDate); + verify(mockSuspensionStateBuilder).includeJobs(true); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionIdWithUnparseableDate() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("executionDate", "a"); + + String message = "Could not update the suspension state of Job Definitions due to: Invalid format: \"a\""; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByProcessDefinitionIdWithAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateJobDefinitionByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + String message = "Either processDefinitionId or processDefinitionKey can be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + String message = "Either processDefinitionId or processDefinitionKey can be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendJobDefinitionByNothing() { + Map params = new HashMap<>(); + params.put("suspended", true); + + String message = "Either jobDefinitionId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSetJobRetries() { + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_RETRIES_URL); + + verify(mockManagementService, times(1)).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder, times(1)).jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSetJobRetriesBuilder, times(1)).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetJobRetriesWithDueDate() { + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + Date newDueDate = new Date(1675752840000L); + retriesVariableJson.put("dueDate", newDueDate); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_RETRIES_URL); + + verify(mockManagementService, times(1)).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder, times(1)).jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSetJobRetriesBuilder, times(1)).dueDate(newDueDate); + verify(mockSetJobRetriesBuilder, times(1)).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetJobRetriesWithNullDueDate() { + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + retriesVariableJson.put("dueDate", null); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_RETRIES_URL); + + verify(mockManagementService, times(1)).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder, times(1)).jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSetJobRetriesBuilder, times(1)).dueDate(null); + verify(mockSetJobRetriesBuilder, times(1)).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetJobRetriesExceptionExpected() { + doThrow(new ProcessEngineException("job definition not found")) + .when(mockSetJobRetriesBuilder).execute(); + + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("job definition not found")) + .when() + .put(JOB_DEFINITION_RETRIES_URL); + + verify(mockManagementService, times(1)).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder, times(1)).jobDefinitionId(MockProvider.NON_EXISTING_JOB_DEFINITION_ID); + verify(mockSetJobRetriesBuilder, times(1)).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetJobRetriesAuthorizationException() { + String expectedMessage = "expected exception message"; + doThrow(new AuthorizationException(expectedMessage)).when(mockSetJobRetriesBuilder).execute(); + + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_DEFINITION_RETRIES_URL); + + verify(mockManagementService, times(1)).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder, times(1)).jobDefinitionId(MockProvider.NON_EXISTING_JOB_DEFINITION_ID); + verify(mockSetJobRetriesBuilder, times(1)).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetJobPriority() { + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + + verify(mockManagementService).setOverridingJobPriorityForJobDefinition(MockProvider.EXAMPLE_JOB_DEFINITION_ID, + MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY, false); + } + + @Test + public void testSetJobPriorityToExtremeValue() { + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", Long.MAX_VALUE); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + + verify(mockManagementService).setOverridingJobPriorityForJobDefinition(MockProvider.EXAMPLE_JOB_DEFINITION_ID, + Long.MAX_VALUE, false); + } + + @Test + public void testSetJobPriorityIncludeExistingJobs() { + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY); + priorityJson.put("includeJobs", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + + verify(mockManagementService).setOverridingJobPriorityForJobDefinition(MockProvider.EXAMPLE_JOB_DEFINITION_ID, + MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY, true); + } + + @Test + public void testSetJobPriorityExceptionExpected() { + String expectedMessage = "expected exception message"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockManagementService) + .setOverridingJobPriorityForJobDefinition(eq(MockProvider.EXAMPLE_JOB_DEFINITION_ID), + eq(MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY), anyBoolean()); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + + verify(mockManagementService).setOverridingJobPriorityForJobDefinition(MockProvider.EXAMPLE_JOB_DEFINITION_ID, + MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY, false); + } + + @Test + public void testSetNonExistingJobDefinitionPriority() { + String expectedMessage = "expected exception message"; + + doThrow(new NotFoundException(expectedMessage)) + .when(mockManagementService) + .setOverridingJobPriorityForJobDefinition(eq(MockProvider.NON_EXISTING_JOB_DEFINITION_ID), + eq(MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY), anyBoolean()); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + } + + @Test + public void testSetJobPriorityAuthorizationException() { + String expectedMessage = "expected exception message"; + doThrow(new AuthorizationException(expectedMessage)) + .when(mockManagementService) + .setOverridingJobPriorityForJobDefinition(eq(MockProvider.EXAMPLE_JOB_DEFINITION_ID), + eq(MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY), anyBoolean()); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + } + + @Test + public void testResetJobPriority() { + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", null); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + + verify(mockManagementService).clearOverridingJobPriorityForJobDefinition(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + } + + @Test + public void testResetJobPriorityIncludeJobsNotAllowed() { + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", null); + priorityJson.put("includeJobs", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot reset priority for job definition " + MockProvider.EXAMPLE_JOB_DEFINITION_ID + + " with includeJobs=true")) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + } + + @Test + public void testResetJobPriorityExceptionExpected() { + String expectedMessage = "expected exception message"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockManagementService).clearOverridingJobPriorityForJobDefinition(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", null); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + } + + @Test + public void testResetNonExistingJobDefinitionPriority() { + String expectedMessage = "expected exception message"; + + doThrow(new NotFoundException(expectedMessage)) + .when(mockManagementService).clearOverridingJobPriorityForJobDefinition(MockProvider.NON_EXISTING_JOB_DEFINITION_ID); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", null); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + } + + @Test + public void testResetJobPriorityAuthorizationException() { + String expectedMessage = "expected exception message"; + doThrow(new AuthorizationException(expectedMessage)) + .when(mockManagementService).clearOverridingJobPriorityForJobDefinition(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", null); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_DEFINITION_PRIORITY_URL); + } + + @Test + public void testTenantIdListParameter() { + mockQuery = setUpMockJobDefinitionQuery(createMockJobDefinitionsTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOB_DEFINITION_RESOURCE_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List jobDefinitions = from(content).getList(""); + assertThat(jobDefinitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockQuery = setUpMockJobDefinitionQuery(createMockJobDefinitionsTwoTenants()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOB_DEFINITION_RESOURCE_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List jobDefinitions = from(content).getList(""); + assertThat(jobDefinitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + private List createMockJobDefinitionsTwoTenants() { + return Arrays.asList( + MockProvider.mockJobDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.mockJobDefinition().tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobDefinitionRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobDefinitionRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..341e1a4b9762ad2935073146e5ee48b47cf9da69 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobDefinitionRestServiceQueryTest.java @@ -0,0 +1,616 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.management.JobDefinition; +import org.camunda.bpm.engine.management.JobDefinitionQuery; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.response.Response; + +public class JobDefinitionRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String JOB_DEFINITION_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/job-definition"; + protected static final String JOB_DEFINITION_COUNT_QUERY_URL = JOB_DEFINITION_QUERY_URL + "/count"; + private JobDefinitionQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockDefinitionQuery(MockProvider.createMockJobDefinitions()); + } + + private JobDefinitionQuery setUpMockDefinitionQuery(List mockedJobDefinitions) { + JobDefinitionQuery query = mock(JobDefinitionQuery.class); + + when(query.list()).thenReturn(mockedJobDefinitions); + when(query.count()).thenReturn((long) mockedJobDefinitions.size()); + when(processEngine.getManagementService().createJobDefinitionQuery()).thenReturn(query); + + return query; + } + + @Test + public void testEmptyQuery() { + String queryJobDefinitionId = ""; + given().queryParam("jobDefinitionId", queryJobDefinitionId).then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testEmptyQueryAsPost() { + Map params = new HashMap<>(); + params.put("jobDefinitionId", ""); + + given().contentType(POST_JSON_CONTENT_TYPE).body(params) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("jobDefinitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(JOB_DEFINITION_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "jobDefinitionId") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + } + + @Test + public void testSortingParameters() { + // asc + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobType", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobConfiguration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobConfiguration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + // desc + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobType(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobConfiguration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobConfiguration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap<>(); + json.put("sorting", OrderingBuilder.create() + .orderBy("jobType").desc() + .orderBy("jobConfiguration").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOB_DEFINITION_QUERY_URL); + + inOrder.verify(mockedQuery).orderByJobType(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByJobConfiguration(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given().queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given().queryParam("firstResult", firstResult) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testJobDefinitionRetrieval() { + String queryJobDefinitionId = "aJobDefId"; + Response response = given().queryParam("jobDefinitionId", queryJobDefinitionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).jobDefinitionId(queryJobDefinitionId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> jobDefinitions = from(content).getList(""); + + assertThat(jobDefinitions).hasSize(1); + assertThat(jobDefinitions.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedJobType = from(content).getString("[0].jobType"); + String returnedJobConfiguration = from(content).getString("[0].jobConfiguration"); + boolean returnedSuspensionState = from(content).getBoolean("[0].suspended"); + Long returnedJobPriority = from(content).getObject("[0].overridingJobPriority", Long.class); + String returnedDeploymentId = from(content).getString("[0].deploymentId"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + assertThat(returnedProcessDefinitionId).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertThat(returnedProcessDefinitionKey).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + assertThat(returnedActivityId).isEqualTo(MockProvider.EXAMPLE_ACTIVITY_ID); + assertThat(returnedJobType).isEqualTo(MockProvider.EXAMPLE_JOB_TYPE); + assertThat(returnedJobConfiguration).isEqualTo(MockProvider.EXAMPLE_JOB_CONFIG); + assertThat(returnedSuspensionState).isEqualTo(MockProvider.EXAMPLE_JOB_DEFINITION_IS_SUSPENDED); + assertThat(returnedJobPriority).isEqualTo(MockProvider.EXAMPLE_JOB_DEFINITION_PRIORITY); + assertThat(returnedDeploymentId).isEqualTo(MockProvider.EXAMPLE_JOB_DEFINITION_DEPLOYMENT_ID); + } + + @Test + public void testJobDefinitionRetrievalAsPost() { + String queryJobDefinitionId = "aJobDefId"; + Map queryParameter = new HashMap<>(); + queryParameter.put("jobDefinitionId", queryJobDefinitionId); + + Response response = given().contentType(POST_JSON_CONTENT_TYPE).body(queryParameter) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOB_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).jobDefinitionId(queryJobDefinitionId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List> jobDefinitions = from(content).getList(""); + + assertThat(jobDefinitions).hasSize(1); + assertThat(jobDefinitions.get(0)).isNotNull(); + + String returnedId = from(content).getString("[0].id"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedJobType = from(content).getString("[0].jobType"); + String returnedJobConfiguration = from(content).getString("[0].jobConfiguration"); + boolean returnedSuspensionState = from(content).getBoolean("[0].suspended"); + String returnedDeploymentId = from(content).getString("[0].deploymentId"); + + assertThat(returnedId).isEqualTo(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + assertThat(returnedProcessDefinitionId).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertThat(returnedProcessDefinitionKey).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + assertThat(returnedActivityId).isEqualTo(MockProvider.EXAMPLE_ACTIVITY_ID); + assertThat(returnedJobType).isEqualTo(MockProvider.EXAMPLE_JOB_TYPE); + assertThat(returnedJobConfiguration).isEqualTo(MockProvider.EXAMPLE_JOB_CONFIG); + assertThat(returnedSuspensionState).isEqualTo(MockProvider.EXAMPLE_JOB_DEFINITION_IS_SUSPENDED); + assertThat(returnedDeploymentId).isEqualTo(MockProvider.EXAMPLE_JOB_DEFINITION_DEPLOYMENT_ID); + } + + @Test + public void testMultipleParameters() { + Map queryParameters = new HashMap<>(); + + queryParameters.put("jobDefinitionId", "aJobDefId"); + queryParameters.put("processDefinitionId", "aProcDefId"); + queryParameters.put("processDefinitionKey", "aProcDefKey"); + queryParameters.put("activityIdIn", "aActId,anotherActId"); + queryParameters.put("jobType", "aJobType"); + queryParameters.put("jobConfiguration", "aJobConfig"); + queryParameters.put("suspended", "true"); + queryParameters.put("active", "true"); + queryParameters.put("withOverridingJobPriority", "true"); + + given().queryParams(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).jobDefinitionId(queryParameters.get("jobDefinitionId")); + verify(mockedQuery).processDefinitionId(queryParameters.get("processDefinitionId")); + verify(mockedQuery).processDefinitionKey(queryParameters.get("processDefinitionKey")); + verify(mockedQuery).activityIdIn("aActId", "anotherActId"); + verify(mockedQuery).jobType(queryParameters.get("jobType")); + verify(mockedQuery).jobConfiguration(queryParameters.get("jobConfiguration")); + verify(mockedQuery).active(); + verify(mockedQuery).suspended(); + verify(mockedQuery).withOverridingJobPriority(); + verify(mockedQuery).list(); + } + + @Test + public void testMultipleParametersAsPost() { + String aJobDefId = "aJobDefId"; + String aProcDefId = "aProcDefId"; + String aProcDefKey = "aProcDefKey"; + String aActId = "aActId"; + String anotherActId = "anotherActId"; + String aJobType = "aJobType"; + String aJobConfig = "aJobConfig"; + + Map queryParameters = new HashMap<>(); + + queryParameters.put("jobDefinitionId", aJobDefId); + queryParameters.put("processDefinitionId", aProcDefId); + queryParameters.put("processDefinitionKey", aProcDefKey); + queryParameters.put("jobType", aJobType); + queryParameters.put("jobConfiguration", aJobConfig); + queryParameters.put("suspended", "true"); + queryParameters.put("active", "true"); + queryParameters.put("withOverridingJobPriority", "true"); + + List activityIdIn = new ArrayList<>(); + activityIdIn.add(aActId); + activityIdIn.add(anotherActId); + queryParameters.put("activityIdIn", activityIdIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(queryParameters) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).jobDefinitionId(aJobDefId); + verify(mockedQuery).processDefinitionId(aProcDefId); + verify(mockedQuery).processDefinitionKey(aProcDefKey); + verify(mockedQuery).activityIdIn(aActId, anotherActId); + verify(mockedQuery).jobType(aJobType); + verify(mockedQuery).jobConfiguration(aJobConfig); + verify(mockedQuery).active(); + verify(mockedQuery).suspended(); + verify(mockedQuery).withOverridingJobPriority(); + verify(mockedQuery).list(); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(JOB_DEFINITION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountAsPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(JOB_DEFINITION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockDefinitionQuery(createMockJobDefinitionsTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdParameter() { + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testIncludeJobDefinitionsWithoutTenantIdParameter() { + List jobDefinitions = Arrays.asList( + MockProvider.mockJobDefinition().tenantId(null).build(), + MockProvider.mockJobDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockedQuery = setUpMockDefinitionQuery(jobDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("includeJobDefinitionsWithoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockedQuery).includeJobDefinitionsWithoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockDefinitionQuery(createMockJobDefinitionsTwoTenants()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdPostParameter() { + Map queryParameters = new HashMap<>(); + queryParameters.put("withoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testIncludeJobDefinitionsWithoutTenantIdPostParameter() { + List jobDefinitions = Arrays.asList( + MockProvider.mockJobDefinition().tenantId(null).build(), + MockProvider.mockJobDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockedQuery = setUpMockDefinitionQuery(jobDefinitions); + + Map queryParameters = new HashMap<>(); + queryParameters.put("tenantIdIn", new String[] { MockProvider.EXAMPLE_TENANT_ID }); + queryParameters.put("includeJobDefinitionsWithoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOB_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockedQuery).includeJobDefinitionsWithoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + private List createMockJobDefinitionsTwoTenants() { + return Arrays.asList( + MockProvider.mockJobDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.mockJobDefinition().tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f38ce4139295d3633b0115652c37985a977095de --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobRestServiceInteractionTest.java @@ -0,0 +1,1821 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.management.SetJobRetriesBuilder; +import org.camunda.bpm.engine.management.SetJobRetriesByJobsAsyncBuilder; +import org.camunda.bpm.engine.management.UpdateJobSuspensionStateSelectBuilder; +import org.camunda.bpm.engine.management.UpdateJobSuspensionStateTenantBuilder; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.JobSuspensionStateDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.MockJobBuilder; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.JsonPathUtil; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.Job; +import org.camunda.bpm.engine.runtime.JobQuery; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +public class JobRestServiceInteractionTest extends AbstractRestServiceTest { + + private static final String RETRIES = "retries"; + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String JOB_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/job"; + protected static final String SINGLE_JOB_RESOURCE_URL = JOB_RESOURCE_URL + "/{id}"; + protected static final String JOB_RESOURCE_SET_RETRIES_URL = SINGLE_JOB_RESOURCE_URL + "/retries"; + protected static final String JOBS_SET_RETRIES_URL = JOB_RESOURCE_URL + "/retries"; + protected static final String JOB_RESOURCE_SET_PRIORITY_URL = SINGLE_JOB_RESOURCE_URL + "/priority"; + protected static final String JOB_RESOURCE_EXECUTE_JOB_URL = SINGLE_JOB_RESOURCE_URL + "/execute"; + protected static final String JOB_RESOURCE_GET_STACKTRACE_URL = SINGLE_JOB_RESOURCE_URL + "/stacktrace"; + protected static final String JOB_RESOURCE_SET_DUEDATE_URL = SINGLE_JOB_RESOURCE_URL + "/duedate"; + protected static final String JOB_RESOURCE_RECALC_DUEDATE_URL = JOB_RESOURCE_SET_DUEDATE_URL + "/recalculate"; + protected static final String SINGLE_JOB_SUSPENDED_URL = SINGLE_JOB_RESOURCE_URL + "/suspended"; + protected static final String JOB_SUSPENDED_URL = JOB_RESOURCE_URL + "/suspended"; + + private ProcessEngine namedProcessEngine; + private ManagementService mockManagementService; + + private UpdateJobSuspensionStateTenantBuilder mockSuspensionStateBuilder; + private UpdateJobSuspensionStateSelectBuilder mockSuspensionStateSelectBuilder; + + private JobQuery mockQuery; + private SetJobRetriesByJobsAsyncBuilder mockSetJobRetriesByJobsAsyncBuilder; + private SetJobRetriesBuilder mockSetJobRetriesBuilder; + + @Before + public void setUpRuntimeData() { + + mockQuery = mock(JobQuery.class); + Job mockedJob = new MockJobBuilder() + .id(MockProvider.EXAMPLE_JOB_ID) + .processInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .executionId(MockProvider.EXAMPLE_EXECUTION_ID) + .retries(MockProvider.EXAMPLE_JOB_RETRIES) + .exceptionMessage(MockProvider.EXAMPLE_JOB_NO_EXCEPTION_MESSAGE) + .failedActivityId(MockProvider.EXAMPLE_JOB_FAILED_ACTIVITY_ID) + .dueDate(new Date()) + .priority(MockProvider.EXAMPLE_JOB_PRIORITY) + .jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID) + .tenantId(MockProvider.EXAMPLE_TENANT_ID) + .createTime(DateTimeUtil.parseDate(MockProvider.EXAMPLE_JOB_CREATE_TIME)) + .batchId(MockProvider.EXAMPLE_BATCH_ID) + .build(); + + when(mockQuery.singleResult()).thenReturn(mockedJob); + when(mockQuery.jobId(MockProvider.EXAMPLE_JOB_ID)).thenReturn(mockQuery); + + mockManagementService = mock(ManagementService.class); + when(mockManagementService.createJobQuery()).thenReturn(mockQuery); + + mockSetJobRetriesByJobsAsyncBuilder = MockProvider.createMockSetJobRetriesByJobsAsyncBuilder(mockManagementService); + + mockSetJobRetriesBuilder = MockProvider.createMockSetJobRetriesBuilder(mockManagementService); + + mockSuspensionStateSelectBuilder = mock(UpdateJobSuspensionStateSelectBuilder.class); + when(mockManagementService.updateJobSuspensionState()).thenReturn(mockSuspensionStateSelectBuilder); + + mockSuspensionStateBuilder = mock(UpdateJobSuspensionStateTenantBuilder.class); + when(mockSuspensionStateSelectBuilder.byJobId(anyString())).thenReturn(mockSuspensionStateBuilder); + when(mockSuspensionStateSelectBuilder.byJobDefinitionId(anyString())).thenReturn(mockSuspensionStateBuilder); + when(mockSuspensionStateSelectBuilder.byProcessInstanceId(anyString())).thenReturn(mockSuspensionStateBuilder); + when(mockSuspensionStateSelectBuilder.byProcessDefinitionId(anyString())).thenReturn(mockSuspensionStateBuilder); + when(mockSuspensionStateSelectBuilder.byProcessDefinitionKey(anyString())).thenReturn(mockSuspensionStateBuilder); + + namedProcessEngine = getProcessEngine(MockProvider.EXAMPLE_PROCESS_ENGINE_NAME); + when(namedProcessEngine.getManagementService()).thenReturn(mockManagementService); + } + + @Test + public void testSetRetries() { + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_RESOURCE_SET_RETRIES_URL); + + verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder).jobId(MockProvider.EXAMPLE_JOB_ID); + verify(mockSetJobRetriesBuilder).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetRetriesWithDueDate() { + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + Date newDueDate = new Date(1675752840000L); + retriesVariableJson.put("dueDate", newDueDate); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_RESOURCE_SET_RETRIES_URL); + + verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder).jobId(MockProvider.EXAMPLE_JOB_ID); + verify(mockSetJobRetriesBuilder).dueDate(newDueDate); + verify(mockSetJobRetriesBuilder).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetRetriesWithNullDueDate() { + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + retriesVariableJson.put("dueDate", null); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_RESOURCE_SET_RETRIES_URL); + + verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder).jobId(MockProvider.EXAMPLE_JOB_ID); + verify(mockSetJobRetriesBuilder).dueDate(null); + verify(mockSetJobRetriesBuilder).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetRetriesNonExistentJob() { + String expectedMessage = "No job found with id '" + MockProvider.NON_EXISTING_JOB_ID + "'."; + + doThrow(new ProcessEngineException(expectedMessage)).when(mockSetJobRetriesBuilder).execute(); + + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_JOB_RETRIES); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_RESOURCE_SET_RETRIES_URL); + + verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_JOB_RETRIES); + verify(mockSetJobRetriesBuilder).jobId(MockProvider.NON_EXISTING_JOB_ID); + verify(mockSetJobRetriesBuilder).execute(); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetRetriesNegativeRetries() { + + String expectedMessage = "The number of job retries must be a non-negative Integer, but '" + MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES + + "' has been provided."; + + doThrow(new ProcessEngineException(expectedMessage)).when(mockManagementService).setJobRetries(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(retriesVariableJson) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .put(JOB_RESOURCE_SET_RETRIES_URL); + + verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetRetriesThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(mockManagementService).setJobRetries(anyInt()); + + Map retriesVariableJson = new HashMap<>(); + retriesVariableJson.put("retries", MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON).body(retriesVariableJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(JOB_RESOURCE_SET_RETRIES_URL); + + verify(mockManagementService).setJobRetries(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSimpleJobGet() { + given().pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_JOB_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("executionId", equalTo(MockProvider.EXAMPLE_EXECUTION_ID)) + .body("exceptionMessage", equalTo(MockProvider.EXAMPLE_JOB_NO_EXCEPTION_MESSAGE)) + .body("failedActivityId", equalTo(MockProvider.EXAMPLE_JOB_FAILED_ACTIVITY_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_JOB_PRIORITY)) + .body("jobDefinitionId", equalTo(MockProvider.EXAMPLE_JOB_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("createTime", equalTo(MockProvider.EXAMPLE_JOB_CREATE_TIME)) + .body("batchId", equalTo(MockProvider.EXAMPLE_BATCH_ID)) + .when() + .get(SINGLE_JOB_RESOURCE_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).jobId(MockProvider.EXAMPLE_JOB_ID); + inOrder.verify(mockQuery).singleResult(); + } + + @Test + public void testJobGetIdDoesntExist() { + JobQuery invalidQueryNonExistingJob; + invalidQueryNonExistingJob = mock(JobQuery.class); + when(mockManagementService.createJobQuery().jobId(MockProvider.NON_EXISTING_JOB_ID)).thenReturn(invalidQueryNonExistingJob); + when(invalidQueryNonExistingJob.singleResult()).thenReturn(null); + + String jobId = MockProvider.NON_EXISTING_JOB_ID; + + given() + .pathParam("id", jobId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Job with id " + jobId + " does not exist")) + .when() + .get(SINGLE_JOB_RESOURCE_URL); + } + + @Test + public void testExecuteJob() { + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(JOB_RESOURCE_EXECUTE_JOB_URL); + + verify(mockManagementService).executeJob(MockProvider.EXAMPLE_JOB_ID); + } + + @Test + public void testExecuteJobIdDoesntExist() { + String jobId = MockProvider.NON_EXISTING_JOB_ID; + + String expectedMessage = "No job found with id '" + jobId + "'"; + + doThrow(new ProcessEngineException(expectedMessage)).when(mockManagementService).executeJob(MockProvider.NON_EXISTING_JOB_ID); + + given().pathParam("id", jobId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())).body("message", equalTo(expectedMessage)) + .when().post(JOB_RESOURCE_EXECUTE_JOB_URL); + } + + @Test + public void testExecuteJobRuntimeException() { + String jobId = MockProvider.EXAMPLE_JOB_ID; + + doThrow(new RuntimeException("Runtime exception")).when(mockManagementService).executeJob(jobId); + + given().pathParam("id", jobId) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())).body("message", equalTo("Runtime exception")) + .when().post(JOB_RESOURCE_EXECUTE_JOB_URL); + } + + @Test + public void testExecuteJobThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(mockManagementService).executeJob(anyString()); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(JOB_RESOURCE_EXECUTE_JOB_URL); + } + + @Test + public void testGetStacktrace() { + String stacktrace = "aStacktrace"; + when(mockManagementService.getJobExceptionStacktrace(MockProvider.EXAMPLE_JOB_ID)).thenReturn(stacktrace); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect().statusCode(Status.OK.getStatusCode()).contentType(ContentType.TEXT) + .when().get(JOB_RESOURCE_GET_STACKTRACE_URL); + + String content = response.asString(); + Assert.assertEquals(stacktrace, content); + } + + @Test + public void testGetStacktraceJobNotFound() { + String exceptionMessage = "job not found"; + doThrow(new ProcessEngineException(exceptionMessage)).when(mockManagementService).getJobExceptionStacktrace(MockProvider.EXAMPLE_JOB_ID); + + given().pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when().get(JOB_RESOURCE_GET_STACKTRACE_URL); + } + + @Test + public void testGetStacktraceJobThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(mockManagementService).getJobExceptionStacktrace(MockProvider.EXAMPLE_JOB_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(JOB_RESOURCE_GET_STACKTRACE_URL); + } + + @Test + public void testSetJobDuedate() { + Date newDuedate = MockProvider.createMockDuedate(); + Map duedateVariableJson = new HashMap<>(); + duedateVariableJson.put("duedate", newDuedate); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(duedateVariableJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_RESOURCE_SET_DUEDATE_URL); + + verify(mockManagementService).setJobDuedate(MockProvider.EXAMPLE_JOB_ID, newDuedate, false); + } + + @Test + public void testSetJobDuedateNull() { + Map duedateVariableJson = new HashMap<>(); + duedateVariableJson.put("duedate", null); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(duedateVariableJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_RESOURCE_SET_DUEDATE_URL); + + verify(mockManagementService).setJobDuedate(MockProvider.EXAMPLE_JOB_ID, null, false); + } + + @Test + public void testSetJobDuedateCascade() { + Date newDuedate = MockProvider.createMockDuedate(); + Map duedateVariableJson = new HashMap<>(); + duedateVariableJson.put("duedate", newDuedate); + duedateVariableJson.put("cascade", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(duedateVariableJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_RESOURCE_SET_DUEDATE_URL); + + verify(mockManagementService).setJobDuedate(MockProvider.EXAMPLE_JOB_ID, newDuedate, true); + } + + @Test + public void testSetJobDuedateNullCascade() { + Map duedateVariableJson = new HashMap<>(); + duedateVariableJson.put("duedate", null); + duedateVariableJson.put("cascade", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(duedateVariableJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_RESOURCE_SET_DUEDATE_URL); + + verify(mockManagementService).setJobDuedate(MockProvider.EXAMPLE_JOB_ID, null, true); + } + + @Test + public void testSetJobDuedateNonExistentJob() { + Date newDuedate = MockProvider.createMockDuedate(); + String expectedMessage = "No job found with id '" + MockProvider.NON_EXISTING_JOB_ID + "'."; + + doThrow(new ProcessEngineException(expectedMessage)).when(mockManagementService).setJobDuedate(MockProvider.NON_EXISTING_JOB_ID, + newDuedate, false); + + Map duedateVariableJson = new HashMap<>(); + duedateVariableJson.put("duedate", newDuedate); + + given().pathParam("id", MockProvider.NON_EXISTING_JOB_ID).contentType(ContentType.JSON) + .body(duedateVariableJson).then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when().put(JOB_RESOURCE_SET_DUEDATE_URL); + + verify(mockManagementService).setJobDuedate(MockProvider.NON_EXISTING_JOB_ID, newDuedate, false); + } + + @Test + public void testSetJobDuedateThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(mockManagementService).setJobDuedate(anyString(), any(Date.class), anyBoolean()); + + Date newDuedate = MockProvider.createMockDuedate(); + Map duedateVariableJson = new HashMap<>(); + duedateVariableJson.put("duedate", newDuedate); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(duedateVariableJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(JOB_RESOURCE_SET_DUEDATE_URL); + } + + @Test + public void testActivateJob() { + JobSuspensionStateDto dto = new JobSuspensionStateDto(); + dto.setSuspended(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobId(MockProvider.EXAMPLE_JOB_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateThrowsProcessEngineException() { + JobSuspensionStateDto dto = new JobSuspensionStateDto(); + dto.setSuspended(false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_SUSPENDED_URL); + } + + @Test + public void testActivateThrowsAuthorizationException() { + JobSuspensionStateDto dto = new JobSuspensionStateDto(); + dto.setSuspended(false); + + String expectedMessage = "expectedMessage"; + + doThrow(new AuthorizationException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJob() { + JobSuspensionStateDto dto = new JobSuspensionStateDto(); + dto.setSuspended(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobId(MockProvider.EXAMPLE_JOB_ID); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendedThrowsProcessEngineException() { + JobSuspensionStateDto dto = new JobSuspensionStateDto(); + dto.setSuspended(true); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendWithMultipleByParameters() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "Only one of jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(SINGLE_JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendThrowsAuthorizationException() { + JobSuspensionStateDto dto = new JobSuspensionStateDto(); + dto.setSuspended(true); + + String expectedMessage = "expectedMessage"; + + doThrow(new AuthorizationException(expectedMessage)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobByProcessDefinitionKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByProcessDefinitionKeyThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobByProcessDefinitionKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByProcessDefinitionKeyThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByProcessDefinitionKeyAndTenantId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobByProcessDefinitionKeyWithoutTenantId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionWithoutTenantId", true); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionWithoutTenantId(); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testSuspendJobByProcessDefinitionKeyAndTenantId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobByProcessDefinitionKeyWithoutTenantId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionWithoutTenantId", true); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockSuspensionStateBuilder).processDefinitionWithoutTenantId(); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testActivateJobByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobByProcessDefinitionIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByProcessDefinitionIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobByProcessDefinitionIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByProcessDefinitionIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByProcessInstanceId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobByProcessInstanceIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByProcessInstanceIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByProcessInstanceId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobByProcessInstanceIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByProcessInstanceIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByJobDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateJobByJobDefinitionIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByJobDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(JOB_SUSPENDED_URL); + + verify(mockSuspensionStateSelectBuilder).byJobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendJobByJobDefinitionIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new AuthorizationException(expectedException)) + .when(mockSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testActivateJobByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("jobId", MockProvider.EXAMPLE_JOB_ID); + + String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("jobId", MockProvider.EXAMPLE_JOB_ID); + + String message = "Either jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey can be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSuspendJobByNothing() { + Map params = new HashMap<>(); + params.put("suspended", true); + + String message = "Either jobId, jobDefinitionId, processInstanceId, processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(JOB_SUSPENDED_URL); + } + + @Test + public void testSetJobPriority() { + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(JOB_RESOURCE_SET_PRIORITY_URL); + + verify(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY); + } + + @Test + public void testSetJobPriorityToExtremeValue() { + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", Long.MAX_VALUE); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(JOB_RESOURCE_SET_PRIORITY_URL); + + verify(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, Long.MAX_VALUE); + } + + @Test + public void testSetJobPriorityNonExistentJob() { + String expectedMessage = "No job found with id '" + MockProvider.NON_EXISTING_JOB_ID + "'."; + + doThrow(new NotFoundException(expectedMessage)) + .when(mockManagementService).setJobPriority(MockProvider.NON_EXISTING_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY); + + given() + .pathParam("id", MockProvider.NON_EXISTING_JOB_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when().put(JOB_RESOURCE_SET_PRIORITY_URL); + + verify(mockManagementService).setJobPriority(MockProvider.NON_EXISTING_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY); + } + + @Test + public void testSetJobPriorityFailure() { + String expectedMessage = "No job found with id '" + MockProvider.EXAMPLE_JOB_ID + "'."; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when().put(JOB_RESOURCE_SET_PRIORITY_URL); + + verify(mockManagementService).setJobPriority(MockProvider.EXAMPLE_JOB_ID, MockProvider.EXAMPLE_JOB_PRIORITY); + } + + @Test + public void testSetNullJobPriorityFailure() { + String expectedMessage = "Priority for job '" + MockProvider.EXAMPLE_JOB_ID + "' cannot be null."; + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", null); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when().put(JOB_RESOURCE_SET_PRIORITY_URL); + + verifyNoMoreInteractions(mockManagementService); + } + + @Test + public void testSetJobPriorityThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)) + .when(mockManagementService).setJobPriority(any(), anyLong()); + + Map priorityJson = new HashMap<>(); + priorityJson.put("priority", MockProvider.EXAMPLE_JOB_PRIORITY); + + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .contentType(ContentType.JSON) + .body(priorityJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(JOB_RESOURCE_SET_PRIORITY_URL); + } + + @Test + public void deleteJob() { + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_JOB_RESOURCE_URL); + + verify(mockManagementService).deleteJob(MockProvider.EXAMPLE_JOB_ID); + verifyNoMoreInteractions(mockManagementService); + } + + @Test + public void deleteNotExistingJob() { + String jobId = MockProvider.NON_EXISTING_JOB_ID; + + String expectedMessage = "No job found with id '" + jobId + "'."; + + doThrow(new NullValueException(expectedMessage)) + .when(mockManagementService).deleteJob(jobId); + + given() + .pathParam("id", jobId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .delete(SINGLE_JOB_RESOURCE_URL); + + verify(mockManagementService).deleteJob(jobId); + verifyNoMoreInteractions(mockManagementService); + } + + @Test + public void deleteLockedJob() { + String jobId = MockProvider.EXAMPLE_JOB_ID; + + String expectedMessage = "Cannot delete job when the job is being executed. Try again later."; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockManagementService).deleteJob(jobId); + + given() + .pathParam("id", jobId) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo(expectedMessage)) + .when() + .delete(SINGLE_JOB_RESOURCE_URL); + + verify(mockManagementService).deleteJob(jobId); + verifyNoMoreInteractions(mockManagementService); + } + + @Test + public void deleteJobThrowAuthorizationException() { + String jobId = MockProvider.EXAMPLE_JOB_ID; + + String expectedMessage = "Missing permissions"; + + doThrow(new AuthorizationException(expectedMessage)) + .when(mockManagementService).deleteJob(jobId); + + given() + .pathParam("id", jobId) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .delete(SINGLE_JOB_RESOURCE_URL); + + verify(mockManagementService).deleteJob(jobId); + verifyNoMoreInteractions(mockManagementService); + } + + @Test + public void testSetRetriesByJobsAsync() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("jobIds", ids); + messageBodyJson.put(RETRIES, 5); + + Response response = + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_SET_RETRIES_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByJobsAsync(5); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobIds(eq(ids)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobQuery(null); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByJobsAsyncBuilder); + } + + @Test + public void testSetRetriesAsyncWithDueDate() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("jobIds", ids); + Date newDueDate = new Date(1675752840000L); + messageBodyJson.put("dueDate", newDueDate); + messageBodyJson.put(RETRIES, 5); + + Response response = + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_SET_RETRIES_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByJobsAsync(eq(5)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobIds(eq(ids)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobQuery(null); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).dueDate(newDueDate); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByJobsAsyncBuilder); + } + + @Test + public void testSetRetriesAsyncWithNullDueDate() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("jobIds", ids); + messageBodyJson.put("dueDate", null); + messageBodyJson.put(RETRIES, 5); + + Response response = + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_SET_RETRIES_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByJobsAsync(eq(5)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobIds(eq(ids)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobQuery(null); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).dueDate(null); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByJobsAsyncBuilder); + } + @Test + public void testSetRetriesAsyncWithQuery() { + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, 5); + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + messageBodyJson.put("jobQuery", query); + + Response response = + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_SET_RETRIES_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByJobsAsync(5); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobIds(null); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobQuery(any(JobQuery.class)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByJobsAsyncBuilder); + } + + + @Test + public void testSetRetriesAsyncWithCreateTimesQuery() { + Map messageBodyJson = new HashMap(); + messageBodyJson.put(RETRIES, 5); + Map condition = new HashMap(); + condition.put("operator", "lt"); + condition.put("value", "2022-12-15T10:45:00.000+0100"); + Map jobQueryDto = new HashMap(); + jobQueryDto.put("createTimes", Arrays.asList(condition)); + messageBodyJson.put("jobQuery", jobQueryDto); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(JOBS_SET_RETRIES_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByJobsAsync(5); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobIds(null); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobQuery(any(JobQuery.class)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByJobsAsyncBuilder); + } + + + @Test + public void testSetRetriesAsyncWithDueDatesQuery() { + Map messageBodyJson = new HashMap(); + messageBodyJson.put(RETRIES, 5); + Map condition = new HashMap(); + condition.put("operator", "lt"); + condition.put("value", "2022-12-15T10:45:00.000+0100"); + Map jobQueryDto = new HashMap(); + jobQueryDto.put("dueDates", Arrays.asList(condition)); + messageBodyJson.put("jobQuery", jobQueryDto); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(JOBS_SET_RETRIES_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByJobsAsync(5); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobIds(null); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).jobQuery(any(JobQuery.class)); + verify(mockSetJobRetriesByJobsAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByJobsAsyncBuilder); + } + + + @Test + public void testSetRetriesWithBadRequestQuery() { + doThrow(new BadUserRequestException("job ids are empty")) + .when(mockSetJobRetriesByJobsAsyncBuilder).jobQuery(eq((JobQuery) null)); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, 5); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(JOBS_SET_RETRIES_URL); + } + + @Test + public void testSetRetriesWithoutBody() { + given() + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(JOBS_SET_RETRIES_URL); + + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testSetRetriesWithNegativeRetries() { + doThrow(new BadUserRequestException("retries are negative")) + .when(mockManagementService).setJobRetriesByJobsAsync(eq(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES)); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + JobQueryDto query = new JobQueryDto(); + messageBodyJson.put("jobQuery", query); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(JOBS_SET_RETRIES_URL); + } + + @Test + public void testSetRetriesWithoutRetries() { + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("jobIds", null); + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(JOBS_SET_RETRIES_URL); + + verifyNoMoreInteractions(mockSetJobRetriesBuilder); + } + + @Test + public void testRecalculateDuedateWithoutDateBase() { + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(JOB_RESOURCE_RECALC_DUEDATE_URL); + + verify(mockManagementService).recalculateJobDuedate(MockProvider.EXAMPLE_JOB_ID, true); + } + + @Test + public void testRecalculateDuedateCreationDateBased() { + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .queryParam("creationDateBased", true) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(JOB_RESOURCE_RECALC_DUEDATE_URL); + + verify(mockManagementService).recalculateJobDuedate(MockProvider.EXAMPLE_JOB_ID, true); + } + + @Test + public void testRecalculateDuedateCurrentDateBased() { + given() + .pathParam("id", MockProvider.EXAMPLE_JOB_ID) + .queryParam("creationDateBased", false) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(JOB_RESOURCE_RECALC_DUEDATE_URL); + + verify(mockManagementService).recalculateJobDuedate(MockProvider.EXAMPLE_JOB_ID, false); + } + + @Test + public void testRecalculateDuedateWithUnknownJobId() { + String jobId = MockProvider.NON_EXISTING_JOB_ID; + + String expectedMessage = "No job found with id '" + jobId + "'."; + + doThrow(new NotFoundException(expectedMessage)) + .when(mockManagementService).recalculateJobDuedate(jobId, true); + + given() + .pathParam("id", jobId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when().post(JOB_RESOURCE_RECALC_DUEDATE_URL); + + verify(mockManagementService).recalculateJobDuedate(jobId, true); + verifyNoMoreInteractions(mockManagementService); + } + + @Test + public void testRecalculateDuedateUnauthorized() { + String jobId = MockProvider.EXAMPLE_JOB_ID; + + String expectedMessage = "Missing permissions"; + + doThrow(new AuthorizationException(expectedMessage)) + .when(mockManagementService).recalculateJobDuedate(jobId, true); + + given() + .pathParam("id", jobId) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when().post(JOB_RESOURCE_RECALC_DUEDATE_URL); + + verify(mockManagementService).recalculateJobDuedate(jobId, true); + verifyNoMoreInteractions(mockManagementService); + } + + protected void verifyBatchJson(String batchJson) { + BatchDto batch = JsonPathUtil.from(batchJson).getObject("", BatchDto.class); + assertNotNull("The returned batch should not be null.", batch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..07de7257ba779baa30715a75461c594ecd2d8277 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/JobRestServiceQueryTest.java @@ -0,0 +1,996 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.Job; +import org.camunda.bpm.engine.runtime.JobQuery; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class JobRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String JOBS_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/job"; + protected static final String JOBS_QUERY_COUNT_URL = JOBS_RESOURCE_URL + "/count"; + + private JobQuery mockQuery; + private static final int MAX_RESULTS_TEN = 10; + private static final int FIRST_RESULTS_ZERO = 0; + protected static final long JOB_QUERY_MAX_PRIORITY = Long.MAX_VALUE; + protected static final long JOB_QUERY_MIN_PRIORITY = Long.MIN_VALUE; + + @Before + public void setUpRuntimeData() { + mockQuery = setUpMockJobQuery(MockProvider.createMockJobs()); + } + + private JobQuery setUpMockJobQuery(List mockedJobs) { + JobQuery sampleJobQuery = mock(JobQuery.class); + + when(sampleJobQuery.list()).thenReturn(mockedJobs); + when(sampleJobQuery.count()).thenReturn((long) mockedJobs.size()); + + when(processEngine.getManagementService().createJobQuery()).thenReturn(sampleJobQuery); + + return sampleJobQuery; + } + + @Test + public void testEmptyQuery() { + String queryJobId = ""; + given().queryParam("id", queryJobId).then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(JOBS_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()) + .when().get(JOBS_RESOURCE_URL); + + verify(mockQuery).list(); + verifyNoMoreInteractions(mockQuery); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "jobDueDate") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(JOBS_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(JOBS_RESOURCE_URL); + } + + @Test + public void testSimpleJobQuery() { + String jobId = MockProvider.EXAMPLE_JOB_ID; + + Response response = given().queryParam("jobId", jobId).then().expect() + .statusCode(Status.OK.getStatusCode()).when() + .get(JOBS_RESOURCE_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).jobId(jobId); + inOrder.verify(mockQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one job returned.", 1, instances.size()); + Assert.assertNotNull("The returned job should not be null.", instances.get(0)); + + String returnedJobId = from(content).getString("[0].id"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedExceptionMessage = from(content).getString("[0].exceptionMessage"); + String returnedFailedActivityId = from(content).getString("[0].failedActivityId"); + int returnedRetries = from(content).getInt("[0].retries"); + Date returnedDueDate = DateTimeUtil.parseDate(from(content).getString("[0].dueDate")); + boolean returnedSuspended = from(content).getBoolean("[0].suspended"); + long returnedPriority = from(content).getLong("[0].priority"); + String returnedJobDefinitionId= from(content).getString("[0].jobDefinitionId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedCreateTime = from(content).getString("[0].createTime"); + String returnedBatchId = from(content).getString("[0].batchId"); + + Assert.assertEquals(MockProvider.EXAMPLE_JOB_ID, returnedJobId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_NO_EXCEPTION_MESSAGE, returnedExceptionMessage); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_FAILED_ACTIVITY_ID, returnedFailedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_RETRIES, returnedRetries); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_DUE_DATE), returnedDueDate); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_IS_SUSPENDED, returnedSuspended); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_PRIORITY, returnedPriority); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_DEFINITION_ID, returnedJobDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_JOB_CREATE_TIME, returnedCreateTime); + Assert.assertEquals(MockProvider.EXAMPLE_BATCH_ID, returnedBatchId); + } + + private interface DateParameters { + String name(); + + String description(); + + void expectLowerThan(JobQuery query, Date date); + + void expectHigherThan(JobQuery query, Date date); + } + + private static final DateParameters DUE_DATES = new DateParameters() { + @Override + public String name() { + return "dueDates"; + } + + @Override + public String description() { + return "due date"; + } + + @Override + public void expectLowerThan(JobQuery query, Date date) { + query.duedateLowerThan(date); + } + + @Override + public void expectHigherThan(JobQuery query, Date date) { + query.duedateHigherThan(date); + } + }; + + private static final DateParameters CREATE_TIMES = new DateParameters() { + @Override + public String name() { + return "createTimes"; + } + + @Override + public String description() { + return "create time"; + } + + @Override + public void expectLowerThan(JobQuery query, Date date) { + query.createdBefore(date); + } + + @Override + public void expectHigherThan(JobQuery query, Date date) { + query.createdAfter(date); + } + }; + + private void testInvalidDateComparator(DateParameters parameters) { + + String variableValue = withTimezone("2013-05-05T00:00:00"); + String invalidComparator = "bt"; + + String queryValue = invalidComparator + "_" + variableValue; + given().queryParam(parameters.name(), queryValue).then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Invalid " + parameters.description() + " comparator specified: " + invalidComparator)).when().get(JOBS_RESOURCE_URL); + } + + private void testInvalidDateComparatorAsPost(DateParameters parameters) { + String invalidComparator = "bt"; + + Map conditionJson = new HashMap<>(); + conditionJson.put("operator", invalidComparator); + conditionJson.put("value", withTimezone("2013-05-05T00:00:00")); + + List> conditions = new ArrayList<>(); + conditions.add(conditionJson); + + Map json = new HashMap<>(); + json.put(parameters.name(), conditions); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json).then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Invalid " + parameters.description() + " comparator specified: " + invalidComparator)).when().post(JOBS_RESOURCE_URL); + } + + private void testInvalidDate(DateParameters parameters) { + String variableValue = "invalidValue"; + String invalidComparator = "lt"; + + String queryValue = invalidComparator + "_" + variableValue; + given().queryParam(parameters.name(), queryValue).then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Invalid " + parameters.description() + " format: Cannot convert value \"invalidValue\" to java type java.util.Date")).when() + .get(JOBS_RESOURCE_URL); + } + + private void testInvalidDateAsPost(DateParameters parameters) { + Map conditionJson = new HashMap<>(); + conditionJson.put("operator", "lt"); + conditionJson.put("value", "invalidValue"); + + List> conditions = new ArrayList<>(); + conditions.add(conditionJson); + + Map json = new HashMap<>(); + json.put(parameters.name(), conditions); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json).then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Invalid " + parameters.description() + " format: Cannot convert value \"invalidValue\" to java type java.util.Date")).when() + .post(JOBS_RESOURCE_URL); + } + + @Test + public void testInvalidDueDateComparator() { + testInvalidDateComparator(DUE_DATES); + } + + @Test + public void testInvalidCreateTimeComparator() { + testInvalidDateComparator(CREATE_TIMES); + } + + @Test + public void testInvalidDueDateComperatorAsPost() { + testInvalidDateComparatorAsPost(DUE_DATES); + } + + @Test + public void testInvalidCreateTimeComparatorAsPost() { + testInvalidDateComparatorAsPost(CREATE_TIMES); + } + + @Test + public void testInvalidDueDate() { + testInvalidDate(DUE_DATES); + } + + @Test + public void testInvalidCreateTime() { + testInvalidDate(CREATE_TIMES); + } + + @Test + public void testInvalidDueDateAsPost() { + testInvalidDateAsPost(DUE_DATES); + } + + @Test + public void testInvalidCreateTimeAsPost() { + testInvalidDateAsPost(CREATE_TIMES); + } + + @Test + public void testAdditionalParametersExcludingDueDates() { + Map parameters = getCompleteParameters(); + + given().queryParams(parameters).then().expect() + .statusCode(Status.OK.getStatusCode()).when() + .get(JOBS_RESOURCE_URL); + + verifyParameterQueryInvocations(); + verify(mockQuery).list(); + } + + @Test + public void testMessagesParameter() { + Map parameters = new HashMap<>(); + parameters.put("messages", MockProvider.EXAMPLE_MESSAGES); + + given().queryParams(parameters) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(JOBS_RESOURCE_URL); + + verify(mockQuery).messages(); + verify(mockQuery).list(); + } + + @Test + public void testAcquiredParameter() { + Map parameters = new HashMap<>(); + parameters.put("acquired", MockProvider.EXAMPLE_ACQUIRED); + + given() + .queryParams(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOBS_RESOURCE_URL); + + verify(mockQuery).acquired(); + verify(mockQuery).list(); + } + + @Test + public void testAcquiredParameterAsPost() { + Map parameters = new HashMap<>(); + parameters.put("acquired", MockProvider.EXAMPLE_ACQUIRED); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_RESOURCE_URL); + } + + @Test + public void testMessagesTimersParameter() { + Map parameters = new HashMap<>(); + parameters.put("messages", MockProvider.EXAMPLE_MESSAGES); + parameters.put("timers", MockProvider.EXAMPLE_TIMERS); + + given().queryParams(parameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type",equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Parameter timers cannot be used together with parameter messages.")) + .when().get(JOBS_RESOURCE_URL); + } + + @Test + public void testMessagesTimersParameterAsPost() { + Map parameters = new HashMap<>(); + parameters.put("messages", MockProvider.EXAMPLE_MESSAGES); + parameters.put("timers", MockProvider.EXAMPLE_TIMERS); + + given().contentType(POST_JSON_CONTENT_TYPE).body(parameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type",equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Parameter timers cannot be used together with parameter messages.")) + .when().post(JOBS_RESOURCE_URL); + } + + @Test + public void testMessagesParameterAsPost() { + Map parameters = new HashMap<>(); + parameters.put("messages", MockProvider.EXAMPLE_MESSAGES); + + given().contentType(POST_JSON_CONTENT_TYPE).body(parameters) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOBS_RESOURCE_URL); + + verify(mockQuery).messages(); + verify(mockQuery).list(); + } + + private Map getCompleteParameters() { + Map parameters = new HashMap<>(); + + parameters.put("activityId", MockProvider.EXAMPLE_ACTIVITY_ID); + parameters.put("jobId", MockProvider.EXAMPLE_JOB_ID); + parameters.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + parameters.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + parameters.put("executionId", MockProvider.EXAMPLE_EXECUTION_ID); + parameters.put("withRetriesLeft", MockProvider.EXAMPLE_WITH_RETRIES_LEFT); + parameters.put("executable", MockProvider.EXAMPLE_EXECUTABLE); + parameters.put("timers", MockProvider.EXAMPLE_TIMERS); + parameters.put("withException", MockProvider.EXAMPLE_WITH_EXCEPTION); + parameters.put("exceptionMessage", MockProvider.EXAMPLE_EXCEPTION_MESSAGE); + parameters.put("failedActivityId", MockProvider.EXAMPLE_JOB_FAILED_ACTIVITY_ID); + parameters.put("noRetriesLeft", MockProvider.EXAMPLE_NO_RETRIES_LEFT); + parameters.put("active", true); + parameters.put("suspended", true); + parameters.put("priorityLowerThanOrEquals", JOB_QUERY_MAX_PRIORITY); + parameters.put("priorityHigherThanOrEquals", JOB_QUERY_MIN_PRIORITY); + parameters.put("jobDefinitionId", MockProvider.EXAMPLE_JOB_DEFINITION_ID); + parameters.put("acquired", MockProvider.EXAMPLE_ACQUIRED); + return parameters; + } + + @Test + public void testAdditionalParametersExcludingDueDatesAsPost() { + Map parameters = getCompleteParameters(); + + given().contentType(POST_JSON_CONTENT_TYPE).body(parameters) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOBS_RESOURCE_URL); + + verifyParameterQueryInvocations(); + verify(mockQuery).list(); + } + + + private void verifyParameterQueryInvocations() { + Map parameters = getCompleteParameters(); + + verify(mockQuery).jobId((String) parameters.get("jobId")); + verify(mockQuery).processInstanceId((String) parameters.get("processInstanceId")); + verify(mockQuery).processDefinitionId((String) parameters.get("processDefinitionId")); + verify(mockQuery).processDefinitionKey((String) parameters.get("processDefinitionKey")); + verify(mockQuery).executionId((String) parameters.get("executionId")); + verify(mockQuery).activityId((String) parameters.get("activityId")); + verify(mockQuery).withRetriesLeft(); + verify(mockQuery).executable(); + verify(mockQuery).timers(); + verify(mockQuery).withException(); + verify(mockQuery).exceptionMessage((String) parameters.get("exceptionMessage")); + verify(mockQuery).failedActivityId((String) parameters.get("failedActivityId")); + verify(mockQuery).noRetriesLeft(); + verify(mockQuery).active(); + verify(mockQuery).suspended(); + verify(mockQuery).priorityLowerThanOrEquals(JOB_QUERY_MAX_PRIORITY); + verify(mockQuery).priorityHigherThanOrEquals(JOB_QUERY_MIN_PRIORITY); + verify(mockQuery).jobDefinitionId(MockProvider.EXAMPLE_JOB_DEFINITION_ID); + verify(mockQuery).acquired(); + } + + private void testDateParameters(DateParameters parameters) { + String variableValue = withTimezone("2013-05-05T00:00:00"); + Date date = DateTimeUtil.parseDate(variableValue); + + String queryValue = "lt_" + variableValue; + given().queryParam(parameters.name(), queryValue).then().expect().statusCode(Status.OK.getStatusCode()).when().get(JOBS_RESOURCE_URL); + + InOrder inOrder = inOrder(mockQuery); + parameters.expectLowerThan(inOrder.verify(mockQuery), date); + inOrder.verify(mockQuery).list(); + + queryValue = "gt_" + variableValue; + given().queryParam(parameters.name(), queryValue).then().expect().statusCode(Status.OK.getStatusCode()).when().get(JOBS_RESOURCE_URL); + + inOrder = inOrder(mockQuery); + parameters.expectHigherThan(inOrder.verify(mockQuery), date); + inOrder.verify(mockQuery).list(); + } + + private void testDateParametersAsPost(DateParameters parameters) { + String value = withTimezone("2013-05-18T00:00:00"); + String anotherValue = withTimezone("2013-05-05T00:00:00"); + + Date date = DateTimeUtil.parseDate(value); + Date anotherDate = DateTimeUtil.parseDate(anotherValue); + + Map conditionJson = new HashMap<>(); + conditionJson.put("operator", "lt"); + conditionJson.put("value", value); + + Map anotherConditionJson = new HashMap<>(); + anotherConditionJson.put("operator", "gt"); + anotherConditionJson.put("value", anotherValue); + + List> conditions = new ArrayList<>(); + conditions.add(conditionJson); + conditions.add(anotherConditionJson); + + Map json = new HashMap<>(); + json.put(parameters.name(), conditions); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json).then().expect().statusCode(Status.OK.getStatusCode()).when().post(JOBS_RESOURCE_URL); + + parameters.expectHigherThan(verify(mockQuery), anotherDate); + parameters.expectLowerThan(verify(mockQuery), date); + } + + private void testMultipleDateParameters(DateParameters parameters) { + String variableValue1 = withTimezone("2012-05-05T00:00:00"); + String variableParameter1 = "gt_" + variableValue1; + + String variableValue2 = withTimezone("2013-02-02T00:00:00"); + String variableParameter2 = "lt_" + variableValue2; + + Date date = DateTimeUtil.parseDate(variableValue1); + Date anotherDate = DateTimeUtil.parseDate(variableValue2); + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam(parameters.name(), queryValue).then().expect().statusCode(Status.OK.getStatusCode()).when().get(JOBS_RESOURCE_URL); + + parameters.expectHigherThan(verify(mockQuery), date); + parameters.expectLowerThan(verify(mockQuery), anotherDate); + } + + @Test + public void testDueDateParameters() { + testDateParameters(DUE_DATES); + } + + @Test + public void testCreateTimeParameters() { + testDateParameters(CREATE_TIMES); + } + + @Test + public void testDueDateParametersAsPost() { + testDateParametersAsPost(DUE_DATES); + } + + @Test + public void testCreateTimeParametersAsPost() { + testDateParametersAsPost(CREATE_TIMES); + } + + @Test + public void testMultipleDueDateParameters() { + testMultipleDateParameters(DUE_DATES); + } + + @Test + public void testMultipleCreateTimeParameters() { + testMultipleDateParameters(CREATE_TIMES); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("jobId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByJobId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByProcessInstanceId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByExecutionId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("jobRetries", "asc", Status.OK); + inOrder.verify(mockQuery).orderByJobRetries(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("jobDueDate", "desc", Status.OK); + inOrder.verify(mockQuery).orderByJobDuedate(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("jobPriority", "asc", Status.OK); + inOrder.verify(mockQuery).orderByJobPriority(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTenantId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTenantId(); + inOrder.verify(mockQuery).desc(); + } + + private void executeAndVerifySorting(String sortBy, String sortOrder, + Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(JOBS_RESOURCE_URL); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockQuery); + Map json = new HashMap<>(); + json.put("sorting", OrderingBuilder.create() + .orderBy("jobRetries").desc() + .orderBy("jobDueDate").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(JOBS_RESOURCE_URL); + + inOrder.verify(mockQuery).orderByJobRetries(); + inOrder.verify(mockQuery).desc(); + inOrder.verify(mockQuery).orderByJobDuedate(); + inOrder.verify(mockQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = FIRST_RESULTS_ZERO; + int maxResults = MAX_RESULTS_TEN; + given().queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults).then().expect() + .statusCode(Status.OK.getStatusCode()).when() + .get(JOBS_RESOURCE_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + @Test + public void testQueryCount() { + given() + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(JOBS_QUERY_COUNT_URL); + + verify(mockQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(JOBS_QUERY_COUNT_URL); + + verify(mockQuery).count(); + } + + @Test + public void testTenantIdListParameter() { + mockQuery = setUpMockJobQuery(createMockJobsTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOBS_RESOURCE_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdParameter() { + Job mockJob = MockProvider.mockJob().tenantId(null).build(); + mockQuery = setUpMockJobQuery(Arrays.asList(mockJob)); + + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOBS_RESOURCE_URL); + + verify(mockQuery).withoutTenantId(); + verify(mockQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testIncludeJobsWithoutTenantIdParameter() { + List jobs = Arrays.asList( + MockProvider.mockJob().tenantId(null).build(), + MockProvider.mockJob().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockQuery = setUpMockJobQuery(jobs); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("includeJobsWithoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOBS_RESOURCE_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockQuery).includeJobsWithoutTenantId(); + verify(mockQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockQuery = setUpMockJobQuery(createMockJobsTwoTenants()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_RESOURCE_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdPostParameter() { + Job mockJob = MockProvider.mockJob().tenantId(null).build(); + mockQuery = setUpMockJobQuery(Arrays.asList(mockJob)); + + Map queryParameters = new HashMap<>(); + queryParameters.put("withoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_RESOURCE_URL); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testIncludeJobsWithoutTenantIdPostParameter() { + List jobs = Arrays.asList( + MockProvider.mockJob().tenantId(null).build(), + MockProvider.mockJob().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockQuery = setUpMockJobQuery(jobs); + + Map queryParameters = new HashMap<>(); + queryParameters.put("tenantIdIn", new String[] { MockProvider.EXAMPLE_TENANT_ID }); + queryParameters.put("includeJobsWithoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_RESOURCE_URL); + + verify(mockQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockQuery).includeJobsWithoutTenantId(); + verify(mockQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + private List createMockJobsTwoTenants() { + return Arrays.asList( + MockProvider.mockJob().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.mockJob().tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build()); + } + + @Test + public void testProcessInstanceIdListParameter() { + mockQuery = setUpMockJobQuery(createMockJobsTwoProcessInstances()); + + Response response = given() + .queryParam("processInstanceIds", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOBS_RESOURCE_URL); + + Set expectedIds = new HashSet<>(); + Collections.addAll(expectedIds, MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID); + verify(mockQuery).processInstanceIds(expectedIds); + verify(mockQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].processInstanceId"); + String returnedTenantId2 = from(content).getString("[1].processInstanceId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID); + } + + @Test + public void testProcessInstanceIdListPostParameter() { + mockQuery = setUpMockJobQuery(createMockJobsTwoProcessInstances()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("processInstanceIds", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_RESOURCE_URL); + + Set expectedIds = new HashSet<>(); + Collections.addAll(expectedIds, MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID); + verify(mockQuery).processInstanceIds(expectedIds); + verify(mockQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedProcessInstaneId1 = from(content).getString("[0].processInstanceId"); + String returnedProcessInstaneId2 = from(content).getString("[1].processInstanceId"); + + assertThat(returnedProcessInstaneId1).isEqualTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + assertThat(returnedProcessInstaneId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID); + } + + private List createMockJobsTwoProcessInstances() { + return Arrays.asList( + MockProvider.mockJob().processInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).build(), + MockProvider.mockJob().processInstanceId(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID).build()); + } + + @Test + public void testJobIdListParameter() { + mockQuery = setUpMockJobQuery(createMockJobsTwoJobIds()); + + Response response = given() + .queryParam("jobIds", MockProvider.EXAMPLE_JOB_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOBS_RESOURCE_URL); + + Set expectedIds = new HashSet<>(); + Collections.addAll(expectedIds, MockProvider.EXAMPLE_JOB_ID, MockProvider.ANOTHER_EXAMPLE_JOB_ID); + verify(mockQuery).jobIds(expectedIds); + verify(mockQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedJobId1 = from(content).getString("[0].id"); + String returnedJobId2 = from(content).getString("[1].id"); + + assertThat(returnedJobId1).isEqualTo(MockProvider.EXAMPLE_JOB_ID); + assertThat(returnedJobId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_JOB_ID); + } + + @Test + public void testJobIdListPostParameter() { + mockQuery = setUpMockJobQuery(createMockJobsTwoJobIds()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("jobIds", MockProvider.EXAMPLE_JOB_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(JOBS_RESOURCE_URL); + + Set expectedIds = new HashSet<>(); + Collections.addAll(expectedIds, MockProvider.EXAMPLE_JOB_ID, MockProvider.ANOTHER_EXAMPLE_JOB_ID); + verify(mockQuery).jobIds(expectedIds); + verify(mockQuery).list(); + + String content = response.asString(); + List jobs = from(content).getList(""); + assertThat(jobs).hasSize(2); + + String returnedJobId1 = from(content).getString("[0].id"); + String returnedJobId2 = from(content).getString("[1].id"); + + assertThat(returnedJobId1).isEqualTo(MockProvider.EXAMPLE_JOB_ID); + assertThat(returnedJobId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_JOB_ID); + } + + private List createMockJobsTwoJobIds() { + return Arrays.asList( + MockProvider.mockJob().build(), + MockProvider.mockJob().id(MockProvider.ANOTHER_EXAMPLE_JOB_ID).build()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MessageRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MessageRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d8519ed52af23e50be3f9c975c288499df126236 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MessageRestServiceTest.java @@ -0,0 +1,1362 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.MismatchingMessageCorrelationException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.EqualsMap; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import java.util.ArrayList; +import java.util.List; +import junit.framework.Assert; +import org.camunda.bpm.engine.runtime.MessageCorrelationResult; +import org.camunda.bpm.engine.runtime.MessageCorrelationResultType; +import org.camunda.bpm.engine.runtime.MessageCorrelationResultWithVariables; +import org.camunda.bpm.engine.variable.type.ValueType; + +import static org.mockito.Mockito.when; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class MessageRestServiceTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String MESSAGE_URL = TEST_RESOURCE_ROOT_PATH + MessageRestService.PATH; + + private RuntimeService runtimeServiceMock; + private MessageCorrelationBuilder messageCorrelationBuilderMock; + private MessageCorrelationResult executionResult; + private MessageCorrelationResult procInstanceResult; + private List executionResultList; + private List procInstanceResultList; + private List mixedResultList; + + private MessageCorrelationResultWithVariables executionResultWithVariables; + private List execResultWithVariablesList; + + @Before + public void setupMocks() { + runtimeServiceMock = mock(RuntimeService.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + + messageCorrelationBuilderMock = mock(MessageCorrelationBuilder.class); + + when(runtimeServiceMock.createMessageCorrelation(anyString())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.processInstanceId(anyString())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.processInstanceBusinessKey(anyString())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.processInstanceVariableEquals(anyString(), any())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.setVariables(Mockito.any())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.setVariable(anyString(), any())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.setVariablesLocal(Mockito.any())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.setVariableLocal(anyString(), any())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.setVariablesToTriggeredScope(Mockito.any())).thenReturn(messageCorrelationBuilderMock); + when(messageCorrelationBuilderMock.setVariableToTriggeredScope(anyString(), any())).thenReturn(messageCorrelationBuilderMock); + + executionResult = MockProvider.createMessageCorrelationResult(MessageCorrelationResultType.Execution); + procInstanceResult = MockProvider.createMessageCorrelationResult(MessageCorrelationResultType.ProcessDefinition); + executionResultList = MockProvider.createMessageCorrelationResultList(MessageCorrelationResultType.Execution); + procInstanceResultList = MockProvider.createMessageCorrelationResultList(MessageCorrelationResultType.ProcessDefinition); + mixedResultList = new ArrayList<>(executionResultList); + mixedResultList.addAll(procInstanceResultList); + + executionResultWithVariables = MockProvider.createMessageCorrelationResultWithVariables(MessageCorrelationResultType.Execution); + execResultWithVariablesList = new ArrayList<>(); + execResultWithVariablesList.add(executionResultWithVariables); + + } + + @Test + public void testFullMessageCorrelation() { + String messageName = "aMessageName"; + String businessKey = "aBusinessKey"; + Map variables = VariablesBuilder.create().variable("aKey", "aValue").getVariables(); + Map variablesLocal = VariablesBuilder.create().variable("aKeyLocal", "aValueLocal").getVariables(); + Map variablesToTriggeredScope = VariablesBuilder.create().variable("aKeyToTriggeredScope", "aValueToTriggeredScope").getVariables(); + + Map correlationKeys = VariablesBuilder.create() + .variable("aKey", "aValue") + .variable("anotherKey", 1) + .variable("aThirdKey", true).getVariables(); + + Map localCorrelationKeys = VariablesBuilder.create() + .variable("aLocalKey", "aValue") + .variable("anotherLocalKey", 1) + .variable("aThirdLocalKey", false).getVariables(); + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", correlationKeys); + messageParameters.put("localCorrelationKeys", localCorrelationKeys); + messageParameters.put("processVariables", variables); + messageParameters.put("processVariablesLocal", variablesLocal); + messageParameters.put("processVariablesToTriggeredScope", variablesToTriggeredScope); + messageParameters.put("businessKey", businessKey); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + Map expectedCorrelationKeys = new HashMap<>(); + expectedCorrelationKeys.put("aKey", "aValue"); + expectedCorrelationKeys.put("anotherKey", 1); + expectedCorrelationKeys.put("aThirdKey", true); + + Map expectedLocalCorrelationKeys = new HashMap<>(); + expectedLocalCorrelationKeys.put("aLocalKey", "aValue"); + expectedLocalCorrelationKeys.put("anotherLocalKey", 1); + expectedLocalCorrelationKeys.put("aThirdLocalKey", false); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aKey", "aValue"); + Map expectedVariablesLocal = new HashMap<>(); + expectedVariablesLocal.put("aKeyLocal", "aValueLocal"); + Map expectedVariablesToTriggeredScope = new HashMap<>(); + expectedVariablesToTriggeredScope.put("aKeyToTriggeredScope", "aValueToTriggeredScope"); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).processInstanceBusinessKey(eq(businessKey)); + verify(messageCorrelationBuilderMock).setVariables(argThat(new EqualsMap(expectedVariables))); + verify(messageCorrelationBuilderMock).setVariablesLocal(argThat(new EqualsMap(expectedVariablesLocal))); + verify(messageCorrelationBuilderMock).setVariablesToTriggeredScope(argThat(new EqualsMap(expectedVariablesToTriggeredScope))); + + for (Entry expectedKey : expectedCorrelationKeys.entrySet()) { + String name = expectedKey.getKey(); + Object value = expectedKey.getValue(); + verify(messageCorrelationBuilderMock).processInstanceVariableEquals(name, value); + } + + for (Entry expectedLocalKey : expectedLocalCorrelationKeys.entrySet()) { + String name = expectedLocalKey.getKey(); + Object value = expectedLocalKey.getValue(); + verify(messageCorrelationBuilderMock).localVariableEquals(name, value); + } + + verify(messageCorrelationBuilderMock).correlateWithResult(); + } + + @Test + public void testFullMessageCorrelationWithExecutionResult() { + //given + when(messageCorrelationBuilderMock.correlateWithResult()).thenReturn(executionResult); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("resultEnabled", true); + + //when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + //then + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + checkExecutionResult(content, 0); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateWithResult(); + } + + protected void checkExecutionResult(String content, int idx) { + //resultType should be execution + String resultType = from(content).get("[" + idx + "].resultType").toString(); + assertEquals(MessageCorrelationResultType.Execution.name(), resultType); + //execution should be filled and process instance should be null + assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, from(content).get("[" + idx + "].execution.id")); + assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, from(content).get("[" + idx + "].execution.processInstanceId")); + assertNull(from(content).get("[" + idx + "].processInstance")); + } + + @Test + public void testFullMessageCorrelationWithProcessDefinitionResult() { + //given + when(messageCorrelationBuilderMock.correlateWithResult()).thenReturn(procInstanceResult); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("resultEnabled", true); + + //when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + //then + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + checkProcessInstanceResult(content, 0); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateWithResult(); + } + + protected void checkProcessInstanceResult(String content, int idx) { + //resultType should be set to process definition + String resultType = from(content).get("[" + idx + "].resultType"); + Assert.assertEquals(MessageCorrelationResultType.ProcessDefinition.name(), resultType); + + //process instance should be filled and execution should be null + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, from(content).get("[" + idx + "].processInstance.id")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, from(content).get("[" + idx + "].processInstance.definitionId")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, from(content).get("[" + idx + "].processInstance.definitionKey")); + Assert.assertNull(from(content).get("[" + idx + "].execution")); + } + + @Test + public void testFullMessageCorrelationAll() { + String messageName = "aMessageName"; + String businessKey = "aBusinessKey"; + Map variables = VariablesBuilder.create().variable("aKey", "aValue").getVariables(); + Map variablesLocal = VariablesBuilder.create().variable("aKeyLocal", "aValueLocal").getVariables(); + Map variablesToTriggeredScope = VariablesBuilder.create().variable("aKeyToTriggeredScope", "aValueToTriggeredScope").getVariables(); + + Map correlationKeys = VariablesBuilder.create() + .variable("aKey", "aValue") + .variable("anotherKey", 1) + .variable("aThirdKey", true).getVariables(); + + Map localCorrelationKeys = VariablesBuilder.create() + .variable("aLocalKey", "aValue") + .variable("anotherLocalKey", 1) + .variable("aThirdLocalKey", false).getVariables(); + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", correlationKeys); + messageParameters.put("localCorrelationKeys", localCorrelationKeys); + messageParameters.put("processVariables", variables); + messageParameters.put("processVariablesLocal", variablesLocal); + messageParameters.put("processVariablesToTriggeredScope", variablesToTriggeredScope); + messageParameters.put("businessKey", businessKey); + messageParameters.put("all", true); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + Map expectedCorrelationKeys = new HashMap<>(); + expectedCorrelationKeys.put("aKey", "aValue"); + expectedCorrelationKeys.put("anotherKey", 1); + expectedCorrelationKeys.put("aThirdKey", true); + + Map expectedLocalCorrelationKeys = new HashMap<>(); + expectedLocalCorrelationKeys.put("aLocalKey", "aValue"); + expectedLocalCorrelationKeys.put("anotherLocalKey", 1); + expectedLocalCorrelationKeys.put("aThirdLocalKey", false); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aKey", "aValue"); + Map expectedVariablesLocal = new HashMap<>(); + expectedVariablesLocal.put("aKeyLocal", "aValueLocal"); + Map expectedVariablesToTriggeredScope = new HashMap<>(); + expectedVariablesToTriggeredScope.put("aKeyToTriggeredScope", "aValueToTriggeredScope"); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).processInstanceBusinessKey(eq(businessKey)); + verify(messageCorrelationBuilderMock).setVariables(argThat(new EqualsMap(expectedVariables))); + verify(messageCorrelationBuilderMock).setVariablesLocal(argThat(new EqualsMap(expectedVariablesLocal))); + verify(messageCorrelationBuilderMock).setVariablesToTriggeredScope(argThat(new EqualsMap(expectedVariablesToTriggeredScope))); + + for (Entry expectedKey : expectedCorrelationKeys.entrySet()) { + String name = expectedKey.getKey(); + Object value = expectedKey.getValue(); + verify(messageCorrelationBuilderMock).processInstanceVariableEquals(name, value); + } + + for (Entry expectedLocalKey : expectedLocalCorrelationKeys.entrySet()) { + String name = expectedLocalKey.getKey(); + Object value = expectedLocalKey.getValue(); + verify(messageCorrelationBuilderMock).localVariableEquals(name, value); + } + + verify(messageCorrelationBuilderMock).correlateAllWithResult(); + } + + @Test + public void testFullMessageCorrelationAllWithExecutionResult() { + //given + when(messageCorrelationBuilderMock.correlateAllWithResult()).thenReturn(executionResultList); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("all", true); + messageParameters.put("resultEnabled", true); + + //when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + //then + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + + List results = from(content).getList(""); + assertEquals(2, results.size()); + for (int i = 0; i < 2; i++) { + checkExecutionResult(content, i); + } + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateAllWithResult(); + } + + @Test + public void testFullMessageCorrelationAllWithProcessInstanceResult() { + //given + when(messageCorrelationBuilderMock.correlateAllWithResult()).thenReturn(procInstanceResultList); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("all", true); + messageParameters.put("resultEnabled", true); + + //when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + //then + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + + List results = from(content).getList(""); + assertEquals(2, results.size()); + for (int i = 0; i < 2; i++) { + checkProcessInstanceResult(content, i); + } + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateAllWithResult(); + } + + @Test + public void testFullMessageCorrelationAllWithMixedResult() { + //given + when(messageCorrelationBuilderMock.correlateAllWithResult()).thenReturn(mixedResultList); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("all", true); + messageParameters.put("resultEnabled", true); + + //when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + //then + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + + List results = from(content).getList(""); + assertEquals(4, results.size()); + for (int i = 0; i < 2; i++) { + String resultType = from(content).get("[" + i + "].resultType"); + assertNotNull(resultType); + if (resultType.equals(MessageCorrelationResultType.Execution.name())) { + checkExecutionResult(content, i); + } else { + checkProcessInstanceResult(content, i); + } + } + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateAllWithResult(); + } + + + @Test + public void testFullMessageCorrelationAllWithNoResult() { + //given + when(messageCorrelationBuilderMock.correlateAllWithResult()).thenReturn(mixedResultList); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("all", true); + + //when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + //then + assertNotNull(response); + String content = response.asString(); + assertTrue(content.isEmpty()); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateAllWithResult(); + } + + @Test + public void testMessageNameOnlyCorrelation() { + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateWithResult(); + verifyNoMoreInteractions(messageCorrelationBuilderMock); + } + + @Test + public void testMessageNameAndBusinessKeyCorrelation() { + String messageName = "aMessageName"; + String businessKey = "aBusinessKey"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("businessKey", businessKey); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).processInstanceBusinessKey(eq(businessKey)); + verify(messageCorrelationBuilderMock).correlateWithResult(); + verifyNoMoreInteractions(messageCorrelationBuilderMock); + + } + + @Test + public void testMessageNameAndBusinessKeyCorrelationAll() { + String messageName = "aMessageName"; + String businessKey = "aBusinessKey"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("businessKey", businessKey); + messageParameters.put("all", true); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).processInstanceBusinessKey(eq(businessKey)); + verify(messageCorrelationBuilderMock).correlateAllWithResult(); + verifyNoMoreInteractions(messageCorrelationBuilderMock); + + } + + @Test + public void testMismatchingCorrelation() { + String messageName = "aMessage"; + + doThrow(new MismatchingMessageCorrelationException(messageName, "Expected exception: cannot correlate")) + .when(messageCorrelationBuilderMock).correlateWithResult(); + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", containsString("Expected exception: cannot correlate")) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingInstantiation() { + String messageName = "aMessage"; + + // thrown, if instantiation of the process or signalling the instance fails + doThrow(new ProcessEngineException("Expected exception")) + .when(messageCorrelationBuilderMock).correlateWithResult(); + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("Expected exception")) + .when().post(MESSAGE_URL); + } + + @Test + public void testNoMessageNameCorrelation() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No message name supplied")) + .when().post(MESSAGE_URL); + } + + @Test + public void testMessageCorrelationWithTenantId() { + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("tenantId", MockProvider.EXAMPLE_TENANT_ID); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).tenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(messageCorrelationBuilderMock).correlateWithResult(); + verifyNoMoreInteractions(messageCorrelationBuilderMock); + } + + @Test + public void testMessageCorrelationWithoutTenantId() { + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("withoutTenantId", true); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).withoutTenantId(); + verify(messageCorrelationBuilderMock).correlateWithResult(); + verifyNoMoreInteractions(messageCorrelationBuilderMock); + } + + @Test + public void testFailingInvalidTenantParameters() { + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("tenantId", MockProvider.EXAMPLE_TENANT_ID); + messageParameters.put("withoutTenantId", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Parameter 'tenantId' cannot be used together with parameter 'withoutTenantId'.")) + .when() + .post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableIntegerInCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableIntegerInLocalCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("localCorrelationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableShortInCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableShortInLocalCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("localCorrelationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableLongInCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableLongInLocalCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("localCorrelationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDoubleInCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDoubleInLocalCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("localCorrelationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDateInCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDateInLocalCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("localCorrelationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToNotSupportedTypeInCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("correlationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: Unsupported value type 'X'")) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToNotSupportedTypeInLocalCorrelationKeys() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("localCorrelationKeys", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: Unsupported value type 'X'")) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableIntegerInProcessVariables() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariables", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableShortInProcessVariables() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariables", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableLongInProcessVariables() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariables", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDoubleInProcessVariables() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariables", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDateInProcessVariables() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariables", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToNotSupportedTypeInProcessVariables() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariables", variableJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: Unsupported value type 'X'")) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableIntegerInProcessVariablesLocal() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableLocalJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariablesLocal", variableLocalJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToNotSupportedTypeInProcessVariablesLocal() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableLocalJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariablesLocal", variableLocalJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: Unsupported value type 'X'")) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDateInProcessVariablesLocal() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableLocalJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariablesLocal", variableLocalJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableIntegerInProcessVariablesToTriggeredScope() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableToTriggeredScopeJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariablesToTriggeredScope", variableToTriggeredScopeJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(MESSAGE_URL); + } + + + @Test + public void testFailingDueToNotSupportedTypeInProcessVariablesToTriggeredScope() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableToTriggeredScopeJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariablesToTriggeredScope", variableToTriggeredScopeJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: Unsupported value type 'X'")) + .when().post(MESSAGE_URL); + } + + @Test + public void testFailingDueToUnparseableDateInProcessVariablesToTriggeredScope() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableToTriggeredScopeJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processVariablesToTriggeredScope", variableToTriggeredScopeJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot deliver message: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(MESSAGE_URL); + } + + @Test + public void testCorrelateThrowsAuthorizationException() { + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(messageCorrelationBuilderMock).correlateWithResult(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(MESSAGE_URL); + } + + @Test + public void testcorrelateAllThrowsAuthorizationException() { + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("all", true); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(messageCorrelationBuilderMock).correlateAllWithResult(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(MESSAGE_URL); + } + + @Test + public void testMessageCorrelationWithProcessInstanceId() { + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then() + .expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).processInstanceId(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + + verify(messageCorrelationBuilderMock).correlateWithResult(); + } + + @Test + public void testMessageCorrelationWithoutBusinessKey() { + when(messageCorrelationBuilderMock.processInstanceBusinessKey(null)) + .thenThrow(new NullValueException()); + + String messageName = "aMessageName"; + + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then() + .expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + + verify(messageCorrelationBuilderMock, Mockito.never()).processInstanceBusinessKey(anyString()); + verify(messageCorrelationBuilderMock).correlateWithResult(); + verifyNoMoreInteractions(messageCorrelationBuilderMock); + } + + @Test + public void testCorrelationWithVariablesInResult() { + // given + when(messageCorrelationBuilderMock.correlateWithResultAndVariables(false)).thenReturn(executionResultWithVariables); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("resultEnabled", true); + messageParameters.put("variablesInResultEnabled", true); + + // when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + // then + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + checkVariablesInResult(content, 0); + checkExecutionResult(content, 0); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateWithResultAndVariables(false); + } + + @Test + public void testCorrelationAllWithVariablesInResult() { + // given + when(messageCorrelationBuilderMock.correlateAllWithResultAndVariables(false)).thenReturn(execResultWithVariablesList); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("all", true); + messageParameters.put("resultEnabled", true); + messageParameters.put("variablesInResultEnabled", true); + + // when + Response response = given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + // then + assertNotNull(response); + String content = response.asString(); + assertTrue(!content.isEmpty()); + + List> results = from(content).getList(""); + assertEquals(1, results.size()); + checkVariablesInResult(content, 0); + + verify(runtimeServiceMock).createMessageCorrelation(eq(messageName)); + verify(messageCorrelationBuilderMock).correlateAllWithResultAndVariables(false); + } + + @Test + public void testFailingCorrelationWithVariablesInResultDueToDisabledResult() { + // given + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + messageParameters.put("resultEnabled", false); + messageParameters.put("variablesInResultEnabled", true); + + // when/ + given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Parameter 'variablesInResultEnabled' cannot be used without 'resultEnabled' set to true.")) + .when().post(MESSAGE_URL); + } + + @Test + public void shouldReturnErrorOnMessageCorrelation() { + // given + doThrow(new ProcessEngineException("foo", 123)) + .when(messageCorrelationBuilderMock).correlateWithResult(); + + String messageName = "aMessageName"; + Map messageParameters = new HashMap<>(); + messageParameters.put("messageName", messageName); + + // when/ + given().contentType(POST_JSON_CONTENT_TYPE) + .body(messageParameters) + .then().expect() + .contentType(ContentType.JSON) + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("foo")) + .body("code", equalTo(123)) + .when().post(MESSAGE_URL); + } + + protected void checkVariablesInResult(String content, int idx) { + List variableNames = java.util.Arrays.asList(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME, MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME); + + for (String variableName : variableNames) { + String variablePath = "[" + idx + "].variables." + variableName; + assertEquals(MockProvider.FORMAT_APPLICATION_JSON, from(content).getMap(variablePath + ".valueInfo").get("serializationDataFormat")); + assertEquals(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE, from(content).get(variablePath + ".value")); + assertEquals(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT), from(content).get(variablePath + ".type")); + } + + assertEquals(ArrayList.class.getName(), + from(content).getMap("[" + idx + "].variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo").get("objectTypeName")); + assertEquals(Object.class.getName(), + from(content).getMap("[" + idx + "].variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo").get("objectTypeName")); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MetricsRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MetricsRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..78ba6f053f57025618274dc0eee731865ce49d42 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MetricsRestServiceInteractionTest.java @@ -0,0 +1,426 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.hamcrest.Matchers.*; +import static io.restassured.RestAssured.given; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Date; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.management.Metrics; +import org.camunda.bpm.engine.management.MetricsQuery; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +/** + * @author Daniel Meyer + */ +public class MetricsRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + public static final String METRICS_URL = TEST_RESOURCE_ROOT_PATH + MetricsRestService.PATH; + public static final String DELETE_UTW_URL = METRICS_URL + "/task-worker"; + public static final String SINGLE_METER_URL = METRICS_URL + "/{name}"; + public static final String SUM_URL = SINGLE_METER_URL + "/sum"; + + protected ManagementService managementServiceMock; + private MetricsQuery meterQueryMock; + + @Before + public void setUpRuntimeData() { + managementServiceMock = mock(ManagementService.class); + + when(processEngine.getManagementService()).thenReturn(managementServiceMock); + + meterQueryMock = MockProvider.createMockMeterQuery(); + when(managementServiceMock.createMetricsQuery()).thenReturn(meterQueryMock); + + when(managementServiceMock.getUniqueTaskWorkerCount(any(), any())).thenReturn(10L); + } + + @Test + public void testGetInterval() { + when(meterQueryMock.interval()).thenReturn(MockProvider.createMockMetricIntervalResult()); + + given() + .then() + .expect() + .body("[0].name", equalTo("metricName")) + .body("[0].timestamp", equalTo(withTimezone(new Date(15 * 60 * 1000 * 3)))) + .body("[0].reporter", equalTo("REPORTER")) + .body("[0].value", equalTo(23)) + + .body("[1].name", equalTo("metricName")) + .body("[1].timestamp", equalTo(withTimezone(new Date(15 * 60 * 1000 * 2)))) + .body("[1].reporter", equalTo("REPORTER")) + .body("[1].value", equalTo(22)) + + .body("[2].name", equalTo("metricName")) + .body("[2].timestamp", equalTo(withTimezone(new Date(15 * 60 * 1000 * 1)))) + .body("[2].reporter", equalTo("REPORTER")) + .body("[2].value", equalTo(21)) + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetIntervalByName() { + given() + .queryParam("name", MockProvider.EXAMPLE_METRICS_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(MockProvider.EXAMPLE_METRICS_NAME); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + + @Test + public void testGetIntervalByReporter() { + given() + .queryParam("reporter", MockProvider.EXAMPLE_METRICS_REPORTER) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(MockProvider.EXAMPLE_METRICS_REPORTER); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + + @Test + public void testGetIntervalWithOffset() { + given() + .queryParam("firstResult", 10) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock).offset(10); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetIntervalWithLimit() { + given() + .queryParam("maxResults", 10) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock).limit(10); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetIntervalAggregation() { + given() + .queryParam("aggregateByReporter", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock).aggregateByReporter(); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetIntervalWithStartDate() { + + given() + .queryParam("startDate", DATE_FORMAT_WITH_TIMEZONE.format(new Date(0))) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock).startDate(new Date(0)); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetIntervalWithEndDate() { + + given() + .queryParam("endDate", DATE_FORMAT_WITH_TIMEZONE.format(new Date(15 * 60 * 1000))) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock).endDate(new Date(15 * 60 * 1000)); + verify(meterQueryMock, times(1)).interval(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetIntervalWithCustomInterval() { + given() + .queryParam("interval", 300) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(null); + verify(meterQueryMock).reporter(null); + verify(meterQueryMock, times(1)).interval(300); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetIntervalWithAll() { + + given() + .queryParam("name", MockProvider.EXAMPLE_METRICS_NAME) + .queryParam("reporter", MockProvider.EXAMPLE_METRICS_REPORTER) + .queryParam("maxResults", 10) + .queryParam("firstResult", 10) + .queryParam("startDate", DATE_FORMAT_WITH_TIMEZONE.format(new Date(0))) + .queryParam("endDate", DATE_FORMAT_WITH_TIMEZONE.format(new Date(15 * 60 * 1000))) + .queryParam("aggregateByReporter", true) + .queryParam("interval", 300) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(METRICS_URL); + + verify(meterQueryMock).name(MockProvider.EXAMPLE_METRICS_NAME); + verify(meterQueryMock).reporter(MockProvider.EXAMPLE_METRICS_REPORTER); + verify(meterQueryMock).offset(10); + verify(meterQueryMock).limit(10); + verify(meterQueryMock).startDate(new Date(0)); + verify(meterQueryMock).endDate(new Date(15 * 60 * 1000)); + verify(meterQueryMock).aggregateByReporter(); + verify(meterQueryMock, times(1)).interval(300); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetSum() { + + when(meterQueryMock.sum()).thenReturn(10l); + + given() + .pathParam("name", Metrics.ACTIVTY_INSTANCE_START) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("result", equalTo(10)) + .when() + .get(SUM_URL); + + verify(meterQueryMock).name(Metrics.ACTIVTY_INSTANCE_START); + verify(meterQueryMock, times(1)).sum(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetSumWithTimestamps() { + + when(meterQueryMock.sum()).thenReturn(10l); + + given() + .pathParam("name", Metrics.ACTIVTY_INSTANCE_START) + .queryParam("startDate", MockProvider.EXAMPLE_METRICS_START_DATE) + .queryParam("endDate", MockProvider.EXAMPLE_METRICS_END_DATE) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("result", equalTo(10)) + .when() + .get(SUM_URL); + + verify(meterQueryMock).name(Metrics.ACTIVTY_INSTANCE_START); + verify(meterQueryMock).startDate(any(Date.class)); + verify(meterQueryMock).endDate(any(Date.class)); + verify(meterQueryMock, times(1)).sum(); + verifyNoMoreInteractions(meterQueryMock); + } + + @Test + public void testGetSumWithInvalidTimestamp() { + + when(meterQueryMock.sum()).thenReturn(10l); + + given() + .pathParam("name", Metrics.ACTIVTY_INSTANCE_START) + .queryParam("startDate", "INVALID-TIME-STAMP") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SUM_URL); + + } + + @Test + public void testGetUtw() { + + given() + .pathParam("name", Metrics.UNIQUE_TASK_WORKERS) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("result", equalTo(10)) + .when() + .get(SUM_URL); + + verify(managementServiceMock, times (1)).getUniqueTaskWorkerCount(null, null); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void testGetTaskUsers() { + + given() + .pathParam("name", Metrics.TASK_USERS) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("result", equalTo(10)) + .when() + .get(SUM_URL); + + verify(managementServiceMock, times (1)).getUniqueTaskWorkerCount(null, null); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void testGetUtwWithTimestamps() { + + given() + .pathParam("name", Metrics.UNIQUE_TASK_WORKERS) + .queryParam("startDate", MockProvider.EXAMPLE_METRICS_START_DATE) + .queryParam("endDate", MockProvider.EXAMPLE_METRICS_END_DATE) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("result", equalTo(10)) + .when() + .get(SUM_URL); + + verify(managementServiceMock, times(1)).getUniqueTaskWorkerCount(any(Date.class), any(Date.class)); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void testGetUtwWithInvalidTimestamp() { + + given() + .pathParam("name", Metrics.UNIQUE_TASK_WORKERS) + .queryParam("startDate", "INVALID-TIME-STAMP") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SUM_URL); + + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void testDeleteUtwWithTimestamp() { + Date date = MockProvider.createMockDuedate(); + + given() + .queryParam("date", DATE_FORMAT_WITH_TIMEZONE.format(date)) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DELETE_UTW_URL); + + verify(managementServiceMock, times(1)).deleteTaskMetrics(date); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void testDeleteUtwWithoutTimestamp() { + given() + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(DELETE_UTW_URL); + + verify(managementServiceMock, times(1)).deleteTaskMetrics(null); + verifyNoMoreInteractions(managementServiceMock); + } + + @Test + public void testDeleteUtwThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(managementServiceMock).deleteTaskMetrics(any()); + + given() + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(DELETE_UTW_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MigrationRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MigrationRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2d4e865e60ff6148abc6b7b4bb634ec98a429786 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/MigrationRestServiceInteractionTest.java @@ -0,0 +1,1604 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.helper.MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_BATCH_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_BATCH_TOTAL_JOBS; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_BATCH_TYPE; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TENANT_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_ACTIVITY_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockBatch; +import static org.camunda.bpm.engine.rest.helper.NoIntermediaryInvocation.immediatelyAfter; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.variable.impl.value.PrimitiveTypeValueImpl.*; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.emptyArray; +import static org.hamcrest.Matchers.emptyCollectionOf; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; +import org.camunda.bpm.engine.migration.MigratingActivityInstanceValidationReport; +import org.camunda.bpm.engine.migration.MigratingProcessInstanceValidationException; +import org.camunda.bpm.engine.migration.MigratingProcessInstanceValidationReport; +import org.camunda.bpm.engine.migration.MigratingTransitionInstanceValidationReport; +import org.camunda.bpm.engine.migration.MigrationInstruction; +import org.camunda.bpm.engine.migration.MigrationInstructionValidationReport; +import org.camunda.bpm.engine.migration.MigrationPlan; +import org.camunda.bpm.engine.migration.MigrationPlanBuilder; +import org.camunda.bpm.engine.migration.MigrationPlanExecutionBuilder; +import org.camunda.bpm.engine.migration.MigrationPlanValidationException; +import org.camunda.bpm.engine.migration.MigrationPlanValidationReport; +import org.camunda.bpm.engine.migration.MigrationVariableValidationReport; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.migration.MigrationInstructionDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.helper.FluentAnswer; +import org.camunda.bpm.engine.rest.helper.MockMigrationPlanBuilder; +import org.camunda.bpm.engine.rest.helper.MockMigrationPlanBuilder.JoinedMigrationPlanBuilderMock; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.rest.util.migration.MigrationExecutionDtoBuilder; +import org.camunda.bpm.engine.rest.util.migration.MigrationPlanDtoBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.response.Response; +import java.util.List; +import org.camunda.bpm.engine.rest.util.migration.MigrationInstructionDtoBuilder; + +public class MigrationRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String MIGRATION_URL = TEST_RESOURCE_ROOT_PATH + "/migration"; + protected static final String GENERATE_MIGRATION_URL = MIGRATION_URL + "/generate"; + protected static final String VALIDATE_MIGRATION_URL = MIGRATION_URL + "/validate"; + protected static final String EXECUTE_MIGRATION_URL = MIGRATION_URL + "/execute"; + protected static final String EXECUTE_MIGRATION_ASYNC_URL = MIGRATION_URL + "/executeAsync"; + + protected RuntimeService runtimeServiceMock; + protected JoinedMigrationPlanBuilderMock migrationPlanBuilderMock; + protected MigrationPlanExecutionBuilder migrationPlanExecutionBuilderMock; + + @Before + public void setUpRuntimeData() { + runtimeServiceMock = mock(RuntimeService.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + + migrationPlanBuilderMock = new MockMigrationPlanBuilder() + .sourceProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .targetProcessDefinitionId(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .builder(); + + when(runtimeServiceMock.createMigrationPlan(eq(EXAMPLE_PROCESS_DEFINITION_ID), eq(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID))) + .thenReturn(migrationPlanBuilderMock); + + migrationPlanExecutionBuilderMock = mock(MigrationPlanExecutionBuilder.class); + when(migrationPlanExecutionBuilderMock.processInstanceIds(Mockito.>any())).thenReturn(migrationPlanExecutionBuilderMock); + + when(runtimeServiceMock.newMigration(any())).thenReturn(migrationPlanExecutionBuilderMock); + } + + @Test + public void generateMigrationPlanWithInitialEmptyInstructions() { + Map initialMigrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instructions(Collections.>emptyList()) + .build(); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(GENERATE_MIGRATION_URL); + + verifyGenerateMigrationPlanInteraction(migrationPlanBuilderMock, initialMigrationPlan); + verifyGenerateMigrationPlanResponse(response); + } + + @Test + public void generateMigrationPlanWithInitialNullInstructions() { + Map initialMigrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instructions(null) + .build(); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(GENERATE_MIGRATION_URL); + + verifyGenerateMigrationPlanInteraction(migrationPlanBuilderMock, initialMigrationPlan); + verifyGenerateMigrationPlanResponse(response); + } + + @Test + public void generateMigrationPlanWithNoInitialInstructions() { + Map initialMigrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .build(); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(GENERATE_MIGRATION_URL); + + verifyGenerateMigrationPlanInteraction(migrationPlanBuilderMock, initialMigrationPlan); + verifyGenerateMigrationPlanResponse(response); + } + + @Test + public void generateMigrationPlanIgnoringInitialInstructions() { + Map initialMigrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction("ignored", "ignored") + .build(); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(GENERATE_MIGRATION_URL); + + verifyGenerateMigrationPlanInteraction(migrationPlanBuilderMock, initialMigrationPlan); + verifyGenerateMigrationPlanResponse(response); + } + + @Test + public void generateMigrationPlanWithNullSourceProcessDefinition() { + String message = "source process definition id is null"; + MigrationPlanBuilder planBuilder = mock(MigrationPlanBuilder.class, Mockito.RETURNS_DEEP_STUBS); + when(runtimeServiceMock.createMigrationPlan(isNull(), anyString())) + .thenReturn(planBuilder); + + when(planBuilder.mapEqualActivities().build()) + .thenThrow(new BadUserRequestException(message)); + + Map initialMigrationPlan = new MigrationPlanDtoBuilder(null, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID).build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(GENERATE_MIGRATION_URL); + } + + @Test + public void generateMigrationPlanWithNonExistingSourceProcessDefinition() { + String message = "source process definition with id " + NON_EXISTING_PROCESS_DEFINITION_ID + " does not exist"; + MigrationPlanBuilder migrationPlanBuilder = mock(MigrationPlanBuilder.class, Mockito.RETURNS_DEEP_STUBS); + when(runtimeServiceMock.createMigrationPlan(eq(NON_EXISTING_PROCESS_DEFINITION_ID), anyString())) + .thenReturn(migrationPlanBuilder); + + when( + migrationPlanBuilder + .mapEqualActivities() + .build()) + .thenThrow(new BadUserRequestException(message)); + + Map initialMigrationPlan = new MigrationPlanDtoBuilder(NON_EXISTING_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID).build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(GENERATE_MIGRATION_URL); + } + + @Test + public void generateMigrationPlanWithNullTargetProcessDefinition() { + String message = "target process definition id is null"; + MigrationPlanBuilder migrationPlanBuilder = mock(MigrationPlanBuilder.class, Mockito.RETURNS_DEEP_STUBS); + when(runtimeServiceMock.createMigrationPlan(anyString(), isNull())) + .thenReturn(migrationPlanBuilder); + when( + migrationPlanBuilder + .mapEqualActivities() + .build()) + .thenThrow(new BadUserRequestException(message)); + + Map initialMigrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, null).build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(GENERATE_MIGRATION_URL); + } + + @Test + public void generateMigrationPlanWithNonExistingTargetProcessDefinition() { + String message = "target process definition with id " + NON_EXISTING_PROCESS_DEFINITION_ID + " does not exist"; + MigrationPlanBuilder migrationPlanBuilder = mock(MigrationPlanBuilder.class, Mockito.RETURNS_DEEP_STUBS); + when(runtimeServiceMock.createMigrationPlan(anyString(), eq(NON_EXISTING_PROCESS_DEFINITION_ID))) + .thenReturn(migrationPlanBuilder); + when( + migrationPlanBuilder + .mapEqualActivities() + .build()) + .thenThrow(new BadUserRequestException(message)); + + Map initialMigrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, NON_EXISTING_PROCESS_DEFINITION_ID).build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(initialMigrationPlan) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(GENERATE_MIGRATION_URL); + } + + @Test + public void generatePlanUpdateEventTriggers() { + migrationPlanBuilderMock = new MockMigrationPlanBuilder() + .sourceProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .targetProcessDefinitionId(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID, true) + .builder(); + + Map generationRequest = new HashMap(); + generationRequest.put("sourceProcessDefinitionId", EXAMPLE_PROCESS_DEFINITION_ID); + generationRequest.put("targetProcessDefinitionId", ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + generationRequest.put("updateEventTriggers", true); + + when(runtimeServiceMock.createMigrationPlan(anyString(), anyString())) + .thenReturn(migrationPlanBuilderMock); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(generationRequest) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(GENERATE_MIGRATION_URL); + + verify(runtimeServiceMock).createMigrationPlan(eq(EXAMPLE_PROCESS_DEFINITION_ID), eq(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID)); + + InOrder inOrder = Mockito.inOrder(migrationPlanBuilderMock); + + // the map equal activities method should be called + inOrder.verify(migrationPlanBuilderMock).mapEqualActivities(); + inOrder.verify(migrationPlanBuilderMock, immediatelyAfter()).updateEventTriggers(); + verify(migrationPlanBuilderMock, never()).mapActivities(anyString(), anyString()); + } + + @Test + public void generatePlanUpdateEventTriggerResponse() { + migrationPlanBuilderMock = new MockMigrationPlanBuilder() + .sourceProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .targetProcessDefinitionId(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID, true) + .builder(); + when(runtimeServiceMock.createMigrationPlan(anyString(), anyString())) + .thenReturn(migrationPlanBuilderMock); + + Map generationRequest = new HashMap(); + generationRequest.put("sourceProcessDefinitionId", EXAMPLE_PROCESS_DEFINITION_ID); + generationRequest.put("targetProcessDefinitionId", ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(generationRequest) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("instructions[0].sourceActivityIds[0]", equalTo(EXAMPLE_ACTIVITY_ID)) + .body("instructions[0].targetActivityIds[0]", equalTo(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .body("instructions[0].updateEventTrigger", equalTo(true)) + .when() + .post(GENERATE_MIGRATION_URL); + + } + + @Test + public void generatePlanVariables() { + migrationPlanBuilderMock = new MockMigrationPlanBuilder() + .sourceProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .targetProcessDefinitionId(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID, true) + .builder(); + + Map generationRequest = new HashMap<>(); + generationRequest.put("sourceProcessDefinitionId", EXAMPLE_PROCESS_DEFINITION_ID); + generationRequest.put("targetProcessDefinitionId", ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + + Map variableDtos = new HashMap<>(); + + VariableValueDto valueDtoFoo = new VariableValueDto(); + valueDtoFoo.setValue("foo"); + valueDtoFoo.setType("String"); + valueDtoFoo.setValueInfo(Collections.singletonMap("transient", true)); + variableDtos.put("foo", valueDtoFoo); + + VariableValueDto valueDtoBar = new VariableValueDto(); + valueDtoBar.setValue(5); + valueDtoBar.setType("short"); + valueDtoBar.setValueInfo(Collections.singletonMap("transient", false)); + variableDtos.put("bar", valueDtoBar); + + generationRequest.put("variables", variableDtos); + + when(runtimeServiceMock.createMigrationPlan(anyString(), anyString())) + .thenReturn(migrationPlanBuilderMock); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(generationRequest) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(GENERATE_MIGRATION_URL); + + verify(runtimeServiceMock).createMigrationPlan(eq(EXAMPLE_PROCESS_DEFINITION_ID), eq(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID)); + + InOrder inOrder = Mockito.inOrder(migrationPlanBuilderMock); + + // the map equal activities method should be called + inOrder.verify(migrationPlanBuilderMock).mapEqualActivities(); + ArgumentCaptor variablesCaptor = ArgumentCaptor.forClass(Map.class); + + inOrder.verify(migrationPlanBuilderMock).setVariables(variablesCaptor.capture()); + TypedValue foo = ((VariableMap) variablesCaptor.getValue()).getValueTyped("foo"); + assertThat(foo.getValue()).isEqualTo("foo"); + assertThat(foo.isTransient()).isTrue(); + assertThat(foo.getType().getName()).isEqualTo("string"); + + TypedValue bar = ((VariableMap) variablesCaptor.getValue()).getValueTyped("bar"); + assertThat(bar.getValue()).isEqualTo((short)5); + assertThat(bar.isTransient()).isFalse(); + assertThat(bar.getType().getName()).isEqualTo("short"); + + verify(migrationPlanBuilderMock, never()).mapActivities(anyString(), anyString()); + } + + @Test + public void generatePlanVariablesResponse() { + migrationPlanBuilderMock = new MockMigrationPlanBuilder() + .sourceProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .targetProcessDefinitionId(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID, true) + .variables(Variables.putValue("foo", Variables.stringValue("bar", true)) + .putValue("bar", Variables.shortValue((short)5))) + .builder(); + when(runtimeServiceMock.createMigrationPlan(anyString(), anyString())) + .thenReturn(migrationPlanBuilderMock); + + Map generationRequest = new HashMap<>(); + generationRequest.put("sourceProcessDefinitionId", EXAMPLE_PROCESS_DEFINITION_ID); + generationRequest.put("targetProcessDefinitionId", ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + generationRequest.put("variables", new HashMap<>()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(generationRequest) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("instructions[0].sourceActivityIds[0]", equalTo(EXAMPLE_ACTIVITY_ID)) + .body("instructions[0].targetActivityIds[0]", equalTo(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .body("instructions[0].updateEventTrigger", equalTo(true)) + .body("variables.foo.value", is("bar")) + .body("variables.foo.type", is("String")) + .body("variables.foo.valueInfo.transient", is(true)) + .body("variables.bar.value", is(5)) + .body("variables.bar.type", is("Short")) + .when() + .post(GENERATE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlan() { + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MIGRATION_URL); + + verifyCreateMigrationPlanInteraction(migrationPlanBuilderMock, (Map) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_MIGRATION_PLAN)); + verifyMigrationPlanExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanWithProcessInstanceQuery() { + when(runtimeServiceMock.createProcessInstanceQuery()) + .thenReturn(new ProcessInstanceQueryImpl()); + + ProcessInstanceQueryDto processInstanceQuery = new ProcessInstanceQueryDto(); + processInstanceQuery.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstanceQuery(processInstanceQuery) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MIGRATION_URL); + + + verifyCreateMigrationPlanInteraction(migrationPlanBuilderMock, (Map) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_MIGRATION_PLAN)); + verifyMigrationPlanExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanSkipListeners() { + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID) + .skipCustomListeners(true) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MIGRATION_URL); + + verifyMigrationPlanExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanSkipIoMappings() { + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID) + .skipIoMappings(true) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MIGRATION_URL); + + verifyMigrationPlanExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanWithNullInstructions() { + MigrationInstructionValidationReport instructionReport = mock(MigrationInstructionValidationReport.class); + when(instructionReport.getMigrationInstruction()).thenReturn(null); + when(instructionReport.getFailures()).thenReturn(Collections.singletonList("failure")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + when(validationReport.getInstructionReports()).thenReturn(Collections.singletonList(instructionReport)); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(MigrationPlanValidationException.class.getSimpleName())) + .body("message", is("fooo")) + .body("validationReport.instructionReports", hasSize(1)) + .body("validationReport.instructionReports[0].instruction", nullValue()) + .body("validationReport.instructionReports[0].failures", hasSize(1)) + .body("validationReport.instructionReports[0].failures[0]", is("failure")) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithEmptyInstructions() { + MigrationInstructionValidationReport instructionReport = mock(MigrationInstructionValidationReport.class); + when(instructionReport.getMigrationInstruction()).thenReturn(null); + when(instructionReport.getFailures()).thenReturn(Collections.singletonList("failure")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + when(validationReport.getInstructionReports()).thenReturn(Collections.singletonList(instructionReport)); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + ((Map) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_MIGRATION_PLAN)) + .put(MigrationPlanDtoBuilder.PROP_INSTRUCTIONS, Collections.emptyList()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(MigrationPlanValidationException.class.getSimpleName())) + .body("message", is("fooo")) + .body("validationReport.instructionReports", hasSize(1)) + .body("validationReport.instructionReports[0].instruction", nullValue()) + .body("validationReport.instructionReports[0].failures", hasSize(1)) + .body("validationReport.instructionReports[0].failures[0]", is("failure")) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNullSourceProcessInstanceId() { + String message = "source process definition id is null"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(isNull(), anyString())) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(null, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNonExistingSourceProcessInstanceId() { + String message = "source process definition with id " + NON_EXISTING_PROCESS_DEFINITION_ID + " does not exist"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(eq(NON_EXISTING_PROCESS_DEFINITION_ID), anyString())) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(NON_EXISTING_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNullTargetProcessInstanceId() { + String message = "target process definition id is null"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(anyString(), isNull())) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, null) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNonExistingTargetProcessInstanceId() { + String message = "target process definition with id " + NON_EXISTING_PROCESS_DEFINITION_ID + " does not exist"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(anyString(), eq(NON_EXISTING_PROCESS_DEFINITION_ID))) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, NON_EXISTING_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNullSourceActivityId() { + String message = "sourceActivityId is null"; + when(migrationPlanBuilderMock.mapActivities(isNull(), anyString())) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(null, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNonExistingSourceActivityId() { + String message = "sourceActivity is null"; + when(migrationPlanBuilderMock.mapActivities(eq(NON_EXISTING_ACTIVITY_ID), anyString())) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(NON_EXISTING_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNullTargetActivityId() { + String message = "targetActivityId is null"; + when(migrationPlanBuilderMock.mapActivities(anyString(), isNull())) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, null) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanWithNonExistingTargetActivityId() { + String message = "targetActivity is null"; + when(migrationPlanBuilderMock.mapActivities(anyString(), eq(NON_EXISTING_ACTIVITY_ID))) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, NON_EXISTING_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanValidationException() { + + MigrationInstruction migrationInstruction = mock(MigrationInstruction.class); + when(migrationInstruction.getSourceActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(migrationInstruction.getTargetActivityId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + + MigrationInstructionValidationReport instructionReport1 = mock(MigrationInstructionValidationReport.class); + when(instructionReport1.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instructionReport1.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationInstructionValidationReport instructionReport2 = mock(MigrationInstructionValidationReport.class); + when(instructionReport2.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instructionReport2.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + when(validationReport.getInstructionReports()).thenReturn(Arrays.asList(instructionReport1, instructionReport2)); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(MigrationPlanValidationException.class.getSimpleName())) + .body("message", is("fooo")) + .body("validationReport.instructionReports", hasSize(2)) + .body("validationReport.instructionReports[0].instruction.sourceActivityIds", hasSize(1)) + .body("validationReport.instructionReports[0].instruction.sourceActivityIds[0]", is(EXAMPLE_ACTIVITY_ID)) + .body("validationReport.instructionReports[0].instruction.targetActivityIds", hasSize(1)) + .body("validationReport.instructionReports[0].instruction.targetActivityIds[0]", is(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .body("validationReport.instructionReports[0].failures", hasSize(2)) + .body("validationReport.instructionReports[0].failures[0]", is("failure1")) + .body("validationReport.instructionReports[0].failures[1]", is("failure2")) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigratingProcessInstanceValidationException() { + + MigrationInstruction migrationInstruction = mock(MigrationInstruction.class); + when(migrationInstruction.getSourceActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(migrationInstruction.getTargetActivityId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + + MigratingActivityInstanceValidationReport instanceReport1 = mock(MigratingActivityInstanceValidationReport.class); + when(instanceReport1.getActivityInstanceId()).thenReturn(EXAMPLE_ACTIVITY_INSTANCE_ID); + when(instanceReport1.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instanceReport1.getSourceScopeId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(instanceReport1.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigratingTransitionInstanceValidationReport instanceReport2 = mock(MigratingTransitionInstanceValidationReport.class); + when(instanceReport2.getTransitionInstanceId()).thenReturn("transitionInstanceId"); + when(instanceReport2.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instanceReport2.getSourceScopeId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(instanceReport2.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigratingProcessInstanceValidationReport processInstanceReport = mock(MigratingProcessInstanceValidationReport.class); + when(processInstanceReport.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(processInstanceReport.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + when(processInstanceReport.getActivityInstanceReports()).thenReturn(Arrays.asList(instanceReport1)); + when(processInstanceReport.getTransitionInstanceReports()).thenReturn(Arrays.asList(instanceReport2)); + + doThrow(new MigratingProcessInstanceValidationException("fooo", processInstanceReport)) + .when(migrationPlanExecutionBuilderMock).execute(); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(MigratingProcessInstanceValidationException.class.getSimpleName())) + .body("message", is("fooo")) + .body("validationReport.processInstanceId", is(EXAMPLE_PROCESS_INSTANCE_ID)) + .body("validationReport.failures", hasSize(2)) + .body("validationReport.failures[0]", is("failure1")) + .body("validationReport.failures[1]", is("failure2")) + .body("validationReport.activityInstanceValidationReports", hasSize(1)) + .body("validationReport.activityInstanceValidationReports[0].migrationInstruction.sourceActivityIds", hasSize(1)) + .body("validationReport.activityInstanceValidationReports[0].migrationInstruction.sourceActivityIds[0]", is(EXAMPLE_ACTIVITY_ID)) + .body("validationReport.activityInstanceValidationReports[0].migrationInstruction.targetActivityIds", hasSize(1)) + .body("validationReport.activityInstanceValidationReports[0].migrationInstruction.targetActivityIds[0]", is(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .body("validationReport.activityInstanceValidationReports[0].activityInstanceId", is(EXAMPLE_ACTIVITY_INSTANCE_ID)) + .body("validationReport.activityInstanceValidationReports[0].sourceScopeId", is(EXAMPLE_ACTIVITY_ID)) + .body("validationReport.activityInstanceValidationReports[0].failures", hasSize(2)) + .body("validationReport.activityInstanceValidationReports[0].failures[0]", is("failure1")) + .body("validationReport.activityInstanceValidationReports[0].failures[1]", is("failure2")) + .body("validationReport.transitionInstanceValidationReports", hasSize(1)) + .body("validationReport.transitionInstanceValidationReports[0].migrationInstruction.sourceActivityIds", hasSize(1)) + .body("validationReport.transitionInstanceValidationReports[0].migrationInstruction.sourceActivityIds[0]", is(EXAMPLE_ACTIVITY_ID)) + .body("validationReport.transitionInstanceValidationReports[0].migrationInstruction.targetActivityIds", hasSize(1)) + .body("validationReport.transitionInstanceValidationReports[0].migrationInstruction.targetActivityIds[0]", is(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .body("validationReport.transitionInstanceValidationReports[0].transitionInstanceId", is("transitionInstanceId")) + .body("validationReport.transitionInstanceValidationReports[0].sourceScopeId", is(EXAMPLE_ACTIVITY_ID)) + .body("validationReport.transitionInstanceValidationReports[0].failures", hasSize(2)) + .body("validationReport.transitionInstanceValidationReports[0].failures[0]", is("failure1")) + .body("validationReport.transitionInstanceValidationReports[0].failures[1]", is("failure2")) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanAsync() { + Batch batchMock = createMockBatch(); + when(migrationPlanExecutionBuilderMock.executeAsync()).thenReturn(batchMock); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", is(EXAMPLE_BATCH_ID)) + .body("type", is(EXAMPLE_BATCH_TYPE)) + .body("totalJobs", is(EXAMPLE_BATCH_TOTAL_JOBS)) + .body("batchJobsPerSeed", is(EXAMPLE_BATCH_JOBS_PER_SEED)) + .body("invocationsPerBatchJob", is(EXAMPLE_INVOCATIONS_PER_BATCH_JOB)) + .body("seedJobDefinitionId", is(EXAMPLE_SEED_JOB_DEFINITION_ID)) + .body("monitorJobDefinitionId", is(EXAMPLE_MONITOR_JOB_DEFINITION_ID)) + .body("batchJobDefinitionId", is(EXAMPLE_BATCH_JOB_DEFINITION_ID)) + .body("tenantId", is(EXAMPLE_TENANT_ID)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + + verifyCreateMigrationPlanInteraction(migrationPlanBuilderMock, (Map) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_MIGRATION_PLAN)); + verifyMigrationPlanAsyncExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanAsyncWithProcessInstanceQuery() { + when(runtimeServiceMock.createProcessInstanceQuery()) + .thenReturn(new ProcessInstanceQueryImpl()); + + ProcessInstanceQueryDto processInstanceQuery = new ProcessInstanceQueryDto(); + processInstanceQuery.setProcessDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + Batch batchMock = createMockBatch(); + when(migrationPlanExecutionBuilderMock.executeAsync()).thenReturn(batchMock); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstanceQuery(processInstanceQuery) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", is(EXAMPLE_BATCH_ID)) + .body("type", is(EXAMPLE_BATCH_TYPE)) + .body("totalJobs", is(EXAMPLE_BATCH_TOTAL_JOBS)) + .body("batchJobsPerSeed", is(EXAMPLE_BATCH_JOBS_PER_SEED)) + .body("invocationsPerBatchJob", is(EXAMPLE_INVOCATIONS_PER_BATCH_JOB)) + .body("seedJobDefinitionId", is(EXAMPLE_SEED_JOB_DEFINITION_ID)) + .body("monitorJobDefinitionId", is(EXAMPLE_MONITOR_JOB_DEFINITION_ID)) + .body("batchJobDefinitionId", is(EXAMPLE_BATCH_JOB_DEFINITION_ID)) + .body("tenantId", is(EXAMPLE_TENANT_ID)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + + verifyCreateMigrationPlanInteraction(migrationPlanBuilderMock, (Map) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_MIGRATION_PLAN)); + verifyMigrationPlanAsyncExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanAsyncSkipListeners() { + Batch batchMock = createMockBatch(); + when(migrationPlanExecutionBuilderMock.executeAsync()).thenReturn(batchMock); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID) + .skipCustomListeners(true) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + + verifyMigrationPlanAsyncExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanAsyncSkipIoMappings() { + Batch batchMock = createMockBatch(); + when(migrationPlanExecutionBuilderMock.executeAsync()).thenReturn(batchMock); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID) + .skipIoMappings(true) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + + verifyMigrationPlanAsyncExecutionInteraction(migrationExecution); + } + + @Test + public void executeMigrationPlanAsyncWithNullInstructions() { + MigrationInstructionValidationReport instructionReport = mock(MigrationInstructionValidationReport.class); + when(instructionReport.getMigrationInstruction()).thenReturn(null); + when(instructionReport.getFailures()).thenReturn(Collections.singletonList("failure")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + when(validationReport.getInstructionReports()).thenReturn(Collections.singletonList(instructionReport)); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(MigrationPlanValidationException.class.getSimpleName())) + .body("message", is("fooo")) + .body("validationReport.instructionReports", hasSize(1)) + .body("validationReport.instructionReports[0].instruction", nullValue()) + .body("validationReport.instructionReports[0].failures", hasSize(1)) + .body("validationReport.instructionReports[0].failures[0]", is("failure")) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithEmptyInstructions() { + MigrationInstructionValidationReport instructionReport = mock(MigrationInstructionValidationReport.class); + when(instructionReport.getMigrationInstruction()).thenReturn(null); + when(instructionReport.getFailures()).thenReturn(Collections.singletonList("failure")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + when(validationReport.getInstructionReports()).thenReturn(Collections.singletonList(instructionReport)); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + ((Map) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_MIGRATION_PLAN)) + .put(MigrationPlanDtoBuilder.PROP_INSTRUCTIONS, Collections.emptyList()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(MigrationPlanValidationException.class.getSimpleName())) + .body("message", is("fooo")) + .body("validationReport.instructionReports", hasSize(1)) + .body("validationReport.instructionReports[0].instruction", nullValue()) + .body("validationReport.instructionReports[0].failures", hasSize(1)) + .body("validationReport.instructionReports[0].failures[0]", is("failure")) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNullSourceProcessDefinitionId() { + String message = "source process definition id is null"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(isNull(), anyString())) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(null, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNonExistingSourceProcessDefinitionId() { + String message = "source process definition with id " + NON_EXISTING_PROCESS_DEFINITION_ID + " does not exist"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(eq(NON_EXISTING_PROCESS_DEFINITION_ID), anyString())) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(NON_EXISTING_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNullTargetProcessDefinitionId() { + String message = "target process definition id is null"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(anyString(), isNull())) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, null) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNonExistingTargetProcessDefinitionId() { + String message = "target process definition with id " + NON_EXISTING_PROCESS_DEFINITION_ID + " does not exist"; + JoinedMigrationPlanBuilderMock migrationPlanBuilder = mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + when(runtimeServiceMock.createMigrationPlan(anyString(), eq(NON_EXISTING_PROCESS_DEFINITION_ID))) + .thenReturn(migrationPlanBuilder); + when(migrationPlanBuilder.build()).thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, NON_EXISTING_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNullSourceActivityId() { + String message = "sourceActivityId is null"; + when(migrationPlanBuilderMock.mapActivities(isNull(), anyString())) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(null, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNonExistingSourceActivityId() { + String message = "sourceActivity is null"; + when(migrationPlanBuilderMock.mapActivities(eq(NON_EXISTING_ACTIVITY_ID), anyString())) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(NON_EXISTING_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNullTargetActivityId() { + String message = "targetActivityId is null"; + when(migrationPlanBuilderMock.mapActivities(anyString(), isNull())) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, null) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanAsyncWithNonExistingTargetActivityId() { + String message = "targetActivity is null"; + when(migrationPlanBuilderMock.mapActivities(anyString(), eq(NON_EXISTING_ACTIVITY_ID))) + .thenThrow(new BadUserRequestException(message)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, NON_EXISTING_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MIGRATION_URL); + } + + @Test + public void executeMigrationPlanAsyncValidationException() { + + MigrationInstruction migrationInstruction = mock(MigrationInstruction.class); + when(migrationInstruction.getSourceActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(migrationInstruction.getTargetActivityId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + + MigrationInstructionValidationReport instructionReport1 = mock(MigrationInstructionValidationReport.class); + when(instructionReport1.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instructionReport1.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationInstructionValidationReport instructionReport2 = mock(MigrationInstructionValidationReport.class); + when(instructionReport2.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instructionReport2.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + when(validationReport.getInstructionReports()).thenReturn(Arrays.asList(instructionReport1, instructionReport2)); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(MigrationPlanValidationException.class.getSimpleName())) + .body("message", is("fooo")) + .body("validationReport.instructionReports", hasSize(2)) + .body("validationReport.instructionReports[0].instruction.sourceActivityIds", hasSize(1)) + .body("validationReport.instructionReports[0].instruction.sourceActivityIds[0]", is(EXAMPLE_ACTIVITY_ID)) + .body("validationReport.instructionReports[0].instruction.targetActivityIds", hasSize(1)) + .body("validationReport.instructionReports[0].instruction.targetActivityIds[0]", is(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .body("validationReport.instructionReports[0].failures", hasSize(2)) + .body("validationReport.instructionReports[0].failures[0]", is("failure1")) + .body("validationReport.instructionReports[0].failures[1]", is("failure2")) + .when() + .post(EXECUTE_MIGRATION_ASYNC_URL); + } + + @Test + public void executeMigrationPlanUpdateEventTrigger() { + Map migrationExecution = new MigrationExecutionDtoBuilder() + .migrationPlan(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID, true) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID, false) + .done() + .processInstances(EXAMPLE_PROCESS_INSTANCE_ID, ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationExecution) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MIGRATION_URL); + + verifyCreateMigrationPlanInteraction(migrationPlanBuilderMock, (Map) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_MIGRATION_PLAN)); + verifyMigrationPlanExecutionInteraction(migrationExecution); + } + + @Test + public void validateMigrationPlan() { + Map migrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .instruction(ANOTHER_EXAMPLE_ACTIVITY_ID, EXAMPLE_ACTIVITY_ID, true) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationPlan) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("instructionReports", hasSize(0)) + .body("variableReports.isEmpty()", is(true)) + .when() + .post(VALIDATE_MIGRATION_URL); + + verifyCreateMigrationPlanInteraction(migrationPlanBuilderMock, migrationPlan); + } + + @Test + public void validateMigrationPlanInstructionsValidationException() { + MigrationInstruction migrationInstruction = mock(MigrationInstruction.class); + when(migrationInstruction.getSourceActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(migrationInstruction.getTargetActivityId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + + MigrationInstructionValidationReport instructionReport1 = mock(MigrationInstructionValidationReport.class); + when(instructionReport1.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instructionReport1.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationInstructionValidationReport instructionReport2 = mock(MigrationInstructionValidationReport.class); + when(instructionReport2.getMigrationInstruction()).thenReturn(migrationInstruction); + when(instructionReport2.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + when(validationReport.getInstructionReports()).thenReturn(Arrays.asList(instructionReport1, instructionReport2)); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationPlan) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("instructionReports", hasSize(2)) + .body("instructionReports[0].instruction.sourceActivityIds", hasSize(1)) + .body("instructionReports[0].instruction.sourceActivityIds[0]", is(EXAMPLE_ACTIVITY_ID)) + .body("instructionReports[0].instruction.targetActivityIds", hasSize(1)) + .body("instructionReports[0].instruction.targetActivityIds[0]", is(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .body("instructionReports[0].failures", hasSize(2)) + .body("instructionReports[0].failures[0]", is("failure1")) + .body("instructionReports[0].failures[1]", is("failure2")) + .when() + .post(VALIDATE_MIGRATION_URL); + } + + @Test + public void validateMigrationPlanVariablesValidationException() { + MigrationInstruction migrationInstruction = mock(MigrationInstruction.class); + when(migrationInstruction.getSourceActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(migrationInstruction.getTargetActivityId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + + MigrationVariableValidationReport variableReport1 = mock(MigrationVariableValidationReport.class); + when(variableReport1.getTypedValue()).thenReturn(new StringValueImpl("bar")); + when(variableReport1.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationVariableValidationReport variableReport2 = mock(MigrationVariableValidationReport.class); + when(variableReport2.getTypedValue()).thenReturn(new LongValueImpl(8L)); + when(variableReport2.getFailures()).thenReturn(Arrays.asList("failure1", "failure2")); + + MigrationPlanValidationReport validationReport = mock(MigrationPlanValidationReport.class); + Map reports = new HashMap<>(); + reports.put("foo", variableReport1); + reports.put("bar", variableReport2); + when(validationReport.getVariableReports()).thenReturn(reports); + + when(migrationPlanBuilderMock.build()).thenThrow(new MigrationPlanValidationException("fooo", validationReport)); + + Map migrationPlan = new MigrationPlanDtoBuilder(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .instruction(EXAMPLE_ACTIVITY_ID, ANOTHER_EXAMPLE_ACTIVITY_ID) + .build(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(migrationPlan) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("variableReports.foo.type", is("String")) + .body("variableReports.foo.value", is("bar")) + .body("variableReports.foo.failures", hasSize(2)) + .body("variableReports.foo.failures[0]", is("failure1")) + .body("variableReports.foo.failures[1]", is("failure2")) + .body("variableReports.bar.type", is("Long")) + .body("variableReports.bar.value", is(8)) + .body("variableReports.bar.failures", hasSize(2)) + .body("variableReports.bar.failures[0]", is("failure1")) + .body("variableReports.bar.failures[1]", is("failure2")) + .when() + .post(VALIDATE_MIGRATION_URL); + } + + protected void verifyGenerateMigrationPlanResponse(Response response) { + String responseContent = response.asString(); + String sourceProcessDefinitionId = from(responseContent).getString("sourceProcessDefinitionId"); + String targetProcessDefinitionId = from(responseContent).getString("targetProcessDefinitionId"); + List> instructions = from(responseContent).getList("instructions"); + + assertThat(sourceProcessDefinitionId).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + assertThat(targetProcessDefinitionId).isEqualTo(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + + assertThat(instructions).hasSize(2); + assertThat(instructions.get(0)) + .containsEntry("sourceActivityIds", Collections.singletonList(EXAMPLE_ACTIVITY_ID)) + .containsEntry("targetActivityIds", Collections.singletonList(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .containsEntry("updateEventTrigger", false); + + assertThat(instructions.get(1)) + .containsEntry("sourceActivityIds", Collections.singletonList(ANOTHER_EXAMPLE_ACTIVITY_ID)) + .containsEntry("targetActivityIds", Collections.singletonList(EXAMPLE_ACTIVITY_ID)) + .containsEntry("updateEventTrigger", false); + } + + protected void verifyGenerateMigrationPlanInteraction(MigrationPlanBuilder migrationPlanBuilderMock, Map initialMigrationPlan) { + verify(runtimeServiceMock).createMigrationPlan(eq(initialMigrationPlan.get(MigrationPlanDtoBuilder.PROP_SOURCE_PROCESS_DEFINITION_ID).toString()), + eq(initialMigrationPlan.get(MigrationPlanDtoBuilder.PROP_TARGET_PROCESS_DEFINITION_ID).toString())); + // the map equal activities method should be called + verify(migrationPlanBuilderMock).mapEqualActivities(); + // other instructions are ignored + verify(migrationPlanBuilderMock, never()).mapActivities(anyString(), anyString()); + } + + protected void verifyCreateMigrationPlanInteraction(JoinedMigrationPlanBuilderMock migrationPlanBuilderMock, Map migrationPlan) { + verify(runtimeServiceMock).createMigrationPlan(migrationPlan.get(MigrationPlanDtoBuilder.PROP_SOURCE_PROCESS_DEFINITION_ID).toString(), + migrationPlan.get(MigrationPlanDtoBuilder.PROP_TARGET_PROCESS_DEFINITION_ID).toString()); + // the map equal activities method should not be called + verify(migrationPlanBuilderMock, never()).mapEqualActivities(); + // all instructions are added + List> instructions = (List>) migrationPlan.get(MigrationPlanDtoBuilder.PROP_INSTRUCTIONS); + if (instructions != null) { + for (Map migrationInstructionDto : instructions) { + + InOrder inOrder = Mockito.inOrder(migrationPlanBuilderMock); + String sourceActivityId = ((List) migrationInstructionDto.get(MigrationInstructionDtoBuilder.PROP_SOURCE_ACTIVITY_IDS)).get(0); + String targetActivityId = ((List) migrationInstructionDto.get(MigrationInstructionDtoBuilder.PROP_TARGET_ACTIVITY_IDS)).get(0); + inOrder.verify(migrationPlanBuilderMock).mapActivities(eq(sourceActivityId), eq(targetActivityId)); + Boolean updateEventTrigger = (Boolean) migrationInstructionDto.get(MigrationInstructionDtoBuilder.PROP_UPDATE_EVENT_TRIGGER); + if (Boolean.TRUE.equals(updateEventTrigger)) { + inOrder.verify(migrationPlanBuilderMock, immediatelyAfter()).updateEventTrigger(); + } + } + } + } + + protected void verifyMigrationPlanExecutionInteraction(Map migrationExecution) { + InOrder inOrder = inOrder(runtimeServiceMock, migrationPlanExecutionBuilderMock); + + inOrder.verify(runtimeServiceMock).newMigration(any(MigrationPlan.class)); + + verifyMigrationExecutionBuilderInteraction(inOrder, migrationExecution); + inOrder.verify(migrationPlanExecutionBuilderMock).execute(); + + inOrder.verifyNoMoreInteractions(); + } + + protected void verifyMigrationPlanAsyncExecutionInteraction(Map migrationExecution) { + InOrder inOrder = inOrder(runtimeServiceMock, migrationPlanExecutionBuilderMock); + + inOrder.verify(runtimeServiceMock).newMigration(any(MigrationPlan.class)); + + verifyMigrationExecutionBuilderInteraction(inOrder, migrationExecution); + inOrder.verify(migrationPlanExecutionBuilderMock).executeAsync(); + + Mockito.verifyNoMoreInteractions(migrationPlanExecutionBuilderMock); + } + + protected void verifyMigrationExecutionBuilderInteraction(InOrder inOrder, Map migrationExecution) { + List processInstanceIds = ((List) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_PROCESS_INSTANCE_IDS)); + + inOrder.verify(migrationPlanExecutionBuilderMock).processInstanceIds(eq(processInstanceIds)); + ProcessInstanceQueryDto processInstanceQuery = (ProcessInstanceQueryDto) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_PROCESS_INSTANCE_QUERY); + if (processInstanceQuery != null) { + verifyMigrationPlanExecutionProcessInstanceQuery(inOrder); + } + Boolean skipCustomListeners = (Boolean) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_SKIP_CUSTOM_LISTENERS); + if (Boolean.TRUE.equals(skipCustomListeners)) { + inOrder.verify(migrationPlanExecutionBuilderMock).skipCustomListeners(); + } + Boolean skipIoMappings = (Boolean) migrationExecution.get(MigrationExecutionDtoBuilder.PROP_SKIP_IO_MAPPINGS); + if (Boolean.TRUE.equals(skipIoMappings)) { + inOrder.verify(migrationPlanExecutionBuilderMock).skipIoMappings(); + } + } + + protected void verifyMigrationPlanExecutionProcessInstanceQuery(InOrder inOrder) { + ArgumentCaptor queryCapture = ArgumentCaptor.forClass(ProcessInstanceQuery.class); + inOrder.verify(migrationPlanExecutionBuilderMock).processInstanceQuery(queryCapture.capture()); + + ProcessInstanceQueryImpl actualQuery = (ProcessInstanceQueryImpl) queryCapture.getValue(); + assertThat(actualQuery).isNotNull(); + assertThat(actualQuery.getProcessDefinitionId()).isEqualTo(EXAMPLE_PROCESS_DEFINITION_ID); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ModificationRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ModificationRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..757cc2cb6be46ea21a92574067c9020ff7f521fb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ModificationRestServiceInteractionTest.java @@ -0,0 +1,961 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockBatch; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl; +import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.ModificationInstructionBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.ModificationBuilder; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; + +public class ModificationRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/modification"; + protected static final String EXECUTE_MODIFICATION_SYNC_URL = PROCESS_INSTANCE_URL + "/execute"; + protected static final String EXECUTE_MODIFICATION_ASYNC_URL = PROCESS_INSTANCE_URL + "/executeAsync"; + + protected RuntimeService runtimeServiceMock; + protected HistoryService historyServiceMock; + protected ModificationBuilder modificationBuilderMock; + + @Before + public void setUpRuntimeData() { + runtimeServiceMock = mock(RuntimeService.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + + historyServiceMock = mock(HistoryService.class); + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + modificationBuilderMock = mock(ModificationBuilder.class); + when(modificationBuilderMock.cancelAllForActivity(any())).thenReturn(modificationBuilderMock); + when(modificationBuilderMock.startAfterActivity(any())).thenReturn(modificationBuilderMock); + when(modificationBuilderMock.startBeforeActivity(any())).thenReturn(modificationBuilderMock); + when(modificationBuilderMock.startTransition(any())).thenReturn(modificationBuilderMock); + when(modificationBuilderMock.processInstanceIds(Mockito.>any())).thenReturn(modificationBuilderMock); + + Batch batchMock = createMockBatch(); + when(modificationBuilderMock.executeAsync()).thenReturn(batchMock); + + when(runtimeServiceMock.createModification(any())).thenReturn(modificationBuilderMock); + } + + @Test + public void executeModificationSync() { + Map json = new HashMap(); + json.put("skipCustomListeners", true); + json.put("skipIoMappings", true); + json.put("processDefinitionId", "processDefinitionId"); + json.put("processInstanceIds", Arrays.asList("100", "20")); + List> instructions = new ArrayList>(); + + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + + json.put("instructions", instructions); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + verify(runtimeServiceMock).createModification("processDefinitionId"); + verify(modificationBuilderMock).processInstanceIds(eq(Arrays.asList("100", "20"))); + verify(modificationBuilderMock).cancelAllForActivity("activityId"); + verify(modificationBuilderMock).startBeforeActivity("activityId"); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).startTransition("transitionId"); + verify(modificationBuilderMock).skipCustomListeners(); + verify(modificationBuilderMock).skipIoMappings(); + verify(modificationBuilderMock).execute(); + } + + @Test + public void executeModificationWithNullProcessDefinitionIdAsync() { + doThrow(new BadUserRequestException("processDefinitionId must be set")) + .when(modificationBuilderMock).executeAsync(); + + Map json = new HashMap(); + json.put("skipCustomListeners", true); + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("100", "20")); + List> instructions = new ArrayList>(); + + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + + json.put("instructions", instructions); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(runtimeServiceMock).createModification(null); + verify(modificationBuilderMock).processInstanceIds(eq(Arrays.asList("100", "20"))); + verify(modificationBuilderMock).cancelAllForActivity("activityId"); + verify(modificationBuilderMock).startBeforeActivity("activityId"); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).startTransition("transitionId"); + verify(modificationBuilderMock).skipCustomListeners(); + verify(modificationBuilderMock).skipIoMappings(); + verify(modificationBuilderMock).executeAsync(); + } + + @Test + public void executeModificationWithNullProcessDefinitionIdSync() { + doThrow(new BadUserRequestException("processDefinitionId must be set")) + .when(modificationBuilderMock).execute(); + + Map json = new HashMap(); + json.put("skipCustomListeners", true); + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("100", "20")); + List> instructions = new ArrayList>(); + + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + + json.put("instructions", instructions); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + verify(runtimeServiceMock).createModification(null); + verify(modificationBuilderMock).processInstanceIds(eq(Arrays.asList("100", "20"))); + verify(modificationBuilderMock).cancelAllForActivity("activityId"); + verify(modificationBuilderMock).startBeforeActivity("activityId"); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).startTransition("transitionId"); + verify(modificationBuilderMock).skipCustomListeners(); + verify(modificationBuilderMock).skipIoMappings(); + verify(modificationBuilderMock).execute(); + } + + @Test + public void executeModificationWithNullProcessInstanceIdsSync() { + Map json = new HashMap(); + String message = "Process instance ids is null"; + doThrow(new BadUserRequestException(message)) + .when(modificationBuilderMock).execute(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId(EXAMPLE_ACTIVITY_ID).getJson()); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + json.put("processDefinitionId", "processDefinitionId"); + json.put("instructions", instructions); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + } + + @Test + public void executeModificationAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + json.put("processDefinitionId", "processDefinitionId"); + json.put("instructions", instructions); + json.put("processInstanceIds", Arrays.asList("100", "20")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(runtimeServiceMock).createModification("processDefinitionId"); + verify(modificationBuilderMock).processInstanceIds(eq(Arrays.asList("100", "20"))); + verify(modificationBuilderMock).cancelAllForActivity("activityId"); + verify(modificationBuilderMock).startBeforeActivity("activityId"); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).startTransition("transitionId"); + verify(modificationBuilderMock).executeAsync(); + } + + @Test + public void executeModificationWithNullProcessInstanceIdsAsync() { + Map json = new HashMap(); + + String message = "Process instance ids is null"; + doThrow(new BadUserRequestException(message)) + .when(modificationBuilderMock).executeAsync(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId(EXAMPLE_ACTIVITY_ID).getJson()); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + + json.put("instructions", instructions); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", is(message)) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeModificationWithValidProcessInstanceQuerySync() { + + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + json.put("processDefinitionId", "processDefinitionId"); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + processInstanceQueryDto.setBusinessKey("foo"); + + json.put("processInstanceQuery", processInstanceQueryDto); + json.put("instructions", instructions); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + verify(runtimeServiceMock, times(1)).createProcessInstanceQuery(); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).processInstanceQuery(processInstanceQueryDto.toQuery(processEngine)); + verify(modificationBuilderMock).execute(); + } + + @Test + public void executeModificationWithValidHistoricProcessInstanceQuerySync() { + + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + json.put("processDefinitionId", "processDefinitionId"); + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = new HistoricProcessInstanceQueryDto(); + historicProcessInstanceQueryDto.setProcessInstanceBusinessKey("foo"); + + json.put("historicProcessInstanceQuery", historicProcessInstanceQueryDto); + + json.put("instructions", instructions); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + verify(historyServiceMock, times(1)).createHistoricProcessInstanceQuery(); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).historicProcessInstanceQuery(historicProcessInstanceQueryDto.toQuery(processEngine)); + verify(modificationBuilderMock).execute(); + } + + + @Test + public void executeModificationWithValidProcessInstanceQueryAsync() { + + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + processInstanceQueryDto.setBusinessKey("foo"); + + json.put("processInstanceQuery", processInstanceQueryDto); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(runtimeServiceMock, times(1)).createProcessInstanceQuery(); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).processInstanceQuery(processInstanceQueryDto.toQuery(processEngine)); + verify(modificationBuilderMock).executeAsync(); + } + + @Test + public void executeModificationWithValidHistoricProcessInstanceQueryAsync() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = new HistoricProcessInstanceQueryDto(); + historicProcessInstanceQueryDto.setProcessInstanceBusinessKey("foo"); + + json.put("historicProcessInstanceQuery", historicProcessInstanceQueryDto); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(historyServiceMock, times(1)).createHistoricProcessInstanceQuery(); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).historicProcessInstanceQuery(historicProcessInstanceQueryDto.toQuery(processEngine)); + verify(modificationBuilderMock).executeAsync(); + } + + @Test + public void executeModificationWithBothProcessInstanceQueries() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = new HistoricProcessInstanceQueryDto(); + historicProcessInstanceQueryDto.setProcessInstanceBusinessKey("foo"); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + processInstanceQueryDto.setBusinessKey("foo"); + + json.put("processInstanceQuery", processInstanceQueryDto); + json.put("historicProcessInstanceQuery", historicProcessInstanceQueryDto); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(historyServiceMock, times(1)).createHistoricProcessInstanceQuery(); + verify(modificationBuilderMock).startAfterActivity("activityId"); + verify(modificationBuilderMock).historicProcessInstanceQuery(historicProcessInstanceQueryDto.toQuery(processEngine)); + verify(runtimeServiceMock, times(1)).createProcessInstanceQuery(); + verify(modificationBuilderMock).processInstanceQuery(processInstanceQueryDto.toQuery(processEngine)); + verify(modificationBuilderMock).executeAsync(); + } + + @Test + public void executeModificationWithInvalidProcessInstanceQuerySync() { + + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + Map json = new HashMap(); + + String message = "Process instance ids is null"; + doThrow(new BadUserRequestException(message)).when(modificationBuilderMock).execute(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("acivityId").getJson()); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + processInstanceQueryDto.setBusinessKey("foo"); + json.put("processInstanceQuery", processInstanceQueryDto); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + } + + @Test + public void executeModificationWithInvalidHistoricProcessInstanceQuerySync() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + + Map json = new HashMap(); + + String message = "Process instance ids is null"; + doThrow(new BadUserRequestException(message)).when(modificationBuilderMock).execute(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("acivityId").getJson()); + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = new HistoricProcessInstanceQueryDto(); + historicProcessInstanceQueryDto.setProcessInstanceBusinessKey("foo"); + + json.put("historicProcessInstanceQuery", historicProcessInstanceQueryDto); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + } + + @Test + public void executeModificationWithInvalidProcessInstanceQueryAsync() { + + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("acivityId").getJson()); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + processInstanceQueryDto.setBusinessKey("foo"); + json.put("processInstanceQuery", processInstanceQueryDto); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeModificationWithInvalidHistoricProcessInstanceQueryAsync() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("acivityId").getJson()); + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = new HistoricProcessInstanceQueryDto(); + historicProcessInstanceQueryDto.setProcessInstanceBusinessKey("foo"); + + json.put("historicProcessInstanceQuery", historicProcessInstanceQueryDto); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeModificationWithNullInstructionsSync() { + doThrow(new BadUserRequestException("Instructions must be set")).when(modificationBuilderMock).execute(); + + Map json = new HashMap(); + json.put("processInstanceIds", Arrays.asList("200", "11")); + json.put("skipIoMappings", true); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Instructions must be set")) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + } + + @Test + public void executeModificationWithNullInstructionsAsync() { + doThrow(new BadUserRequestException("Instructions must be set")).when(modificationBuilderMock).executeAsync(); + Map json = new HashMap(); + json.put("processInstanceIds", Arrays.asList("200", "11")); + json.put("skipIoMappings", true); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Instructions must be set")) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeModificationThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(modificationBuilderMock).executeAsync(); + + Map json = new HashMap(); + + List> instructions = new ArrayList>(); + + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + + json.put("instructions", instructions); + json.put("processInstanceIds", Arrays.asList("200", "323")); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeInvalidModificationForStartAfterSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startAfter().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startAfterActivity': 'activityId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + } + + @Test + public void executeInvalidModificationForStartAfterAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startAfter().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startAfterActivity': 'activityId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeInvalidModificationForStartBeforeSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startBefore().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startBeforeActivity': 'activityId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + } + + @Test + public void executeInvalidModificationForStartBeforeAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startBefore().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startBeforeActivity': 'activityId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeInvalidModificationForStartTransitionSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startTransition().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startTransition': 'transitionId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + } + + @Test + public void executeInvalidModificationForStartTransitionAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startTransition().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startTransition': 'transitionId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeInvalidModificationForCancelAllSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.cancellation().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'cancel': 'activityId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + } + + @Test + public void executeInvalidModificationForCancelAllAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.cancellation().getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'cancel': 'activityId' must be set")) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + } + + @Test + public void executeCancellationWithActiveFlagSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").cancelCurrentActiveActivityInstances(true).getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + verify(modificationBuilderMock).cancelAllForActivity("activityId", true); + verify(modificationBuilderMock).execute(); + } + + @Test + public void executeCancellationWithActiveFlagAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").cancelCurrentActiveActivityInstances(true).getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(modificationBuilderMock).cancelAllForActivity("activityId", true); + verify(modificationBuilderMock).executeAsync(); + } + + @Test + public void executeCancellationWithoutActiveFlagSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").cancelCurrentActiveActivityInstances(false).getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + verify(modificationBuilderMock).cancelAllForActivity("activityId"); + verify(modificationBuilderMock).execute(); + } + + @Test + public void executeCancellationWithoutActiveFlagAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").cancelCurrentActiveActivityInstances(false).getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(modificationBuilderMock).cancelAllForActivity("activityId"); + verify(modificationBuilderMock).executeAsync(); + } + + @Test + public void executeSyncModificationWithAnnotation() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipIoMappings", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").cancelCurrentActiveActivityInstances(false).getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + json.put("annotation", "anAnnotation"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_SYNC_URL); + + verify(modificationBuilderMock).skipIoMappings(); + verify(modificationBuilderMock).cancelAllForActivity("activityId"); + verify(modificationBuilderMock).setAnnotation("anAnnotation"); + verify(modificationBuilderMock).execute(); + } + + @Test + public void executeAsyncModificationWithAnnotation() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("skipCustomListeners", true); + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("processDefinitionId", "processDefinitionId"); + json.put("annotation", "anAnnotation"); + + given() + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(EXECUTE_MODIFICATION_ASYNC_URL); + + verify(modificationBuilderMock).skipCustomListeners(); + verify(modificationBuilderMock).startBeforeActivity("activityId"); + verify(modificationBuilderMock).setAnnotation("anAnnotation"); + verify(modificationBuilderMock).executeAsync(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/NonPersistenceConnectionExceptionLoggingTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/NonPersistenceConnectionExceptionLoggingTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ab603096360de263bdb17b4f0ee74a50b98c2f99 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/NonPersistenceConnectionExceptionLoggingTest.java @@ -0,0 +1,91 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.impl.util.ExceptionUtil.PERSISTENCE_EXCEPTION_MESSAGE; +import static org.camunda.bpm.engine.impl.util.ExceptionUtil.wrapPersistenceException; +import static org.camunda.bpm.engine.rest.exception.ExceptionLogger.REST_API; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_USER_FIRST_NAME; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import java.sql.SQLNonTransientConnectionException; +import java.util.List; +import org.apache.ibatis.exceptions.PersistenceException; +import org.camunda.bpm.engine.ProcessEnginePersistenceException; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.commons.testing.ProcessEngineLoggingRule; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +/** + * Tests Connection Exceptions that do not originate from persistence layer but are still connection exceptions. + */ +public class NonPersistenceConnectionExceptionLoggingTest extends AbstractRestServiceTest { + + protected static final String USER_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/user"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + @Rule + public ProcessEngineLoggingRule loggingRule = new ProcessEngineLoggingRule() + .watch(REST_API); + + @Test + public void shouldLogNonPersistenceExceptionOnWarning() { + stubFailingUserQuery(new SQLNonTransientConnectionException()); + + String expectedMessage = PERSISTENCE_EXCEPTION_MESSAGE; + + given().queryParam("firstName", EXAMPLE_USER_FIRST_NAME) + .then().expect() + .statusCode(500) + .body("type", equalTo("ProcessEnginePersistenceException")) + .body("message", equalTo(expectedMessage)) + .body("code", equalTo(0)) + .when().get(USER_QUERY_URL); + + verifyLogs(Level.WARN, expectedMessage); + } + + protected void verifyLogs(Level logLevel, String message) { + List logs = loggingRule.getLog(); + + assertThat(logs).hasSize(1); + assertThat(logs.get(0).getLevel()).isEqualTo(logLevel); + assertThat(logs.get(0).getMessage()).containsIgnoringCase(message); + } + + protected void stubFailingUserQuery(Exception secondRootCause) { + UserQuery result = mock(UserQuery.class); + + PersistenceException persistenceException = new PersistenceException("Failed to execute list", secondRootCause); + ProcessEnginePersistenceException exception = wrapPersistenceException(persistenceException); + + when(result.list()).thenThrow(exception); + when(processEngine.getIdentityService().createUserQuery()).thenReturn(result); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/PasswordPolicyServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/PasswordPolicyServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9604bf761cfdf6a2a27dce55a0eafc637577114c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/PasswordPolicyServiceQueryTest.java @@ -0,0 +1,273 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.identity.PasswordPolicy; +import org.camunda.bpm.engine.identity.PasswordPolicyResult; +import org.camunda.bpm.engine.identity.PasswordPolicyRule; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.impl.identity.PasswordPolicyDigitRuleImpl; +import org.camunda.bpm.engine.impl.identity.PasswordPolicyLengthRuleImpl; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +/** + * @author Miklas Boskamp + */ +public class PasswordPolicyServiceQueryTest extends AbstractRestServiceTest { + + protected static final String QUERY_URL = TEST_RESOURCE_ROOT_PATH + IdentityRestService.PATH + "/password-policy"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected ProcessEngineConfiguration processEngineConfigurationMock = mock(ProcessEngineConfiguration.class); + + protected IdentityService identityServiceMock; + + @Before + public void setUpMocks() { + identityServiceMock = mock(IdentityService.class); + + when(processEngine.getProcessEngineConfiguration()) + .thenReturn(processEngineConfigurationMock); + + when(processEngine.getIdentityService()) + .thenReturn(identityServiceMock); + } + + @Test + public void shouldGetPolicy() { + when(processEngineConfigurationMock.isEnablePasswordPolicy()).thenReturn(true); + + PasswordPolicy passwordPolicyMock = mock(PasswordPolicy.class); + + when(identityServiceMock.getPasswordPolicy()) + .thenReturn(passwordPolicyMock); + + when(passwordPolicyMock.getRules()) + .thenReturn(Collections.singletonList(new PasswordPolicyDigitRuleImpl(1))); + + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("rules[0].placeholder", equalTo("PASSWORD_POLICY_DIGIT")) + .body("rules[0].parameter.minDigit", equalTo("1")) + .when() + .get(QUERY_URL); + } + + @Test + public void shouldReturnNotFound_PasswordPolicyDisabled() { + when(processEngineConfigurationMock.isEnablePasswordPolicy()).thenReturn(false); + + given() + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .get(QUERY_URL); + } + + @Test + public void shouldCheckInvalidPassword() { + when(processEngineConfigurationMock.isEnablePasswordPolicy()).thenReturn(true); + + PasswordPolicyResult passwordPolicyResultMock = mock(PasswordPolicyResult.class); + + when(identityServiceMock.checkPasswordAgainstPolicy(anyString(), (User)isNull())) + .thenReturn(passwordPolicyResultMock); + + when(passwordPolicyResultMock.getFulfilledRules()) + .thenReturn(Collections.singletonList(new PasswordPolicyDigitRuleImpl(1))); + + when(passwordPolicyResultMock.getViolatedRules()) + .thenReturn(Collections.singletonList(new PasswordPolicyLengthRuleImpl(1))); + + given() + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(Collections.singletonMap("password", "password")) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + + .body("rules[0].placeholder", equalTo("PASSWORD_POLICY_DIGIT")) + .body("rules[0].parameter.minDigit", equalTo("1")) + .body("rules[0].valid", equalTo(true)) + + .body("rules[1].placeholder", equalTo("PASSWORD_POLICY_LENGTH")) + .body("rules[1].parameter.minLength", equalTo("1")) + .body("rules[1].valid", equalTo(false)) + + .body("valid", equalTo(false)) + .when() + .post(QUERY_URL); + } + + @Test + public void shouldCheckValidPassword() { + when(processEngineConfigurationMock.isEnablePasswordPolicy()).thenReturn(true); + + PasswordPolicyResult passwordPolicyResultMock = mock(PasswordPolicyResult.class); + + when(identityServiceMock.checkPasswordAgainstPolicy(anyString(), (User)isNull())) + .thenReturn(passwordPolicyResultMock); + + when(passwordPolicyResultMock.getFulfilledRules()) + .thenReturn(Collections.singletonList(new PasswordPolicyDigitRuleImpl(1))); + + when(passwordPolicyResultMock.getViolatedRules()) + .thenReturn(Collections.emptyList()); + + given() + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(Collections.singletonMap("password", "password")) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("valid", equalTo(true)) + .when() + .post(QUERY_URL); + } + + @Test + public void shouldCheckPasswordPolicyWithUserData() { + when(processEngineConfigurationMock.isEnablePasswordPolicy()).thenReturn(true); + + User userMock = mock(User.class); + when(identityServiceMock.newUser(anyString())).thenReturn(userMock); + + PasswordPolicyResult passwordPolicyResultMock = mock(PasswordPolicyResult.class); + + when(identityServiceMock.checkPasswordAgainstPolicy(anyString(), any(User.class))) + .thenReturn(passwordPolicyResultMock); + + when(passwordPolicyResultMock.getFulfilledRules()) + .thenReturn(Collections.emptyList()); + + when(passwordPolicyResultMock.getViolatedRules()) + .thenReturn(Collections.emptyList()); + + Map payload = new HashMap<>(); + payload.put("password", "myCandidatePassword"); + + Map profile = new HashMap<>(); + profile.put("id", "myId"); + profile.put("firstName", "foo"); + profile.put("lastName", "bar"); + profile.put("email", "baz"); + payload.put("profile", profile); + + given() + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(payload) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("valid", equalTo(true)) + .when() + .post(QUERY_URL); + + verify(identityServiceMock) + .checkPasswordAgainstPolicy("myCandidatePassword", userMock); + verify(identityServiceMock).newUser("myId"); + verify(userMock).setFirstName("foo"); + verify(userMock).setLastName("bar"); + verify(userMock).setEmail("baz"); + } + + @Test + public void shouldCheckPasswordPolicyWithUserDataAndUserIdNull() { + when(processEngineConfigurationMock.isEnablePasswordPolicy()).thenReturn(true); + + User userMock = mock(User.class); + when(identityServiceMock.newUser(anyString())).thenReturn(userMock); + + PasswordPolicyResult passwordPolicyResultMock = mock(PasswordPolicyResult.class); + + when(identityServiceMock.checkPasswordAgainstPolicy(anyString(), any(User.class))) + .thenReturn(passwordPolicyResultMock); + + when(passwordPolicyResultMock.getFulfilledRules()) + .thenReturn(Collections.emptyList()); + + when(passwordPolicyResultMock.getViolatedRules()) + .thenReturn(Collections.emptyList()); + + Map payload = new HashMap<>(); + payload.put("password", "myCandidatePassword"); + + Map profile = new HashMap<>(); + profile.put("id", null); + payload.put("profile", profile); + + given() + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(payload) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("valid", equalTo(true)) + .when() + .post(QUERY_URL); + + verify(identityServiceMock) + .checkPasswordAgainstPolicy("myCandidatePassword", userMock); + verify(identityServiceMock).newUser(""); + } + + @Test + public void shouldCheckPasswordAgainstNoPolicy() { + when(processEngineConfigurationMock.isEnablePasswordPolicy()).thenReturn(false); + + given() + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(Collections.singletonMap("password", "password")) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .when() + .post(QUERY_URL); + } + +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/PersistenceConnectionExceptionLoggingTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/PersistenceConnectionExceptionLoggingTest.java new file mode 100644 index 0000000000000000000000000000000000000000..01ad65b1fa6debc34cd56885930b20f7f9482268 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/PersistenceConnectionExceptionLoggingTest.java @@ -0,0 +1,147 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.impl.util.ExceptionUtil.PERSISTENCE_EXCEPTION_MESSAGE; +import static org.camunda.bpm.engine.impl.util.ExceptionUtil.wrapPersistenceException; +import static org.camunda.bpm.engine.rest.exception.ExceptionLogger.REST_API; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_USER_FIRST_NAME; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import org.apache.ibatis.exceptions.PersistenceException; +import org.camunda.bpm.engine.ProcessEnginePersistenceException; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.commons.testing.ProcessEngineLoggingRule; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +/** + * Test for Connection Exceptions that originate from the persistence layer. + */ +@RunWith(Parameterized.class) +public class PersistenceConnectionExceptionLoggingTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + @Rule + public ProcessEngineLoggingRule loggingRule = new ProcessEngineLoggingRule() + .watch(REST_API); + + protected static final String USER_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/user"; + + private final ConnectionSubclass subclass; + + public PersistenceConnectionExceptionLoggingTest(ConnectionSubclass subclass) { + this.subclass = subclass; + } + + @Parameters(name = "{index}: {0}") + public static Collection data() { + ConnectionSubclass[] values = ConnectionSubclass.values(); + + return Arrays.stream(values) + .map(c -> new Object[] {c}) + .collect(Collectors.toList()); + } + + @Test + public void shouldLogPersistenceConnectionExceptionOnError() { + stubFailingUserQuery(subclass); + + String expectedMessage = PERSISTENCE_EXCEPTION_MESSAGE; + + given().queryParam("firstName", EXAMPLE_USER_FIRST_NAME) + .then().expect() + .statusCode(500) + .body("type", equalTo("ProcessEnginePersistenceException")) + .body("message", equalTo(expectedMessage)) + .body("code", equalTo(0)) + .when().get(USER_QUERY_URL); + + verifyLogs(Level.ERROR, expectedMessage); + } + + protected void verifyLogs(Level logLevel, String message) { + List logs = loggingRule.getLog(); + + assertThat(logs).hasSize(1); + assertThat(logs.get(0).getLevel()).isEqualTo(logLevel); + assertThat(logs.get(0).getMessage()).containsIgnoringCase(message); + } + + protected void stubFailingUserQuery(ConnectionSubclass subclass) { + UserQuery result = mock(UserQuery.class); + + + when(result.list()).thenThrow(createPersistenceException("list", subclass)); + when(processEngine.getIdentityService().createUserQuery()).thenReturn(result); + } + + private ProcessEnginePersistenceException createPersistenceException(String operation, ConnectionSubclass subclass) { + SQLException sqlException = new SQLException(subclass.message(), subclass.sqlState()); + PersistenceException persistenceException = new PersistenceException("Failed to execute " + operation, sqlException); + + return wrapPersistenceException(persistenceException); + } + + public enum ConnectionSubclass { + + CLIENT_UNABLE("001", "SQL-client unable to establish SQL-connection"), + NAME_IN_USE("002", "connection name in use"), + NOT_EXISTS("003", "connection does not exist"), + SERVER_REJECT("004", "SQL-server rejected establishment of SQL-connection"), + FAILURE("006", "connection failure"), + UNKNOWN_TX_RESOLUTION("007", "transaction resolution unknown"), + + UNKNOWN("XXX", "This is a dummy subclass"); + + private final String subclass; + private final String message; + + ConnectionSubclass(String subclass, String message) { + this.subclass = subclass; + this.message = message; + } + + public String sqlState() { + return "08" + subclass; + } + + public String message() { + return message; + } + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4491625f85476e55685d82d45cd741eb3eea36ce --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestServiceInteractionTest.java @@ -0,0 +1,4131 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.camunda.bpm.ProcessApplicationService; +import org.camunda.bpm.application.ProcessApplicationInfo; +import org.camunda.bpm.container.RuntimeContainerDelegate; +import org.camunda.bpm.engine.*; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.form.StartFormData; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.impl.repository.CalledProcessDefinitionImpl; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.impl.util.ReflectUtil; +import org.camunda.bpm.engine.repository.CalledProcessDefinition; +import org.camunda.bpm.engine.repository.DeleteProcessDefinitionsBuilder; +import org.camunda.bpm.engine.repository.DeleteProcessDefinitionsSelectBuilder; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.HistoryTimeToLiveDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.impl.form.validator.FormFieldValidationException; +import org.camunda.bpm.engine.rest.helper.*; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.sub.repository.impl.ProcessDefinitionResourceImpl; +import org.camunda.bpm.engine.rest.util.EncodingUtil; +import org.camunda.bpm.engine.rest.util.ModificationInstructionBuilder; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.ProcessInstanceWithVariables; +import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.impl.VariableMapImpl; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.assertj.core.api.Assertions; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; +import java.io.*; +import java.net.URISyntaxException; +import java.util.*; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockSerializedVariables; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.isNull; +import static org.mockito.Mockito.*; + +public class ProcessDefinitionRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_DEFINITION_URL = TEST_RESOURCE_ROOT_PATH + "/process-definition"; + protected static final String SINGLE_PROCESS_DEFINITION_URL = PROCESS_DEFINITION_URL + "/{id}"; + protected static final String SINGLE_PROCESS_DEFINITION_BY_KEY_URL = PROCESS_DEFINITION_URL + "/key/{key}"; + protected static final String SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_URL = PROCESS_DEFINITION_URL + "/key/{key}/tenant-id/{tenant-id}"; + + protected static final String START_PROCESS_INSTANCE_URL = SINGLE_PROCESS_DEFINITION_URL + "/start"; + protected static final String START_PROCESS_INSTANCE_BY_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/start"; + protected static final String START_PROCESS_INSTANCE_BY_KEY_AND_TENANT_ID_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_URL + "/start"; + + protected static final String XML_DEFINITION_URL = SINGLE_PROCESS_DEFINITION_URL + "/xml"; + protected static final String XML_DEFINITION_BY_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/xml"; + protected static final String DIAGRAM_DEFINITION_URL = SINGLE_PROCESS_DEFINITION_URL + "/diagram"; + protected static final String DIAGRAM_DEFINITION_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/diagram"; + + protected static final String START_FORM_URL = SINGLE_PROCESS_DEFINITION_URL + "/startForm"; + protected static final String START_FORM_BY_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/startForm"; + protected static final String DEPLOYED_START_FORM_URL = SINGLE_PROCESS_DEFINITION_URL + "/deployed-start-form"; + protected static final String DEPLOYED_START_FORM_BY_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/deployed-start-form"; + protected static final String RENDERED_FORM_URL = SINGLE_PROCESS_DEFINITION_URL + "/rendered-form"; + protected static final String RENDERED_FORM_BY_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/rendered-form"; + protected static final String SUBMIT_FORM_URL = SINGLE_PROCESS_DEFINITION_URL + "/submit-form"; + protected static final String SUBMIT_FORM_BY_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/submit-form"; + protected static final String START_FORM_VARIABLES_URL = SINGLE_PROCESS_DEFINITION_URL + "/form-variables"; + protected static final String START_FORM_VARIABLES_BY_KEY_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/form-variables"; + + protected static final String SINGLE_PROCESS_DEFINITION_SUSPENDED_URL = SINGLE_PROCESS_DEFINITION_URL + "/suspended"; + protected static final String SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/suspended"; + protected static final String SINGLE_PROCESS_DEFINITION_HISTORY_TIMETOLIVE_URL = SINGLE_PROCESS_DEFINITION_URL + "/history-time-to-live"; + protected static final String PROCESS_DEFINITION_SUSPENDED_URL = PROCESS_DEFINITION_URL + "/suspended"; + protected static final String SINGLE_PROCESS_DEFINITION_BY_KEY_DELETE_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_URL + "/delete"; + protected static final String SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_DELETE_URL = SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_URL + "/delete"; + + protected static final String PROCESS_DEFINITION_CALL_ACTIVITY_MAPPINGS = SINGLE_PROCESS_DEFINITION_URL + "/static-called-process-definitions"; + + private RuntimeService runtimeServiceMock; + private RepositoryService repositoryServiceMock; + private FormService formServiceMock; + private ManagementService managementServiceMock; + private ProcessDefinitionQuery processDefinitionQueryMock; + private ProcessInstanceWithVariables mockInstance; + private ProcessInstantiationBuilder mockInstantiationBuilder; + + @Before + public void setUpRuntimeData() { + ProcessDefinition mockDefinition = MockProvider.createMockDefinition(); + setUpRuntimeDataForDefinition(mockDefinition); + + managementServiceMock = mock(ManagementService.class); + when(processEngine.getManagementService()).thenReturn(managementServiceMock); + when(managementServiceMock.getProcessApplicationForDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID)).thenReturn(MockProvider.EXAMPLE_PROCESS_APPLICATION_NAME); + + // replace the runtime container delegate & process application service with a mock + + ProcessApplicationService processApplicationService = mock(ProcessApplicationService.class); + ProcessApplicationInfo appMock = MockProvider.createMockProcessApplicationInfo(); + when(processApplicationService.getProcessApplicationInfo(MockProvider.EXAMPLE_PROCESS_APPLICATION_NAME)).thenReturn(appMock); + + RuntimeContainerDelegate delegate = mock(RuntimeContainerDelegate.class); + when(delegate.getProcessApplicationService()).thenReturn(processApplicationService); + RuntimeContainerDelegate.INSTANCE.set(delegate); + } + + private void setUpRuntimeDataForDefinition(ProcessDefinition mockDefinition) { + mockInstance = MockProvider.createMockInstanceWithVariables(); + + // we replace this mock with every test in order to have a clean one (in terms of invocations) for verification + runtimeServiceMock = mock(RuntimeService.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + when(runtimeServiceMock.startProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), Mockito.>any())).thenReturn(mockInstance); + when(runtimeServiceMock.startProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), any(), any(), any())).thenReturn(mockInstance); + + + mockInstantiationBuilder = setUpMockInstantiationBuilder(); + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())).thenReturn(mockInstance); + when(runtimeServiceMock.createProcessInstanceById(any())).thenReturn(mockInstantiationBuilder); + + + repositoryServiceMock = mock(RepositoryService.class); + when(processEngine.getRepositoryService()).thenReturn(repositoryServiceMock); + when(repositoryServiceMock.getProcessDefinition(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))).thenReturn(mockDefinition); + when(repositoryServiceMock.getProcessModel(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))).thenReturn(createMockProcessDefinionBpmn20Xml()); + + DeleteProcessDefinitionsSelectBuilder deleteProcessDefinitionsSelectBuilder = mock(DeleteProcessDefinitionsSelectBuilder.class, RETURNS_DEEP_STUBS); + when(repositoryServiceMock.deleteProcessDefinitions()).thenReturn(deleteProcessDefinitionsSelectBuilder); + + setUpMockDefinitionQuery(mockDefinition); + + StartFormData formDataMock = MockProvider.createMockStartFormData(mockDefinition); + formServiceMock = mock(FormService.class); + when(processEngine.getFormService()).thenReturn(formServiceMock); + when(formServiceMock.getStartFormData(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))).thenReturn(formDataMock); + when(formServiceMock.getStartFormKey(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))).thenReturn(MockProvider.EXAMPLE_FORM_KEY); + when(formServiceMock.submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), any())).thenReturn(mockInstance); + when(formServiceMock.submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), any(), any())).thenReturn(mockInstance); + + VariableMap startFormVariablesMock = MockProvider.createMockFormVariables(); + when(formServiceMock.getStartFormVariables(eq(EXAMPLE_PROCESS_DEFINITION_ID), any(), anyBoolean())).thenReturn(startFormVariablesMock); + + } + + private InputStream createMockProcessDefinionBpmn20Xml() { + // do not close the input stream, will be done in implementation + InputStream bpmn20XmlIn = null; + bpmn20XmlIn = ReflectUtil.getResourceAsStream("processes/fox-invoice_en_long_id.bpmn"); + Assert.assertNotNull(bpmn20XmlIn); + return bpmn20XmlIn; + } + + private void setUpMockDefinitionQuery(ProcessDefinition mockDefinition) { + processDefinitionQueryMock = mock(ProcessDefinitionQuery.class); + when(processDefinitionQueryMock.processDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.processDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.tenantIdIn(anyString())).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.withoutTenantId()).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.latestVersion()).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.singleResult()).thenReturn(mockDefinition); + when(processDefinitionQueryMock.count()).thenReturn(1L); + when(processDefinitionQueryMock.list()).thenReturn(Collections.singletonList(mockDefinition)); + when(repositoryServiceMock.createProcessDefinitionQuery()).thenReturn(processDefinitionQueryMock); + } + + @Test + public void testInstanceResourceLinkResult() { + String fullInstanceUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/process-instance/" + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("links[0].href", equalTo(fullInstanceUrl)) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testInstanceResourceLinkWithEnginePrefix() { + String startInstanceOnExplicitEngineUrl = TEST_RESOURCE_ROOT_PATH + "/engine/default/process-definition/{id}/start"; + + String fullInstanceUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/engine/default/process-instance/" + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("links[0].href", equalTo(fullInstanceUrl)) + .when().post(startInstanceOnExplicitEngineUrl); + } + + @Test + public void testProcessDefinitionBpmn20XmlRetrieval() { + // Rest-assured has problems with extracting json with escaped quotation marks, i.e. the xml content in our case + Response response = given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) +// .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) +// .body("bpmn20Xml", startsWith("anyContent"; + + when(formServiceMock.getRenderedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(expectedResult); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(XHTML_XML_CONTENT_TYPE) + .when() + .get(RENDERED_FORM_URL); + + String responseContent = response.asString(); + Assertions.assertThat(responseContent).isEqualTo(expectedResult); + } + + @Test + public void testGetRenderedStartFormForDifferentPlatformEncoding() throws NoSuchFieldException, IllegalAccessException, UnsupportedEncodingException { + String expectedResult = "unicode symbol: \u2200"; + when(formServiceMock.getRenderedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(expectedResult); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(XHTML_XML_CONTENT_TYPE) + .when() + .get(RENDERED_FORM_URL); + + String responseContent = new String(response.asByteArray(), EncodingUtil.DEFAULT_ENCODING); + Assertions.assertThat(responseContent).isEqualTo(expectedResult); + } + + @Test + public void testGetRenderedStartFormReturnsNotFound() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No matching rendered start form for process definition with the id " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + " found.")) + .when() + .get(RENDERED_FORM_URL); + } + + @Test + public void testGetRenderedStartFormThrowsAuthorizationException() { + String message = "expected exception"; + when(formServiceMock.getRenderedStartForm(anyString())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(RENDERED_FORM_URL); + } + + @Test + public void testSubmitStartForm() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_URL); + + verify(formServiceMock).submitStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, null); + } + + @Test + public void testSubmitStartFormWithParameters() { + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("anotherVariable", 42) + .variable("aThirdValue", Boolean.TRUE).getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aVariable", "aStringValue"); + expectedVariables.put("anotherVariable", 42); + expectedVariables.put("aThirdValue", Boolean.TRUE); + + verify(formServiceMock).submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testSubmitStartFormWithSerializedVariableValue() { + + String jsonValue = "{}"; + + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("aSerializedVariable", ValueType.OBJECT.getName(), jsonValue, "aFormat", "aRootType") + .getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_URL); + + verify(formServiceMock).submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), + argThat( + new EqualsVariableMap() + .matcher("aVariable", EqualsUntypedValue.matcher().value("aStringValue")) + .matcher("aSerializedVariable", EqualsObjectValue + .objectValueMatcher() + .serializedValue(jsonValue) + .serializationFormat("aFormat") + .objectTypeName("aRootType")))); + } + + @Test + public void testSubmitStartFormWithBase64EncodedBytes() { + + Map variables = VariablesBuilder.create() + .variable("aVariable", Base64.encodeBase64String("someBytes".getBytes()), ValueType.BYTES.getName()) + .getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_URL); + + verify(formServiceMock).submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), + argThat( + new EqualsVariableMap() + .matcher("aVariable", EqualsPrimitiveValue.bytesValue("someBytes".getBytes())))); + } + + @Test + public void testSubmitStartFormWithBusinessKey() { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_URL); + + verify(formServiceMock).submitStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, "myBusinessKey", null); + } + + @Test + public void testSubmitStartFormWithBusinessKeyAndParameters() { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("anotherVariable", 42) + .variable("aThirdValue", Boolean.TRUE).getVariables(); + + json.put("variables", variables); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aVariable", "aStringValue"); + expectedVariables.put("anotherVariable", 42); + expectedVariables.put("aThirdValue", Boolean.TRUE); + + verify(formServiceMock).submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), eq("myBusinessKey"), argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testSubmitStartFormWithUnparseableIntegerVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableShortVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableLongVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableDoubleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableDateVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitStartFormWithNotSupportedVariableType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: Unsupported value type 'X'")) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testUnsuccessfulSubmitStartForm() { + doThrow(new ProcessEngineException("expected exception")).when(formServiceMock).submitStartForm(any(String.class), Mockito.any()); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot instantiate process definition " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + ": expected exception")) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormByIdThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(formServiceMock).submitStartForm(any(String.class), Mockito.any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormByIdThrowsFormFieldValidationException() { + String message = "expected exception"; + doThrow(new FormFieldValidationException("form-exception", message)).when(formServiceMock).submitStartForm(any(String.class), Mockito.any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot instantiate process definition " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + ": " + message)) + .when() + .post(SUBMIT_FORM_URL); + } + + @Test + public void testGetStartFormVariables() { + + given().pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".value", equalTo(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".type", + equalTo(VariableTypeHelper.toExpectedValueTypeName(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getType()))) + .when().get(START_FORM_VARIABLES_URL) + .body(); + + verify(formServiceMock, times(1)).getStartFormVariables(EXAMPLE_PROCESS_DEFINITION_ID, null, true); + } + + @Test + public void testGetStartFormVariablesVarNames() { + + given() + .pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("variableNames", "a,b,c") + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .when().get(START_FORM_VARIABLES_URL); + + verify(formServiceMock, times(1)).getStartFormVariables(EXAMPLE_PROCESS_DEFINITION_ID, Arrays.asList("a", "b", "c"), true); + } + + @Test + public void testGetStartFormVariablesAndDoNotDeserializeVariables() { + + given() + .pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("deserializeValues", false) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".value", equalTo(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".type", + equalTo(VariableTypeHelper.toExpectedValueTypeName(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getType()))) + .when().get(START_FORM_VARIABLES_URL) + .body(); + + verify(formServiceMock, times(1)).getStartFormVariables(EXAMPLE_PROCESS_DEFINITION_ID, null, false); + } + + @Test + public void testGetStartFormVariablesVarNamesAndDoNotDeserializeVariables() { + + given() + .pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("deserializeValues", false) + .queryParam("variableNames", "a,b,c") + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .when().get(START_FORM_VARIABLES_URL); + + verify(formServiceMock, times(1)).getStartFormVariables(EXAMPLE_PROCESS_DEFINITION_ID, Arrays.asList("a", "b", "c"), false); + } + + @Test + public void testGetStartFormVariablesThrowsAuthorizationException() { + String message = "expected exception"; + when(formServiceMock.getStartFormVariables(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, null, true)).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(START_FORM_VARIABLES_URL); + } + + @Test + public void testSimpleProcessInstantiation() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testSimpleProcessInstantiationWithVariables() { + //mock process instance + ProcessInstanceWithVariables mockInstance = MockProvider.createMockInstanceWithVariables(); + ProcessInstantiationBuilder mockInstantiationBuilder = setUpMockInstantiationBuilder(); + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())).thenReturn(mockInstance); + when(runtimeServiceMock.createProcessInstanceById(anyString())).thenReturn(mockInstantiationBuilder); + + //given request with parameter withVariables to get variables in return + Map json = new HashMap<>(); + json.put("withVariablesInReturn", true); + + //when request then return process instance with serialized variables + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + //serialized variable + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(ArrayList.class.getName())) + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + //deserialized variable should also returned as serialized variable + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(Object.class.getName())) + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + .when().post(START_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + + } + + @Test + public void testProcessInstantiationWithParameters() throws IOException { + Map parameters = VariablesBuilder.create() + .variable("aBoolean", Boolean.TRUE) + .variable("aString", "aStringVariableValue") + .variable("anInteger", 42).getVariables(); + + Map json = new HashMap<>(); + json.put("variables", parameters); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + Map expectedParameters = new HashMap<>(); + expectedParameters.put("aBoolean", Boolean.TRUE); + expectedParameters.put("aString", "aStringVariableValue"); + expectedParameters.put("anInteger", 42); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).setVariables(argThat(new EqualsMap(expectedParameters))); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationWithBusinessKey() throws IOException { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).businessKey("myBusinessKey"); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationWithBusinessKeyAndParameters() throws IOException { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + Map parameters = VariablesBuilder.create() + .variable("aBoolean", Boolean.TRUE) + .variable("aString", "aStringVariableValue") + .variable("anInteger", 42).getVariables(); + + json.put("variables", parameters); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + Map expectedParameters = new HashMap<>(); + expectedParameters.put("aBoolean", Boolean.TRUE); + expectedParameters.put("aString", "aStringVariableValue"); + expectedParameters.put("anInteger", 42); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).businessKey("myBusinessKey"); + verify(mockInstantiationBuilder).setVariables(argThat(new EqualsMap(expectedParameters))); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationWithTransientVariables() throws IOException { + Map json = new HashMap<>(); + + json.put("variables", VariablesBuilder.create().variableTransient("foo", "bar", "string").getVariables()); + + final VariableMap varMap = new VariableMapImpl(); + + when(mockInstantiationBuilder.setVariables(anyMap())).thenAnswer(new Answer() { + @Override + public ProcessInstantiationBuilder answer(InvocationOnMock invocation) throws Throwable { + varMap.putAll((VariableMap) invocation.getArguments()[0]); + return mockInstantiationBuilder; + } + }); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + VariableMap expectedVariables = Variables.createVariables().putValueTyped("foo", Variables.stringValue("bar", true)); + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).setVariables(expectedVariables); + assertEquals(expectedVariables.getValueTyped("foo").isTransient(), varMap.getValueTyped("foo").isTransient()); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationAtActivitiesById() { + + Map json = new HashMap<>(); + json.put("variables", VariablesBuilder.create() + .variable("processVariable", "aString", "String").getVariables()); + json.put("businessKey", "aBusinessKey"); + json.put("caseInstanceId", "aCaseInstanceId"); + + List> startInstructions = new ArrayList<>(); + + startInstructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", "value", "String", false) + .variable("varLocal", "valueLocal", "String", true) + .getVariables()) + .getJson()); + startInstructions.add( + ModificationInstructionBuilder.startAfter() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", 52, "Integer", false) + .variable("varLocal", 74, "Integer", true) + .getVariables()) + .getJson()); + startInstructions.add( + ModificationInstructionBuilder.startTransition() + .transitionId("transitionId") + .variables(VariablesBuilder.create() + .variable("var", 53, "Integer", false) + .variable("varLocal", 75, "Integer", true) + .getVariables()) + .getJson()); + + + json.put("startInstructions", startInstructions); + + given().pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(EXAMPLE_PROCESS_DEFINITION_ID)); + + InOrder inOrder = inOrder(mockInstantiationBuilder); + + inOrder.verify(mockInstantiationBuilder).businessKey("aBusinessKey"); + inOrder.verify(mockInstantiationBuilder).caseInstanceId("aCaseInstanceId"); + inOrder.verify(mockInstantiationBuilder).setVariables(argThat(EqualsVariableMap.matches() + .matcher("processVariable", EqualsPrimitiveValue.stringValue("aString")))); + + inOrder.verify(mockInstantiationBuilder).startBeforeActivity("activityId"); + + verify(mockInstantiationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.stringValue("valueLocal"))); + verify(mockInstantiationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.stringValue("value"))); + + inOrder.verify(mockInstantiationBuilder).startAfterActivity("activityId"); + + verify(mockInstantiationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.integerValue(52))); + verify(mockInstantiationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.integerValue(74))); + + inOrder.verify(mockInstantiationBuilder).startTransition("transitionId"); + + verify(mockInstantiationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.integerValue(53))); + verify(mockInstantiationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.integerValue(75))); + + inOrder.verify(mockInstantiationBuilder).executeWithVariablesInReturn(false, false); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testProcessInstantiationAtActivitiesByIdWithVariablesInReturn() { + //set up variables and parameters + Map json = new HashMap<>(); + json.put("variables", VariablesBuilder.create() + .variable("processVariable", "aString", "String").getVariables()); + json.put("businessKey", "aBusinessKey"); + json.put("caseInstanceId", "aCaseInstanceId"); + + VariableMap variables = createMockSerializedVariables() + .putValueTyped("processVariable", Variables.stringValue("aString")) + .putValueTyped("var", Variables.stringValue("value")) + .putValueTyped("varLocal", Variables.stringValue("valueLocal")); + + //mock process instance and instantiation builder + ProcessInstanceWithVariables mockInstance = MockProvider.createMockInstanceWithVariables(); + when(mockInstance.getVariables()).thenReturn(variables); + + ProcessInstantiationBuilder mockInstantiationBuilder = setUpMockInstantiationBuilder(); + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())).thenReturn(mockInstance); + when(runtimeServiceMock.createProcessInstanceById(anyString())).thenReturn(mockInstantiationBuilder); + + //create instructions + List> startInstructions = new ArrayList<>(); + + startInstructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", "value", "String", false) + .variable("varLocal", "valueLocal", "String", true) + .getVariables()) + .getJson()); + + json.put("startInstructions", startInstructions); + json.put("withVariablesInReturn", true); + + //request which response should contain serialized variables of process instance + given().pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + //serialized variable + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(ArrayList.class.getName())) + .body("variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + //deserialized variable should also returned as serialized variable + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(Object.class.getName())) + .body("variables." + MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + .body("variables.processVariable.type", equalTo("String")) + .body("variables.processVariable.value", equalTo("aString")) + .body("variables.var.type", equalTo("String")) + .body("variables.var.value", equalTo("value")) + .body("variables.varLocal.type", equalTo("String")) + .body("variables.varLocal.value", equalTo("valueLocal")) + .when().post(START_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(EXAMPLE_PROCESS_DEFINITION_ID)); + } + + @Test + public void testProcessInstantiationAtActivitiesByKey() { + ProcessInstantiationBuilder mockInstantiationBuilder = setUpMockInstantiationBuilder(); + when(runtimeServiceMock.createProcessInstanceById(anyString())).thenReturn(mockInstantiationBuilder); + + Map json = new HashMap<>(); + json.put("variables", VariablesBuilder.create() + .variable("processVariable", "aString", "String").getVariables()); + json.put("businessKey", "aBusinessKey"); + json.put("caseInstanceId", "aCaseInstanceId"); + + List> startInstructions = new ArrayList<>(); + + startInstructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", "value", "String", false) + .variable("varLocal", "valueLocal", "String", true) + .getVariables()) + .getJson()); + startInstructions.add( + ModificationInstructionBuilder.startAfter() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", 52, "Integer", false) + .variable("varLocal", 74, "Integer", true) + .getVariables()) + .getJson()); + startInstructions.add( + ModificationInstructionBuilder.startTransition() + .transitionId("transitionId") + .variables(VariablesBuilder.create() + .variable("var", 53, "Integer", false) + .variable("varLocal", 75, "Integer", true) + .getVariables()) + .getJson()); + + + json.put("startInstructions", startInstructions); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + + InOrder inOrder = inOrder(mockInstantiationBuilder); + + inOrder.verify(mockInstantiationBuilder).businessKey("aBusinessKey"); + inOrder.verify(mockInstantiationBuilder).caseInstanceId("aCaseInstanceId"); + inOrder.verify(mockInstantiationBuilder).setVariables(argThat(EqualsVariableMap.matches() + .matcher("processVariable", EqualsPrimitiveValue.stringValue("aString")))); + + inOrder.verify(mockInstantiationBuilder).startBeforeActivity("activityId"); + + verify(mockInstantiationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.stringValue("valueLocal"))); + verify(mockInstantiationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.stringValue("value"))); + + inOrder.verify(mockInstantiationBuilder).startAfterActivity("activityId"); + + verify(mockInstantiationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.integerValue(52))); + verify(mockInstantiationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.integerValue(74))); + + inOrder.verify(mockInstantiationBuilder).startTransition("transitionId"); + + verify(mockInstantiationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.integerValue(53))); + verify(mockInstantiationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.integerValue(75))); + + inOrder.verify(mockInstantiationBuilder).executeWithVariablesInReturn(false, false); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testProcessInstantiationAtActivitiesSkipIoMappingsAndListeners() { + ProcessInstantiationBuilder mockInstantiationBuilder = setUpMockInstantiationBuilder(); + when(runtimeServiceMock.createProcessInstanceById(anyString())).thenReturn(mockInstantiationBuilder); + + Map json = new HashMap<>(); + + List> startInstructions = new ArrayList<>(); + + startInstructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .getJson()); + + json.put("startInstructions", startInstructions); + json.put("skipIoMappings", true); + json.put("skipCustomListeners", true); + + given().pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(EXAMPLE_PROCESS_DEFINITION_ID)); + + InOrder inOrder = inOrder(mockInstantiationBuilder); + + inOrder.verify(mockInstantiationBuilder).startBeforeActivity("activityId"); + inOrder.verify(mockInstantiationBuilder).executeWithVariablesInReturn(true, true); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testInvalidInstantiationAtActivities() { + ProcessInstantiationBuilder mockInstantiationBuilder = setUpMockInstantiationBuilder(); + when(runtimeServiceMock.createProcessInstanceById(anyString())).thenReturn(mockInstantiationBuilder); + + Map json = new HashMap<>(); + + // start before: missing activity id + List> instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startBefore().getJson()); + json.put("startInstructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("'activityId' must be set")) + .when() + .post(START_PROCESS_INSTANCE_URL); + + // start after: missing ancestor activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startAfter().getJson()); + json.put("startInstructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("'activityId' must be set")) + .when() + .post(START_PROCESS_INSTANCE_URL); + + // start transition: missing ancestor activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startTransition().getJson()); + json.put("startInstructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("'transitionId' must be set")) + .when() + .post(START_PROCESS_INSTANCE_URL); + } + + @SuppressWarnings("unchecked") + protected ProcessInstantiationBuilder setUpMockInstantiationBuilder() { + ProcessInstanceWithVariables resultInstanceWithVariables = MockProvider.createMockInstanceWithVariables(); + ProcessInstantiationBuilder mockInstantiationBuilder = mock(ProcessInstantiationBuilder.class); + + when(mockInstantiationBuilder.startAfterActivity(any())).thenReturn(mockInstantiationBuilder); + when(mockInstantiationBuilder.startBeforeActivity(any())).thenReturn(mockInstantiationBuilder); + when(mockInstantiationBuilder.startTransition(any())).thenReturn(mockInstantiationBuilder); + when(mockInstantiationBuilder.setVariables(any())).thenReturn(mockInstantiationBuilder); + when(mockInstantiationBuilder.setVariablesLocal(any())).thenReturn(mockInstantiationBuilder); + when(mockInstantiationBuilder.businessKey(any())).thenReturn(mockInstantiationBuilder); + when(mockInstantiationBuilder.caseInstanceId(any())).thenReturn(mockInstantiationBuilder); + when(mockInstantiationBuilder.execute(anyBoolean(), anyBoolean())).thenReturn(resultInstanceWithVariables); + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())).thenReturn(resultInstanceWithVariables); + + return mockInstantiationBuilder; + } + + /** + * {@link RuntimeService#startProcessInstanceById(String, Map)} throws an {@link ProcessEngineException}, if a definition with the given id does not exist. + */ + @Test + public void testUnsuccessfulInstantiation() { + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())) + .thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition")) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testStartProcessInstanceByIdThrowsAuthorizationException() { + String message = "expected exception"; + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())) + .thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testDefinitionRetrieval() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME)) + .body("description", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DESCRIPTION)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME)) + .body("diagram", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED)) + .body("tenantId", nullValue()) + .when().get(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).getProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testNonExistingProcessDefinitionRetrieval() { + String nonExistingId = "aNonExistingDefinitionId"; + when(repositoryServiceMock.getProcessDefinition(eq(nonExistingId))).thenThrow(new ProcessEngineException("no matching definition")); + + given().pathParam("id", "aNonExistingDefinitionId") + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No matching definition with id " + nonExistingId)) + .when().get(SINGLE_PROCESS_DEFINITION_URL); + } + + @Test + public void testNonExistingProcessDefinitionBpmn20XmlRetrieval() { + String nonExistingId = "aNonExistingDefinitionId"; + when(repositoryServiceMock.getProcessModel(eq(nonExistingId))).thenThrow(new NotFoundException("no matching process definition found.")); + + given().pathParam("id", nonExistingId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No matching definition with id " + nonExistingId)) + .when().get(XML_DEFINITION_URL); + } + + @Test + public void testGetProcessDefinitionBpmn20XmlThrowsProcessEngineException() { + String processDefinitionId = "someId"; + when(repositoryServiceMock.getProcessModel(eq(processDefinitionId))).thenThrow(new ProcessEngineException("generic message")); + + given().pathParam("id", processDefinitionId) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("generic message")) + .when().get(XML_DEFINITION_URL); + } + + @Test + public void testGetProcessDefinitionBpmn20XmlThrowsAuthorizationException() { + String message = "expected exception"; + when(repositoryServiceMock.getProcessModel(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(XML_DEFINITION_URL); + } + + @Test + public void testDeleteDeployment() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, false, false); + } + + + @Test + public void testDeleteDeploymentCascade() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("cascade", true) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, false, false); + } + + @Test + public void testDeleteDeploymentCascadeNonsense() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("cascade", "bla") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentCascadeFalse() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("cascade", false) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListeners() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("skipCustomListeners", true) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, true, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListenersNonsense() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("skipCustomListeners", "bla") + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListenersFalse() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("skipCustomListeners", false) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, false, false); + } + + @Test + public void testDeleteDeploymentSkipCustomListenersAndCascade() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("cascade", true) + .queryParam("skipCustomListeners", true) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, true, false); + } + + @Test + public void testDeleteNonExistingDeployment() { + + doThrow(new NotFoundException("No process definition found with id 'NON_EXISTING_ID'")) + .when(repositoryServiceMock) + .deleteProcessDefinition("NON_EXISTING_ID", false, false, false); + + given() + .pathParam("id", "NON_EXISTING_ID") + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No process definition found with id 'NON_EXISTING_ID'")) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + } + + @Test + public void testDeleteDeploymentThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, false, false); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + } + + @Test + public void testDeleteDefinitionSkipIoMappings() { + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("skipIoMappings", true) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_URL); + + verify(repositoryServiceMock).deleteProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, false, true); + } + + @Test + public void testDeleteDefinitionsByKey() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeyCascade() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("cascade", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .cascade(); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeySkipCustomListeners() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("skipCustomListeners", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .skipCustomListeners(); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeySkipIoMappings() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("skipIoMappings", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .skipIoMappings(); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeySkipCustomListenersAndCascade() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("cascade", true) + .queryParam("skipCustomListeners", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .skipCustomListeners() + .cascade(); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeyNotExistingKey() { + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey("NOT_EXISTING_KEY"); + + doThrow(new NotFoundException("No process definition found with key 'NOT_EXISTING_KEY'")).when(builder).delete(); + + given() + .pathParam("key", "NOT_EXISTING_KEY") + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No process definition found with key 'NOT_EXISTING_KEY'")) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_DELETE_URL); + } + + @Test + public void testDeleteDefinitionsByKeyWithTenantId() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .withTenantId(MockProvider.EXAMPLE_TENANT_ID); + + verify(builder).delete(); + } + + + @Test + public void testDeleteDefinitionsByKeyCascadeWithTenantId() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("cascade", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .withTenantId(MockProvider.EXAMPLE_TENANT_ID) + .cascade(); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeySkipCustomListenersWithTenantId() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("skipCustomListeners", true) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .withTenantId(MockProvider.EXAMPLE_TENANT_ID) + .skipCustomListeners(); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeySkipCustomListenersAndCascadeWithTenantId() { + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("skipCustomListeners", true) + .queryParam("cascade", true) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_DELETE_URL); + + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .withTenantId(MockProvider.EXAMPLE_TENANT_ID) + .skipCustomListeners() + .cascade(); + + verify(builder).delete(); + } + + @Test + public void testDeleteDefinitionsByKeyNoPermissions() { + DeleteProcessDefinitionsBuilder builder = repositoryServiceMock.deleteProcessDefinitions() + .byKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .withTenantId(MockProvider.EXAMPLE_TENANT_ID); + + doThrow(new AuthorizationException("No permission to delete process definitions")).when(builder).delete(); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("No permission to delete process definitions")) + .when() + .delete(SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_DELETE_URL); + } + + @Test + public void testGetStartFormDataForNonExistingProcessDefinition() { + when(formServiceMock.getStartFormData(anyString())).thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", "aNonExistingProcessDefinitionId") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot get start form data for process definition")) + .when().get(START_FORM_URL); + } + + @Test + public void testUnparseableIntegerVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testUnparseableShortVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testUnparseableLongVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testUnparseableDoubleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testUnparseableDateVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testNotSupportedTypeVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: Unsupported value type 'X'")) + .when().post(START_PROCESS_INSTANCE_URL); + } + + @Test + public void testActivateProcessDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + } + + @Test + public void testDelayedActivateProcessDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, executionDate); + } + + @Test + public void testActivateProcessDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, null); + } + + @Test + public void testDelayedActivateProcessDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", true); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, executionDate); + } + + @Test + public void testActivateThrowsProcessEngineException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(repositoryServiceMock) + .activateProcessDefinitionById(eq(MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID), eq(false), isNull()); + + given() + .pathParam("id", MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateNonParseableDateFormat() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + params.put("executionDate", "a"); + + String expectedMessage = "Invalid format: \"a\""; + String exceptionMessage = "The suspension state of Process Definition with id " + MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID + " could not be updated due to: " + expectedMessage; + + given() + .pathParam("id", MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(exceptionMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateProcessDefinitionThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + } + + @Test + public void testDelayedSuspendProcessDefinitionExcludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, executionDate); + } + + @Test + public void testSuspendProcessDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, null); + } + + @Test + public void testDelayedSuspendProcessDefinitionIncludingInstances() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", true); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, executionDate); + } + + @Test + public void testSuspendThrowsProcessEngineException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(repositoryServiceMock) + .suspendProcessDefinitionById(eq(MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID), eq(false), isNull()); + + given() + .pathParam("id", MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendNonParseableDateFormat() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + params.put("executionDate", "a"); + + String expectedMessage = "Invalid format: \"a\""; + String exceptionMessage = "The suspension state of Process Definition with id " + MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID + " could not be updated due to: " + expectedMessage; + + given() + .pathParam("id", MockProvider.NON_EXISTING_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(exceptionMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendWithMultipleByParameters() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "Only one of processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(SINGLE_PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateProcessDefinitionByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, null); + } + + @Test + public void testActivateProcessDefinitionByKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, true, null); + } + + @Test + public void testDelayedActivateProcessDefinitionByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, executionDate); + } + + @Test + public void testDelayedActivateProcessDefinitionByKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, true, executionDate); + } + + @Test + public void testActivateProcessDefinitionByKeyWithUnparseableDate() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", "a"); + + String message = "Could not update the suspension state of Process Definitions due to: Invalid format: \"a\""; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateProcessDefinitionByKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(repositoryServiceMock) + .activateProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, null); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateProcessDefinitionByKeyThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(repositoryServiceMock).activateProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, null); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, null); + } + + @Test + public void testSuspendProcessDefinitionByKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, true, null); + } + + @Test + public void testDelayedSuspendProcessDefinitionByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, executionDate); + } + + @Test + public void testDelayedSuspendProcessDefinitionByKeyIncludingInstaces() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, true, executionDate); + } + + @Test + public void testSuspendProcessDefinitionByKeyWithUnparseableDate() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("executionDate", "a"); + + String message = "Could not update the suspension state of Process Definitions due to: Invalid format: \"a\""; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionByKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(repositoryServiceMock) + .suspendProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, null); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", is(expectedException)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionByKeyThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(repositoryServiceMock).suspendProcessDefinitionByKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, false, null); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateProcessDefinitionByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String message = "Only processDefinitionKey can be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testActivateProcessDefinitionByNothing() { + Map params = new HashMap<>(); + params.put("suspended", false); + + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String message = "Only processDefinitionKey can be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionByNothing() { + Map params = new HashMap<>(); + params.put("suspended", true); + + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionThrowsAuthorizationExcpetion() { + Map params = new HashMap<>(); + params.put("suspended", true); + + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(PROCESS_DEFINITION_SUSPENDED_URL); + } + + /** + * + ********************************* test cases for operations of the latest process definition ******************************** + * get the latest process definition by key + * + */ + + @Test + public void testInstanceResourceLinkResult_ByKey() { + String fullInstanceUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/process-instance/" + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("links[0].href", equalTo(fullInstanceUrl)) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testInstanceResourceLinkWithEnginePrefix_ByKey() { + String startInstanceOnExplicitEngineUrl = TEST_RESOURCE_ROOT_PATH + "/engine/default/process-definition/key/{key}/start"; + + String fullInstanceUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/engine/default/process-instance/" + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("links[0].href", equalTo(fullInstanceUrl)) + .when().post(startInstanceOnExplicitEngineUrl); + } + + @Test + public void testProcessDefinitionBpmn20XmlRetrieval_ByKey() { + // Rest-assured has problems with extracting json with escaped quotation marks, i.e. the xml content in our case + Response response = given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) +// .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) +// .body("bpmn20Xml", startsWith("anyContent"; + + when(formServiceMock.getRenderedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(expectedResult); + + Response response = given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(XHTML_XML_CONTENT_TYPE) + .when() + .get(RENDERED_FORM_BY_KEY_URL); + + String responseContent = response.asString(); + Assertions.assertThat(responseContent).isEqualTo(expectedResult); + } + + @Test + public void testGetRenderedStartFormReturnsNotFound_ByKey() { + when(formServiceMock.getRenderedStartForm(anyString(), anyString())).thenReturn(null); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No matching rendered start form for process definition with the id " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + " found.")) + .when() + .get(RENDERED_FORM_BY_KEY_URL); + } + + @Test + public void testGetRenderedStartFormThrowsAuthorizationException_ByKey() { + String message = "expected exception"; + when(formServiceMock.getRenderedStartForm(anyString())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(RENDERED_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitStartForm_ByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_BY_KEY_URL); + + verify(formServiceMock).submitStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, null); + } + + @Test + public void testSubmitStartFormWithParameters_ByKey() { + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("anotherVariable", 42) + .variable("aThirdValue", Boolean.TRUE).getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_BY_KEY_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aVariable", "aStringValue"); + expectedVariables.put("anotherVariable", 42); + expectedVariables.put("aThirdValue", Boolean.TRUE); + + verify(formServiceMock).submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testSubmitStartFormWithBusinessKey_ByKey() { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_BY_KEY_URL); + + verify(formServiceMock).submitStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, "myBusinessKey", null); + } + + @Test + public void testSubmitStartFormWithBusinessKeyAndParameters_ByKey() { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("anotherVariable", 42) + .variable("aThirdValue", Boolean.TRUE).getVariables(); + + json.put("variables", variables); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("definitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("businessKey", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("ended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .when().post(SUBMIT_FORM_BY_KEY_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aVariable", "aStringValue"); + expectedVariables.put("anotherVariable", 42); + expectedVariables.put("aThirdValue", Boolean.TRUE); + + verify(formServiceMock).submitStartForm(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), eq("myBusinessKey"), argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testSubmitStartFormWithUnparseableIntegerVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableShortVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableLongVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableDoubleVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitStartFormWithUnparseableDateVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitStartFormWithNotSupportedVariableType_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: Unsupported value type 'X'")) + .when().post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testUnsuccessfulSubmitStartForm_ByKey() { + doThrow(new ProcessEngineException("expected exception")).when(formServiceMock).submitStartForm(any(String.class), Mockito.any()); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot instantiate process definition " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + ": expected exception")) + .when().post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitFormByKeyThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(formServiceMock).submitStartForm(any(String.class), Mockito.any()); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSubmitFormByKeyThrowsFormFieldValidationException() { + String message = "expected exception"; + doThrow(new FormFieldValidationException("form-exception", message)).when(formServiceMock).submitStartForm(any(String.class), Mockito.any()); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot instantiate process definition " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + ": " + message)) + .when() + .post(SUBMIT_FORM_BY_KEY_URL); + } + + @Test + public void testSimpleProcessInstantiation_ByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testProcessInstantiationWithParameters_ByKey() throws IOException { + Map parameters = VariablesBuilder.create() + .variable("aBoolean", Boolean.TRUE) + .variable("aString", "aStringVariableValue") + .variable("anInteger", 42).getVariables(); + + Map json = new HashMap<>(); + json.put("variables", parameters); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + + Map expectedParameters = new HashMap<>(); + expectedParameters.put("aBoolean", Boolean.TRUE); + expectedParameters.put("aString", "aStringVariableValue"); + expectedParameters.put("anInteger", 42); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).setVariables(argThat(new EqualsMap(expectedParameters))); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationWithBusinessKey_ByKey() throws IOException { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).businessKey("myBusinessKey"); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationWithBusinessKeyAndParameters_ByKey() throws IOException { + Map json = new HashMap<>(); + json.put("businessKey", "myBusinessKey"); + + Map parameters = VariablesBuilder.create() + .variable("aBoolean", Boolean.TRUE) + .variable("aString", "aStringVariableValue") + .variable("anInteger", 42).getVariables(); + + json.put("variables", parameters); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + + Map expectedParameters = new HashMap<>(); + expectedParameters.put("aBoolean", Boolean.TRUE); + expectedParameters.put("aString", "aStringVariableValue"); + expectedParameters.put("anInteger", 42); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).businessKey("myBusinessKey"); + verify(mockInstantiationBuilder).setVariables(argThat(new EqualsMap(expectedParameters))); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + /** + * {@link RuntimeService#startProcessInstanceById(String, Map)} throws an {@link ProcessEngineException}, if a definition with the given id does not exist. + */ + @Test + public void testUnsuccessfulInstantiation_ByKey() { + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())) + .thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition")) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testStartProcessInstanceByKeyThrowsAuthorizationException() { + String message = "expected exception"; + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())) + .thenThrow(new AuthorizationException(message)); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testDefinitionRetrieval_ByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME)) + .body("description", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DESCRIPTION)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME)) + .body("diagram", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED)) + .body("tenantId", nullValue()) + .when().get(SINGLE_PROCESS_DEFINITION_BY_KEY_URL); + + verify(processDefinitionQueryMock).withoutTenantId(); + verify(repositoryServiceMock).getProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testNonExistingProcessDefinitionRetrieval_ByKey() { + String nonExistingKey = "aNonExistingDefinitionKey"; + + when(repositoryServiceMock.createProcessDefinitionQuery().processDefinitionKey(nonExistingKey)).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.latestVersion()).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.singleResult()).thenReturn(null); + when(processDefinitionQueryMock.list()).thenReturn(Collections.emptyList()); + when(processDefinitionQueryMock.count()).thenReturn(0L); + + given().pathParam("key", nonExistingKey) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching process definition with key: " + nonExistingKey + " and no tenant-id")) + .when().get(SINGLE_PROCESS_DEFINITION_BY_KEY_URL); + } + + @Test + public void testDefinitionRetrieval_ByKeyAndTenantId() { + ProcessDefinition mockDefinition = MockProvider.mockDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(); + setUpRuntimeDataForDefinition(mockDefinition); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("key", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("category", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY)) + .body("name", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME)) + .body("description", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DESCRIPTION)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("version", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION)) + .body("resource", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME)) + .body("diagram", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME)) + .body("suspended", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .when().get(SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_URL); + + verify(processDefinitionQueryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(repositoryServiceMock).getProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testNonExistingProcessDefinitionRetrieval_ByKeyAndTenantId() { + String nonExistingKey = "aNonExistingDefinitionKey"; + String nonExistingTenantId = "aNonExistingTenantId"; + + when(repositoryServiceMock.createProcessDefinitionQuery().processDefinitionKey(nonExistingKey)).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("key", nonExistingKey) + .pathParam("tenant-id", nonExistingTenantId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", containsString("No matching process definition with key: " + nonExistingKey + " and tenant-id: " + nonExistingTenantId)) + .when().get(SINGLE_PROCESS_DEFINITION_BY_KEY_AND_TENANT_ID_URL); + } + + @Test + public void testSimpleProcessInstantiation_ByKeyAndTenantId() { + ProcessDefinition mockDefinition = MockProvider.mockDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(); + setUpRuntimeDataForDefinition(mockDefinition); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .pathParam("tenant-id", MockProvider.EXAMPLE_TENANT_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_BY_KEY_AND_TENANT_ID_URL); + + verify(processDefinitionQueryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void testUnparseableIntegerVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testUnparseableShortVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testUnparseableLongVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testUnparseableDoubleVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testUnparseableDateVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void testNotSupportedTypeVariable_ByKey() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot instantiate process definition aProcDefId: Unsupported value type 'X'")) + .when().post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + + @Test + public void testUpdateHistoryTimeToLive() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(5)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_HISTORY_TIMETOLIVE_URL); + + verify(repositoryServiceMock).updateProcessDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, 5); + } + + @Test + public void testUpdateHistoryTimeToLiveNullValue() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .body(new HistoryTimeToLiveDto()) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_HISTORY_TIMETOLIVE_URL); + + verify(repositoryServiceMock).updateProcessDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, null); + } + + @Test + public void testUpdateHistoryTimeToLiveNegativeValue() { + String expectedMessage = "expectedMessage"; + + doThrow(new BadUserRequestException(expectedMessage)) + .when(repositoryServiceMock) + .updateProcessDefinitionHistoryTimeToLive(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), eq(-1)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(-1)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(BadUserRequestException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_HISTORY_TIMETOLIVE_URL); + + verify(repositoryServiceMock).updateProcessDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, -1); + } + + @Test + public void testUpdateHistoryTimeToLiveAuthorizationException() { + String expectedMessage = "expectedMessage"; + + doThrow(new AuthorizationException(expectedMessage)) + .when(repositoryServiceMock) + .updateProcessDefinitionHistoryTimeToLive(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), eq(5)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .body(new HistoryTimeToLiveDto(5)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_HISTORY_TIMETOLIVE_URL); + + verify(repositoryServiceMock).updateProcessDefinitionHistoryTimeToLive(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, 5); + } + + @Test + public void testActivateProcessDefinitionExcludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + } + + @Test + public void testDelayedActivateProcessDefinitionExcludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, executionDate); + } + + @Test + public void testActivateProcessDefinitionIncludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", true); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, null); + } + + @Test + public void testDelayedActivateProcessDefinitionIncludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", true); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, executionDate); + } + + @Test + public void testActivateThrowsProcessEngineException_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(repositoryServiceMock) + .activateProcessDefinitionById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), eq(false), isNull()); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + } + + @Test + public void testActivateNonParseableDateFormat_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("includeProcessInstances", false); + params.put("executionDate", "a"); + + String expectedMessage = "Invalid format: \"a\""; + String exceptionMessage = "The suspension state of Process Definition with id " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + " could not be updated due to: " + expectedMessage; + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(exceptionMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + } + + @Test + public void testActivateProcessDefinitionThrowsAuthorizationException_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(repositoryServiceMock).activateProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionExcludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + } + + @Test + public void testDelayedSuspendProcessDefinitionExcludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, executionDate); + } + + @Test + public void testSuspendProcessDefinitionIncludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", true); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, null); + } + + + + @Test + public void testDelayedSuspendProcessDefinitionIncludingInstances_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", true); + params.put("executionDate", MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + Date executionDate = DateTimeUtil.parseDate(MockProvider.EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + + verify(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, true, executionDate); + } + + @Test + public void testSuspendThrowsProcessEngineException_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(repositoryServiceMock) + .suspendProcessDefinitionById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID), eq(false), isNull()); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(ProcessEngineException.class.getSimpleName())) + .body("message", containsString(expectedMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + } + + @Test + public void testSuspendNonParseableDateFormat_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("includeProcessInstances", false); + params.put("executionDate", "a"); + + String expectedMessage = "Invalid format: \"a\""; + String exceptionMessage = "The suspension state of Process Definition with id " + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID + " could not be updated due to: " + expectedMessage; + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is(exceptionMessage)) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessDefinitionThrowsAuthorizationException_ByKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(repositoryServiceMock).suspendProcessDefinitionById(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, false, null); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .put(SINGLE_PROCESS_DEFINITION_BY_KEY_SUSPENDED_URL); + } + + @Test + public void testProcessInstantiationWithCaseInstanceId() throws IOException { + Map json = new HashMap<>(); + json.put("caseInstanceId", "myCaseInstanceId"); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).caseInstanceId("myCaseInstanceId"); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationWithCaseInstanceIdAndBusinessKey() throws IOException { + Map json = new HashMap<>(); + json.put("caseInstanceId", "myCaseInstanceId"); + json.put("businessKey", "myBusinessKey"); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).businessKey("myBusinessKey"); + verify(mockInstantiationBuilder).caseInstanceId("myCaseInstanceId"); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testProcessInstantiationWithCaseInstanceIdAndBusinessKeyAndParameters() throws IOException { + Map json = new HashMap<>(); + json.put("caseInstanceId", "myCaseInstanceId"); + json.put("businessKey", "myBusinessKey"); + + Map parameters = VariablesBuilder.create() + .variable("aBoolean", Boolean.TRUE) + .variable("aString", "aStringVariableValue") + .variable("anInteger", 42).getVariables(); + + json.put("variables", parameters); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .when().post(START_PROCESS_INSTANCE_URL); + + Map expectedParameters = new HashMap<>(); + expectedParameters.put("aBoolean", Boolean.TRUE); + expectedParameters.put("aString", "aStringVariableValue"); + expectedParameters.put("anInteger", 42); + + verify(runtimeServiceMock).createProcessInstanceById(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verify(mockInstantiationBuilder).businessKey("myBusinessKey"); + verify(mockInstantiationBuilder).caseInstanceId("myCaseInstanceId"); + verify(mockInstantiationBuilder).setVariables(argThat(new EqualsMap(expectedParameters))); + verify(mockInstantiationBuilder).executeWithVariablesInReturn(anyBoolean(), anyBoolean()); + } + + @Test + public void testGetStartFormVariablesThrowsAuthorizationException_ByKey() { + String message = "expected exception"; + when(formServiceMock.getStartFormVariables(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, null, true)).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(START_FORM_VARIABLES_BY_KEY_URL); + } + + @Test + public void testGetDeployedStartForm_ByKey() { + InputStream deployedStartFormMock = new ByteArrayInputStream("Test".getBytes()); + when(formServiceMock.getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenReturn(deployedStartFormMock); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(equalTo("Test")) + .when() + .get(DEPLOYED_START_FORM_BY_KEY_URL); + + verify(formServiceMock).getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testGetDeployedStartForm() { + InputStream deployedStartFormMock = new ByteArrayInputStream("Test".getBytes()); + when(formServiceMock.getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenReturn(deployedStartFormMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(equalTo("Test")) + .contentType(MediaType.APPLICATION_XHTML_XML) + .when() + .get(DEPLOYED_START_FORM_URL); + + verify(formServiceMock).getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testGetDeployedStartFormJson() { + InputStream deployedStartFormMock = new ByteArrayInputStream("Test".getBytes()); + when(formServiceMock.getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenReturn(deployedStartFormMock); + when(formServiceMock.getStartFormKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenReturn("test.form"); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(equalTo("Test")) + .contentType(MediaType.APPLICATION_JSON) + .when() + .get(DEPLOYED_START_FORM_URL); + + verify(formServiceMock).getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testGetDeployedStartFormWithoutAuthorization() { + String message = "unauthorized"; + when(formServiceMock.getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("message", equalTo(message)) + .when() + .get(DEPLOYED_START_FORM_URL); + } + + @Test + public void testGetDeployedStartFormWithWrongFormKeyFormat() { + String message = "wrong key format"; + when(formServiceMock.getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenThrow(new BadUserRequestException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", equalTo(message)) + .when() + .get(DEPLOYED_START_FORM_URL); + } + + @Test + public void testGetDeployedStartFormWithUnexistingForm() { + String message = "not found"; + when(formServiceMock.getDeployedStartForm(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenThrow(new NotFoundException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("message", equalTo(message)) + .when() + .get(DEPLOYED_START_FORM_URL); + } + + @Test + public void testGetStaticCalledProcessDefinitions() { + CalledProcessDefinition mock = mock(CalledProcessDefinitionImpl.class); + when(mock.getCalledFromActivityIds()).thenReturn(Arrays.asList("anActivity", "anotherActivity")); + when(mock.getId()).thenReturn("aKey:1:123"); + when(mock.getCallingProcessDefinitionId()).thenReturn("aCallingId"); + when(mock.getName()).thenReturn("a Name"); + when(mock.getKey()).thenReturn("aKey"); + when(mock.getVersion()).thenReturn(1); + List result = Collections.singletonList(mock); + when(repositoryServiceMock.getStaticCalledProcessDefinitions(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .thenReturn(result); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body("[0].callingProcessDefinitionId", equalTo(mock.getCallingProcessDefinitionId())) + .body("[0].id", equalTo(mock.getId())) + .body("[0].key", equalTo(mock.getKey())) + .body("[0].name", equalTo(mock.getName())) + .body("[0].version", equalTo(mock.getVersion())) + .body("[0].calledFromActivityIds[0]", equalTo("anActivity")) + .body("[0].calledFromActivityIds[1]", equalTo("anotherActivity")) + .when() + .get(PROCESS_DEFINITION_CALL_ACTIVITY_MAPPINGS); + } + + @Test + public void testGetStaticCalledProcessDefinitionNonExistingProcess() { + + when(repositoryServiceMock.getStaticCalledProcessDefinitions("NonExistingId")).thenThrow( + new NotFoundException()); + + given() + .pathParam("id", "NonExistingId") + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .when() + .get(PROCESS_DEFINITION_CALL_ACTIVITY_MAPPINGS); + } + + @Test + public void shouldReturnErrorCodeWhenStartingProcessInstance() { + when(mockInstantiationBuilder.executeWithVariablesInReturn(anyBoolean(), anyBoolean())) + .thenThrow(new ProcessEngineException("foo", 123)); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot instantiate process definition aProcDefId: foo")) + .body("code", equalTo(123)) + .when() + .post(START_PROCESS_INSTANCE_BY_KEY_URL); + } + + @Test + public void shouldReturnErrorCodeWhenSubmittingForm() { + doThrow(new ProcessEngineException("foo", 123)) + .when(formServiceMock).submitStartForm(any(String.class), Mockito.any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot instantiate process definition aProcDefId: foo")) + .body("code", equalTo(123)) + .when() + .post(SUBMIT_FORM_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..9bd98581ba4d073ceee50db377bd613832dd05e7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessDefinitionRestServiceQueryTest.java @@ -0,0 +1,647 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockDefinitionBuilder; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class ProcessDefinitionRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_DEFINITION_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/process-definition"; + protected static final String PROCESS_DEFINITION_COUNT_QUERY_URL = PROCESS_DEFINITION_QUERY_URL + "/count"; + private ProcessDefinitionQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockDefinitionQuery(MockProvider.createMockDefinitions()); + } + + private ProcessDefinitionQuery setUpMockDefinitionQuery(List mockedDefinitions) { + ProcessDefinitionQuery sampleDefinitionsQuery = mock(ProcessDefinitionQuery.class); + when(sampleDefinitionsQuery.list()).thenReturn(mockedDefinitions); + when(sampleDefinitionsQuery.count()).thenReturn((long) mockedDefinitions.size()); + when(processEngine.getRepositoryService().createProcessDefinitionQuery()).thenReturn(sampleDefinitionsQuery); + return sampleDefinitionsQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given().queryParam("keyLike", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + } + + @Test + public void testInvalidNumericParameter() { + String anInvalidIntegerQueryParam = "aString"; + given().queryParam("version", anInvalidIntegerQueryParam) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'version' to value 'aString': " + + "Cannot convert value aString to java type java.lang.Integer")) + .when().get(PROCESS_DEFINITION_QUERY_URL); + } + + @Test + public void testInvalidBooleanParameter() { + String anInvalidBooleanQueryParam = "neitherTrueNorFalse"; + given().queryParam("active", anInvalidBooleanQueryParam) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'active' to value 'neitherTrueNorFalse': " + + "Cannot convert value neitherTrueNorFalse to java type java.lang.Boolean")) + .when().get(PROCESS_DEFINITION_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifyFailingSorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST, + InvalidRequestException.class.getSimpleName(), "Cannot set query parameter 'sortBy' to value 'anInvalidSortByOption'"); + executeAndVerifyFailingSorting("category", "anInvalidSortOrderOption", Status.BAD_REQUEST, + InvalidRequestException.class.getSimpleName(), "Cannot set query parameter 'sortOrder' to value 'anInvalidSortOrderOption'"); + } + + protected void executeAndVerifySuccessfulSorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + } + + protected void executeAndVerifyFailingSorting(String sortBy, String sortOrder, Status expectedStatus, String expectedErrorType, String expectedErrorMessage) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(expectedErrorType)) + .body("message", equalTo(expectedErrorMessage)) + .when().get(PROCESS_DEFINITION_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "category") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(PROCESS_DEFINITION_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(PROCESS_DEFINITION_QUERY_URL); + } + + @Test + public void testProcessDefinitionRetrieval() { + InOrder inOrder = inOrder(mockedQuery); + + String queryKey = "Key"; + Response response = given().queryParam("keyLike", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + // assert query invocation + inOrder.verify(mockedQuery).processDefinitionKeyLike(queryKey); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + Assert.assertEquals("There should be one process definition returned.", 1, definitions.size()); + Assert.assertNotNull("There should be one process definition returned", definitions.get(0)); + + String returnedDefinitionKey = from(content).getString("[0].key"); + String returnedDefinitionId = from(content).getString("[0].id"); + String returnedCategory = from(content).getString("[0].category"); + String returnedDefinitionName = from(content).getString("[0].name"); + String returnedDescription = from(content).getString("[0].description"); + int returnedVersion = from(content).getInt("[0].version"); + String returnedResourceName = from(content).getString("[0].resource"); + String returnedDeploymentId = from(content).getString("[0].deploymentId"); + String returnedDiagramResourceName = from(content).getString("[0].diagram"); + Boolean returnedIsSuspended = from(content).getBoolean("[0].suspended"); + Boolean returnedIsStartedInTasklist = from(content).getBoolean("[0].startableInTasklist"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY, returnedCategory); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME, returnedDefinitionName); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_DESCRIPTION, returnedDescription); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION, returnedVersion); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME, returnedResourceName); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, returnedDeploymentId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME, returnedDiagramResourceName); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED, returnedIsSuspended); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_STARTABLE, returnedIsStartedInTasklist); + } + + @Test + public void testProcessDefinitionRetrievalByList() { + mockedQuery = setUpMockDefinitionQuery(MockProvider.createMockTwoDefinitions()); + + Response response = given() + .queryParam("processDefinitionIdIn", MockProvider.EXAMPLE_PROCESS_DEFINTION_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processDefinitionIdIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedDefinitionId1 = from(content).getString("[0].id"); + String returnedDefinitionId2 = from(content).getString("[1].id"); + + assertThat(returnedDefinitionId1).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertThat(returnedDefinitionId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testProcessDefinitionRetrievalByEmptyList() { + mockedQuery = setUpMockDefinitionQuery(MockProvider.createMockTwoDefinitions()); + + Response response = given() + .queryParam("processDefinitionIdIn", "") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + // assert query invocation + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery, never()).processDefinitionIdIn(Mockito.any()); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedDefinitionId1 = from(content).getString("[0].id"); + String returnedDefinitionId2 = from(content).getString("[1].id"); + + assertThat(returnedDefinitionId1).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertThat(returnedDefinitionId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testIncompleteProcessDefinition() { + setUpMockDefinitionQuery(createIncompleteMockDefinitions()); + Response response = expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + String content = response.asString(); + String returnedResourceName = from(content).getString("[0].resource"); + Assert.assertNull("Should be null, as it is also null in the original process definition on the server.", + returnedResourceName); + } + + private List createIncompleteMockDefinitions() { + List mocks = new ArrayList(); + + MockDefinitionBuilder builder = new MockDefinitionBuilder(); + ProcessDefinition mockDefinition = + builder.id(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .category(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY) + .name(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME) + .key(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .suspended(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED) + .version(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION).build(); + + mocks.add(mockDefinition); + return mocks; + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testAdditionalParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given().queryParams(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + // assert query invocation + verify(mockedQuery).processDefinitionId(queryParameters.get("processDefinitionId")); + verify(mockedQuery).processDefinitionCategory(queryParameters.get("category")); + verify(mockedQuery).processDefinitionCategoryLike(queryParameters.get("categoryLike")); + verify(mockedQuery).processDefinitionName(queryParameters.get("name")); + verify(mockedQuery).processDefinitionNameLike(queryParameters.get("nameLike")); + verify(mockedQuery).deploymentId(queryParameters.get("deploymentId")); + verify(mockedQuery).processDefinitionKey(queryParameters.get("key")); + verify(mockedQuery).processDefinitionKeyLike(queryParameters.get("keyLike")); + verify(mockedQuery).processDefinitionVersion(Integer.parseInt(queryParameters.get("version"))); + verify(mockedQuery).latestVersion(); + verify(mockedQuery).processDefinitionResourceName(queryParameters.get("resourceName")); + verify(mockedQuery).processDefinitionResourceNameLike(queryParameters.get("resourceNameLike")); + verify(mockedQuery).startableByUser(queryParameters.get("startableBy")); + verify(mockedQuery).active(); + verify(mockedQuery).suspended(); + verify(mockedQuery).incidentId(queryParameters.get("incidentId")); + verify(mockedQuery).incidentType(queryParameters.get("incidentType")); + verify(mockedQuery).incidentMessage(queryParameters.get("incidentMessage")); + verify(mockedQuery).incidentMessageLike(queryParameters.get("incidentMessageLike")); + verify(mockedQuery).versionTag(queryParameters.get("versionTag")); + verify(mockedQuery).versionTagLike(queryParameters.get("versionTagLike")); + verify(mockedQuery).startableInTasklist(); + verify(mockedQuery).list(); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("processDefinitionId", "anId"); + parameters.put("category", "cat"); + parameters.put("categoryLike", "catlike"); + parameters.put("name", "name"); + parameters.put("nameLike", "namelike"); + parameters.put("deploymentId", "depId"); + parameters.put("key", "key"); + parameters.put("keyLike", "keylike"); + parameters.put("version", "0"); + parameters.put("latestVersion", "true"); + parameters.put("resourceName", "res"); + parameters.put("resourceNameLike", "resLike"); + parameters.put("startableBy", "kermit"); + parameters.put("suspended", "true"); + parameters.put("active", "true"); + parameters.put("incidentId", "incId"); + parameters.put("incidentType", "incType"); + parameters.put("incidentMessage", "incMessage"); + parameters.put("incidentMessageLike", "incMessageLike"); + parameters.put("versionTag", "semVer"); + parameters.put("versionTagLike", "semVerLike"); + parameters.put("startableInTasklist", "true"); + + return parameters; + } + + @Test + public void testProcessDefinitionTenantIdList() { + List processDefinitions = Arrays.asList( + MockProvider.mockDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.mockDefinition().id(MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID).tenantId(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build()); + mockedQuery = setUpMockDefinitionQuery(processDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testProcessDefinitionKeysList() { + List processDefinitions = Arrays.asList( + MockProvider.mockDefinition().key(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY).build(), + MockProvider.mockDefinition().key(MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY).build()); + mockedQuery = setUpMockDefinitionQuery(processDefinitions); + + Response response = given() + .queryParam("keysIn", MockProvider.EXAMPLE_KEY_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).processDefinitionKeysIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, + MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedKey1 = from(content).getString("[0].key"); + String returnedKey2 = from(content).getString("[1].key"); + + assertThat(returnedKey1).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + assertThat(returnedKey2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY); + } + + @Test + public void testProcessDefinitionWithoutTenantId() { + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testProcessDefinitionTenantIdIncludeDefinitionsWithoutTenantid() { + List processDefinitions = Arrays.asList( + MockProvider.mockDefinition().tenantId(null).build(), + MockProvider.mockDefinition().tenantId(MockProvider.EXAMPLE_TENANT_ID).build()); + mockedQuery = setUpMockDefinitionQuery(processDefinitions); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID) + .queryParam("includeProcessDefinitionsWithoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID); + verify(mockedQuery).includeProcessDefinitionsWithoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(null); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void testProcessDefinitionVersionTag() { + List processDefinitions = Arrays.asList( + MockProvider.mockDefinition().versionTag(MockProvider.EXAMPLE_VERSION_TAG).build(), + MockProvider.mockDefinition().id(MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID).versionTag(MockProvider.ANOTHER_EXAMPLE_VERSION_TAG).build()); + mockedQuery = setUpMockDefinitionQuery(processDefinitions); + + given() + .queryParam("versionTag", MockProvider.EXAMPLE_VERSION_TAG) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).versionTag(MockProvider.EXAMPLE_VERSION_TAG); + verify(mockedQuery).list(); + } + + @Test + public void testProcessDefinitionWithoutVersionTag() { + given() + .queryParam("withoutVersionTag", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).withoutVersionTag(); + verify(mockedQuery).list(); + } + + @Test + public void testNotStartableInTasklist() { + List processDefinitions = Arrays.asList( + MockProvider.mockDefinition().isStartableInTasklist(false).build()); + mockedQuery = setUpMockDefinitionQuery(processDefinitions); + + given() + .queryParam("notStartableInTasklist", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).notStartableInTasklist(); + verify(mockedQuery).list(); + } + + @Test + public void testStartableInTasklistPermissionCheck() { + List processDefinitions = Arrays.asList( + MockProvider.mockDefinition().isStartableInTasklist(false).build()); + mockedQuery = setUpMockDefinitionQuery(processDefinitions); + + given() + .queryParam("startablePermissionCheck", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).startablePermissionCheck(); + verify(mockedQuery).list(); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("category", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionCategory(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("key", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("id", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("version", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionVersion(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("name", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("deploymentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("deployTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("versionTag", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByVersionTag(); + inOrder.verify(mockedQuery).asc(); + + inOrder = inOrder(mockedQuery); + executeAndVerifySuccessfulSorting("versionTag", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByVersionTag(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given().queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given().queryParam("firstResult", firstResult) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(PROCESS_DEFINITION_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryByDeployTimeAfter() { + String deployTime = withTimezone("2020-03-27T01:23:45"); + Date date = DateTimeUtil.parseDate(deployTime); + + given().queryParam("deployedAfter", deployTime) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).deployedAfter(date); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByDeployTimeAt() { + String deployTime = withTimezone("2020-03-27T05:43:21"); + Date date = DateTimeUtil.parseDate(deployTime); + + given().queryParam("deployedAt", deployTime) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_QUERY_URL); + + verify(mockedQuery).deployedAt(date); + verify(mockedQuery).list(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessEngineRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessEngineRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..7b5dfc346d5302ba35eacd3f2f2b44f4315973f4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessEngineRestServiceTest.java @@ -0,0 +1,933 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.hasItems; +import static org.hamcrest.CoreMatchers.is; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import io.restassured.response.Response; +import org.camunda.bpm.engine.CaseService; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.FilterService; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.externaltask.ExternalTaskQuery; +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.filter.FilterQuery; +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; +import org.camunda.bpm.engine.history.HistoricActivityStatistics; +import org.camunda.bpm.engine.history.HistoricActivityStatisticsQuery; +import org.camunda.bpm.engine.history.HistoricDetail; +import org.camunda.bpm.engine.history.HistoricDetailQuery; +import org.camunda.bpm.engine.history.HistoricExternalTaskLog; +import org.camunda.bpm.engine.history.HistoricExternalTaskLogQuery; +import org.camunda.bpm.engine.history.HistoricIncident; +import org.camunda.bpm.engine.history.HistoricIncidentQuery; +import org.camunda.bpm.engine.history.HistoricJobLog; +import org.camunda.bpm.engine.history.HistoricJobLogQuery; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.impl.HistoricActivityStatisticsQueryImpl; +import org.camunda.bpm.engine.management.JobDefinition; +import org.camunda.bpm.engine.management.JobDefinitionQuery; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.repository.DeploymentQuery; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.CaseExecution; +import org.camunda.bpm.engine.runtime.CaseExecutionQuery; +import org.camunda.bpm.engine.runtime.CaseInstance; +import org.camunda.bpm.engine.runtime.CaseInstanceQuery; +import org.camunda.bpm.engine.runtime.Execution; +import org.camunda.bpm.engine.runtime.ExecutionQuery; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.runtime.IncidentQuery; +import org.camunda.bpm.engine.runtime.MessageCorrelationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.runtime.VariableInstanceQuery; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.task.TaskQuery; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.hamcrest.CoreMatchers; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import org.camunda.bpm.engine.runtime.MessageCorrelationResult; + +public class ProcessEngineRestServiceTest extends + AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String ENGINES_URL = TEST_RESOURCE_ROOT_PATH + "/engine"; + protected static final String SINGLE_ENGINE_URL = ENGINES_URL + "/{name}"; + protected static final String PROCESS_DEFINITION_URL = SINGLE_ENGINE_URL + "/process-definition/{id}"; + protected static final String PROCESS_INSTANCE_URL = SINGLE_ENGINE_URL + "/process-instance/{id}"; + protected static final String TASK_URL = SINGLE_ENGINE_URL + "/task/{id}"; + protected static final String IDENTITY_GROUPS_URL = SINGLE_ENGINE_URL + "/identity/groups"; + protected static final String MESSAGE_URL = SINGLE_ENGINE_URL + MessageRestService.PATH; + + protected static final String EXECUTION_URL = SINGLE_ENGINE_URL + "/execution"; + protected static final String VARIABLE_INSTANCE_URL = SINGLE_ENGINE_URL + "/variable-instance"; + protected static final String USER_URL = SINGLE_ENGINE_URL + "/user"; + protected static final String GROUP_URL = SINGLE_ENGINE_URL + "/group"; + protected static final String INCIDENT_URL = SINGLE_ENGINE_URL + "/incident"; + protected static final String AUTHORIZATION_URL = SINGLE_ENGINE_URL + AuthorizationRestService.PATH; + protected static final String AUTHORIZATION_CHECK_URL = AUTHORIZATION_URL + "/check"; + protected static final String DEPLOYMENT_REST_SERVICE_URL = SINGLE_ENGINE_URL + DeploymentRestService.PATH; + protected static final String DEPLOYMENT_URL = DEPLOYMENT_REST_SERVICE_URL + "/{id}"; + protected static final String EXTERNAL_TASKS_URL = SINGLE_ENGINE_URL + "/external-task"; + + protected static final String JOB_DEFINITION_URL = SINGLE_ENGINE_URL + "/job-definition"; + + protected static final String CASE_DEFINITION_URL = SINGLE_ENGINE_URL + "/case-definition"; + protected static final String CASE_INSTANCE_URL = SINGLE_ENGINE_URL + "/case-instance"; + protected static final String CASE_EXECUTION_URL = SINGLE_ENGINE_URL + "/case-execution"; + + protected static final String FILTER_URL = SINGLE_ENGINE_URL + "/filter"; + + protected static final String HISTORY_URL = SINGLE_ENGINE_URL + "/history"; + protected static final String HISTORY_ACTIVITY_INSTANCE_URL = HISTORY_URL + "/activity-instance"; + protected static final String HISTORY_PROCESS_INSTANCE_URL = HISTORY_URL + "/process-instance"; + protected static final String HISTORY_VARIABLE_INSTANCE_URL = HISTORY_URL + "/variable-instance"; + protected static final String HISTORY_BINARY_VARIABLE_INSTANCE_URL = HISTORY_VARIABLE_INSTANCE_URL + "/{id}/data"; + protected static final String HISTORY_ACTIVITY_STATISTICS_URL = HISTORY_URL + "/process-definition/{id}/statistics"; + protected static final String HISTORY_DETAIL_URL = HISTORY_URL + "/detail"; + protected static final String HISTORY_BINARY_DETAIL_URL = HISTORY_DETAIL_URL + "/data"; + protected static final String HISTORY_TASK_INSTANCE_URL = HISTORY_URL + "/task"; + protected static final String HISTORY_INCIDENT_URL = HISTORY_URL + "/incident"; + protected static final String HISTORY_JOB_LOG_URL = HISTORY_URL + "/job-log"; + protected static final String HISTORY_EXTERNAL_TASK_LOG_URL = HISTORY_URL + "/external-task-log"; + + protected static final String EXAMPLE_ENGINE_NAME = "anEngineName"; + + private ProcessEngine namedProcessEngine; + private RepositoryService mockRepoService; + private RuntimeService mockRuntimeService; + private TaskService mockTaskService; + private IdentityService mockIdentityService; + private ManagementService mockManagementService; + private HistoryService mockHistoryService; + private ExternalTaskService mockExternalTaskService; + private CaseService mockCaseService; + private FilterService mockFilterService; + private MessageCorrelationBuilder mockMessageCorrelationBuilder; + private MessageCorrelationResult mockMessageCorrelationResult; + + @Before + public void setUpRuntimeData() { + namedProcessEngine = getProcessEngine(EXAMPLE_ENGINE_NAME); + mockRepoService = mock(RepositoryService.class); + mockRuntimeService = mock(RuntimeService.class); + mockTaskService = mock(TaskService.class); + mockIdentityService = mock(IdentityService.class); + mockManagementService = mock(ManagementService.class); + mockHistoryService = mock(HistoryService.class); + mockCaseService = mock(CaseService.class); + mockFilterService = mock(FilterService.class); + mockExternalTaskService = mock(ExternalTaskService.class); + + when(namedProcessEngine.getRepositoryService()).thenReturn(mockRepoService); + when(namedProcessEngine.getRuntimeService()).thenReturn(mockRuntimeService); + when(namedProcessEngine.getTaskService()).thenReturn(mockTaskService); + when(namedProcessEngine.getIdentityService()).thenReturn(mockIdentityService); + when(namedProcessEngine.getManagementService()).thenReturn(mockManagementService); + when(namedProcessEngine.getHistoryService()).thenReturn(mockHistoryService); + when(namedProcessEngine.getCaseService()).thenReturn(mockCaseService); + when(namedProcessEngine.getFilterService()).thenReturn(mockFilterService); + when(namedProcessEngine.getExternalTaskService()).thenReturn(mockExternalTaskService); + + createProcessDefinitionMock(); + createProcessInstanceMock(); + createTaskMock(); + createIdentityMocks(); + createExecutionMock(); + createVariableInstanceMock(); + createJobDefinitionMock(); + createIncidentMock(); + createDeploymentMock(); + createMessageCorrelationBuilderMock(); + createCaseDefinitionMock(); + createCaseInstanceMock(); + createCaseExecutionMock(); + createFilterMock(); + createExternalTaskMock(); + + createHistoricActivityInstanceMock(); + createHistoricProcessInstanceMock(); + createHistoricVariableInstanceMock(); + createHistoricActivityStatisticsMock(); + createHistoricDetailMock(); + createHistoricTaskInstanceMock(); + createHistoricIncidentMock(); + createHistoricJobLogMock(); + createHistoricExternalTaskLogMock(); + } + + private void createProcessDefinitionMock() { + ProcessDefinition mockDefinition = MockProvider.createMockDefinition(); + + when(mockRepoService.getProcessDefinition(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))).thenReturn(mockDefinition); + } + + + private void createCaseDefinitionMock() { + List caseDefinitions = new ArrayList(); + CaseDefinition mockCaseDefinition = MockProvider.createMockCaseDefinition(); + caseDefinitions.add(mockCaseDefinition); + + CaseDefinitionQuery mockCaseDefinitionQuery = mock(CaseDefinitionQuery.class); + when(mockCaseDefinitionQuery.list()).thenReturn(caseDefinitions); + when(mockRepoService.createCaseDefinitionQuery()).thenReturn(mockCaseDefinitionQuery); + } + + private void createCaseInstanceMock() { + List caseInstances = new ArrayList(); + CaseInstance mockCaseInstance = MockProvider.createMockCaseInstance(); + caseInstances.add(mockCaseInstance); + + CaseInstanceQuery mockCaseInstanceQuery = mock(CaseInstanceQuery.class); + when(mockCaseInstanceQuery.list()).thenReturn(caseInstances); + when(mockCaseService.createCaseInstanceQuery()).thenReturn(mockCaseInstanceQuery); + } + + private void createCaseExecutionMock() { + List caseExecutions = new ArrayList(); + CaseExecution mockCaseExecution = MockProvider.createMockCaseExecution(); + caseExecutions.add(mockCaseExecution); + + CaseExecutionQuery mockCaseExecutionQuery = mock(CaseExecutionQuery.class); + when(mockCaseExecutionQuery.list()).thenReturn(caseExecutions); + when(mockCaseService.createCaseExecutionQuery()).thenReturn(mockCaseExecutionQuery); + } + + private void createProcessInstanceMock() { + ProcessInstance mockInstance = MockProvider.createMockInstance(); + + ProcessInstanceQuery mockInstanceQuery = mock(ProcessInstanceQuery.class); + when(mockInstanceQuery.processInstanceId(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID))).thenReturn(mockInstanceQuery); + when(mockInstanceQuery.singleResult()).thenReturn(mockInstance); + when(mockRuntimeService.createProcessInstanceQuery()).thenReturn(mockInstanceQuery); + } + + private void createExecutionMock() { + Execution mockExecution = MockProvider.createMockExecution(); + + ExecutionQuery mockExecutionQuery = mock(ExecutionQuery.class); + when(mockExecutionQuery.processInstanceId(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID))).thenReturn(mockExecutionQuery); + when(mockExecutionQuery.singleResult()).thenReturn(mockExecution); + when(mockRuntimeService.createExecutionQuery()).thenReturn(mockExecutionQuery); + } + + private void createTaskMock() { + Task mockTask = MockProvider.createMockTask(); + + TaskQuery mockTaskQuery = mock(TaskQuery.class); + when(mockTaskQuery.taskId(eq(MockProvider.EXAMPLE_TASK_ID))).thenReturn(mockTaskQuery); + when(mockTaskQuery.initializeFormKeys()).thenReturn(mockTaskQuery); + when(mockTaskQuery.singleResult()).thenReturn(mockTask); + when(mockTaskService.createTaskQuery()).thenReturn(mockTaskQuery); + } + + private void createIdentityMocks() { + // identity + UserQuery sampleUserQuery = mock(UserQuery.class); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + List mockUsers = new ArrayList(); + User mockUser = MockProvider.createMockUser(); + mockUsers.add(mockUser); + + // user query + when(sampleUserQuery.memberOfGroup(anyString())).thenReturn(sampleUserQuery); + when(sampleUserQuery.list()).thenReturn(mockUsers); + + // group query + List mockGroups = MockProvider.createMockGroups(); + when(sampleGroupQuery.groupMember(anyString())).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.orderByGroupName()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.asc()).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.unlimitedList()).thenReturn(mockGroups); + + when(mockIdentityService.createGroupQuery()).thenReturn(sampleGroupQuery); + when(mockIdentityService.createUserQuery()).thenReturn(sampleUserQuery); + } + + private void createVariableInstanceMock() { + List variables = new ArrayList(); + VariableInstance mockInstance = MockProvider.createMockVariableInstance(); + variables.add(mockInstance); + + VariableInstanceQuery mockVariableInstanceQuery = mock(VariableInstanceQuery.class); + when(mockVariableInstanceQuery.list()).thenReturn(variables); + when(mockRuntimeService.createVariableInstanceQuery()).thenReturn(mockVariableInstanceQuery); + } + + private void createJobDefinitionMock() { + List jobDefinitions = new ArrayList(); + JobDefinition mockJobDefinition = MockProvider.createMockJobDefinition(); + jobDefinitions.add(mockJobDefinition); + + JobDefinitionQuery mockJobDefinitionQuery = mock(JobDefinitionQuery.class); + when(mockJobDefinitionQuery.list()).thenReturn(jobDefinitions); + when(mockManagementService.createJobDefinitionQuery()).thenReturn(mockJobDefinitionQuery); + } + + private void createIncidentMock() { + IncidentQuery mockIncidentQuery = mock(IncidentQuery.class); + List incidents = MockProvider.createMockIncidents(); + when(mockIncidentQuery.list()).thenReturn(incidents); + when(mockRuntimeService.createIncidentQuery()).thenReturn(mockIncidentQuery); + } + + private void createMessageCorrelationBuilderMock() { + mockMessageCorrelationBuilder = mock(MessageCorrelationBuilder.class); + mockMessageCorrelationResult = mock(MessageCorrelationResult.class); + + when(mockRuntimeService.createMessageCorrelation(anyString())).thenReturn(mockMessageCorrelationBuilder); + when(mockMessageCorrelationBuilder.correlateWithResult()).thenReturn(mockMessageCorrelationResult); + when(mockMessageCorrelationBuilder.processInstanceId(anyString())).thenReturn(mockMessageCorrelationBuilder); + when(mockMessageCorrelationBuilder.processInstanceBusinessKey(anyString())).thenReturn(mockMessageCorrelationBuilder); + when(mockMessageCorrelationBuilder.processInstanceVariableEquals(anyString(), any())).thenReturn(mockMessageCorrelationBuilder); + when(mockMessageCorrelationBuilder.setVariables(Mockito.any())).thenReturn(mockMessageCorrelationBuilder); + when(mockMessageCorrelationBuilder.setVariable(anyString(), any())).thenReturn(mockMessageCorrelationBuilder); + + } + + private void createHistoricActivityInstanceMock() { + List activities = new ArrayList(); + HistoricActivityInstance mockInstance = MockProvider.createMockHistoricActivityInstance(); + activities.add(mockInstance); + + HistoricActivityInstanceQuery mockHistoricActivityInstanceQuery = mock(HistoricActivityInstanceQuery.class); + when(mockHistoricActivityInstanceQuery.list()).thenReturn(activities); + when(mockHistoryService.createHistoricActivityInstanceQuery()).thenReturn(mockHistoricActivityInstanceQuery); + } + + private void createHistoricProcessInstanceMock() { + List processes = new ArrayList(); + HistoricProcessInstance mockInstance = MockProvider.createMockHistoricProcessInstance(); + processes.add(mockInstance); + + HistoricProcessInstanceQuery mockHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(mockHistoricProcessInstanceQuery.list()).thenReturn(processes); + when(mockHistoryService.createHistoricProcessInstanceQuery()).thenReturn(mockHistoricProcessInstanceQuery); + } + + private void createHistoricVariableInstanceMock() { + List variables = new ArrayList(); + HistoricVariableInstance mockInstance = MockProvider.createMockHistoricVariableInstance(); + variables.add(mockInstance); + + HistoricVariableInstanceQuery mockHistoricVariableInstanceQuery = mock(HistoricVariableInstanceQuery.class); + when(mockHistoricVariableInstanceQuery.list()).thenReturn(variables); + when(mockHistoryService.createHistoricVariableInstanceQuery()).thenReturn(mockHistoricVariableInstanceQuery); + } + + private void createHistoricActivityStatisticsMock() { + List statistics = MockProvider.createMockHistoricActivityStatistics(); + + HistoricActivityStatisticsQuery query = mock(HistoricActivityStatisticsQueryImpl.class); + when(mockHistoryService.createHistoricActivityStatisticsQuery(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(query); + when(query.list()).thenReturn(statistics); + } + + private void createHistoricDetailMock() { + List details = MockProvider.createMockHistoricDetails(); + + HistoricDetailQuery query = mock(HistoricDetailQuery.class); + when(mockHistoryService.createHistoricDetailQuery()).thenReturn(query); + when(query.list()).thenReturn(details); + } + + private void createHistoricTaskInstanceMock() { + List tasks = MockProvider.createMockHistoricTaskInstances(); + + HistoricTaskInstanceQuery query = mock(HistoricTaskInstanceQuery.class); + when(mockHistoryService.createHistoricTaskInstanceQuery()).thenReturn(query); + when(query.list()).thenReturn(tasks); + } + + private void createHistoricIncidentMock() { + HistoricIncidentQuery mockHistoricIncidentQuery = mock(HistoricIncidentQuery.class); + List historicIncidents = MockProvider.createMockHistoricIncidents(); + when(mockHistoricIncidentQuery.list()).thenReturn(historicIncidents); + when(mockHistoryService.createHistoricIncidentQuery()).thenReturn(mockHistoricIncidentQuery); + } + + private void createDeploymentMock() { + Deployment mockDeployment = MockProvider.createMockDeployment(); + + DeploymentQuery deploymentQueryMock = mock(DeploymentQuery.class); + when(deploymentQueryMock.deploymentId(anyString())).thenReturn(deploymentQueryMock); + when(deploymentQueryMock.singleResult()).thenReturn(mockDeployment); + + when(mockRepoService.createDeploymentQuery()).thenReturn(deploymentQueryMock); + } + + private void createFilterMock() { + List filters = new ArrayList(); + Filter mockFilter = MockProvider.createMockFilter(); + filters.add(mockFilter); + + FilterQuery mockFilterQuery = mock(FilterQuery.class); + when(mockFilterQuery.list()).thenReturn(filters); + when(mockFilterService.createFilterQuery()).thenReturn(mockFilterQuery); + } + + private void createHistoricJobLogMock() { + HistoricJobLogQuery mockHistoricJobLogQuery = mock(HistoricJobLogQuery.class); + List historicJobLogs = MockProvider.createMockHistoricJobLogs(); + when(mockHistoricJobLogQuery.list()).thenReturn(historicJobLogs); + when(mockHistoryService.createHistoricJobLogQuery()).thenReturn(mockHistoricJobLogQuery); + } + + private void createExternalTaskMock() { + ExternalTaskQuery query = mock(ExternalTaskQuery.class); + List tasks = MockProvider.createMockExternalTasks(); + when(query.list()).thenReturn(tasks); + when(mockExternalTaskService.createExternalTaskQuery()).thenReturn(query); + } + + private void createHistoricExternalTaskLogMock() { + HistoricExternalTaskLogQuery mockHistoricExternalTaskLogQuery = mock(HistoricExternalTaskLogQuery.class); + List historicExternalTaskLogs = MockProvider.createMockHistoricExternalTaskLogs(); + when(mockHistoricExternalTaskLogQuery.list()).thenReturn(historicExternalTaskLogs); + when(mockHistoryService.createHistoricExternalTaskLogQuery()).thenReturn(mockHistoricExternalTaskLogQuery); + } + + @Test + public void testNonExistingEngineAccess() { + given().pathParam("name", MockProvider.NON_EXISTING_PROCESS_ENGINE_NAME) + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No process engine available")) + .when().get(PROCESS_DEFINITION_URL); + } + + @Test + public void testEngineNamesList() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("name", hasItems(MockProvider.EXAMPLE_PROCESS_ENGINE_NAME, MockProvider.ANOTHER_EXAMPLE_PROCESS_ENGINE_NAME)) + .when().get(ENGINES_URL); + } + + @Test + public void testProcessDefinitionServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_URL); + + verify(mockRepoService).getProcessDefinition(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + verifyNoInteractions(processEngine); + } + + @Test + public void testProcessInstanceServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_URL); + + verify(mockRuntimeService).createProcessInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testTaskServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(TASK_URL); + + verify(mockTaskService).createTaskQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testIdentityServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .queryParam("userId", "someId") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(IDENTITY_GROUPS_URL); + + verify(mockIdentityService).createUserQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testMessageServiceEngineAccess() { + String messageName = "aMessage"; + Map messageParameters = new HashMap(); + messageParameters.put("messageName", messageName); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters).pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(mockRuntimeService).createMessageCorrelation(eq(messageName)); + verify(mockMessageCorrelationBuilder).correlateWithResult(); + verifyNoMoreInteractions(mockMessageCorrelationBuilder); + verifyNoInteractions(processEngine); + } + + @Test + public void testMessageWithResultServiceEngineAccess() { + String messageName = "aMessage"; + Map messageParameters = new HashMap(); + messageParameters.put("messageName", messageName); + messageParameters.put("resultEnabled", true); + + given().contentType(POST_JSON_CONTENT_TYPE).body(messageParameters).pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect().contentType(ContentType.JSON).statusCode(Status.OK.getStatusCode()) + .when().post(MESSAGE_URL); + + verify(mockRuntimeService).createMessageCorrelation(eq(messageName)); + verify(mockMessageCorrelationBuilder).correlateWithResult(); + verifyNoMoreInteractions(mockMessageCorrelationBuilder); + verifyNoInteractions(processEngine); + } + + + @Test + public void testExecutionServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(EXECUTION_URL); + + verify(mockRuntimeService).createExecutionQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testVariableInstanceServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_URL); + + verify(mockRuntimeService).createVariableInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testUserServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(USER_URL); + + verify(mockIdentityService).createUserQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testGroupServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(GROUP_URL); + + verify(mockIdentityService).createGroupQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testAuthorizationServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(AUTHORIZATION_CHECK_URL); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricActivityInstance() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_ACTIVITY_INSTANCE_URL); + + verify(mockHistoryService).createHistoricActivityInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricProcessInstance() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_PROCESS_INSTANCE_URL); + + verify(mockHistoryService).createHistoricProcessInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricVariableInstance() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_VARIABLE_INSTANCE_URL); + + verify(mockHistoryService).createHistoricVariableInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Ignore + @Test + public void testHistoryServiceEngineAccess_HistoricVariableInstanceBinaryFile() { + + HistoricVariableInstanceQuery query = mock(HistoricVariableInstanceQuery.class); + HistoricVariableInstance instance = mock(HistoricVariableInstance.class); + String filename = "test.txt"; + byte[] byteContent = "test".getBytes(); + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + when(instance.getTypedValue()).thenReturn(variableValue); + when(query.singleResult()).thenReturn(instance); + when(mockHistoryService.createHistoricVariableInstanceQuery()).thenReturn(query); + + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + . body(is(equalTo(new String(byteContent)))) + .and() + .header("Content-Disposition", "attachment; " + + "filename=\"" + filename + "\"; " + + "filename*=UTF-8''" + filename) + .contentType(CoreMatchers.either(equalTo(ContentType.TEXT.toString() + ";charset=UTF-8")).or(equalTo(ContentType.TEXT.toString() + " ;charset=UTF-8"))) + .when() + .get(HISTORY_BINARY_VARIABLE_INSTANCE_URL); + + verify(mockHistoryService).createHistoricVariableInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricActivityStatistics() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_ACTIVITY_STATISTICS_URL); + + verify(mockHistoryService).createHistoricActivityStatisticsQuery(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verifyNoInteractions(processEngine); + } + + @Test + public void testJobDefinitionAccess() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(JOB_DEFINITION_URL); + + verify(mockManagementService).createJobDefinitionQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricDetail() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_DETAIL_URL); + + verify(mockHistoryService).createHistoricDetailQuery(); + verifyNoInteractions(processEngine); + } + + @Ignore + @Test + public void testHistoryServiceEngineAccess_HistoricDetailBinaryFile() { + HistoricDetailQuery query = mock(HistoricDetailQuery.class); + HistoricVariableUpdate instance = mock(HistoricVariableUpdate.class); + String filename = "test.txt"; + byte[] byteContent = "test".getBytes(); + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + when(instance.getTypedValue()).thenReturn(variableValue); + when(query.singleResult()).thenReturn(instance); + when(mockHistoryService.createHistoricDetailQuery()).thenReturn(query); + + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + . body(is(equalTo(new String(byteContent)))) + .and() + .header("Content-Disposition", "attachment; " + + "filename=\"" + filename + "\"; " + + "filename*=UTF-8''" + filename) + .contentType(CoreMatchers.either(equalTo(ContentType.TEXT.toString() + ";charset=UTF-8")).or(equalTo(ContentType.TEXT.toString() + " ;charset=UTF-8"))) + .when() + .get(HISTORY_BINARY_DETAIL_URL); + + verify(mockHistoryService).createHistoricDetailQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricTaskInstance() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_TASK_INSTANCE_URL); + + verify(mockHistoryService).createHistoricTaskInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_Incident() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(INCIDENT_URL); + + verify(mockRuntimeService).createIncidentQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricIncident() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_URL); + + verify(mockHistoryService).createHistoricIncidentQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testDeploymentRestServiceEngineAccess() { + given().pathParam("name", EXAMPLE_ENGINE_NAME) + .pathParam("id", MockProvider.EXAMPLE_DEPLOYMENT_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_URL); + + verify(mockRepoService).createDeploymentQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testGetRegisteredDeployments() { + final Set registeredDeployments = new HashSet<>(Arrays.asList("deployment1", "deployment2")); + when(mockManagementService.getRegisteredDeployments()).thenReturn(registeredDeployments); + + final Response response = given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(DEPLOYMENT_REST_SERVICE_URL + "/registered"); + + verify(mockManagementService).getRegisteredDeployments(); + verifyNoInteractions(processEngine); + + assertThat(response.getBody().as(Set.class)).isEqualTo(registeredDeployments); + } + + @Test + public void testCaseDefinitionAccess() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_DEFINITION_URL); + + verify(mockRepoService).createCaseDefinitionQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testCaseInstanceAccess() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_INSTANCE_URL); + + verify(mockCaseService).createCaseInstanceQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testCaseExecutionAccess() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(CASE_EXECUTION_URL); + + verify(mockCaseService).createCaseExecutionQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testFilterAccess() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(FILTER_URL); + + verify(mockFilterService).createFilterQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricJobLog() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_JOB_LOG_URL); + + verify(mockHistoryService).createHistoricJobLogQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testExternalTaskAccess() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(EXTERNAL_TASKS_URL); + + verify(mockExternalTaskService).createExternalTaskQuery(); + verifyNoInteractions(processEngine); + } + + @Test + public void testHistoryServiceEngineAccess_HistoricExternalTaskLog() { + given() + .pathParam("name", EXAMPLE_ENGINE_NAME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_EXTERNAL_TASK_LOG_URL); + + verify(mockHistoryService).createHistoricExternalTaskLogQuery(); + verifyNoInteractions(processEngine); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..30a9e332e84ccb468699d320d6d9aa5abfc58a53 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceInteractionTest.java @@ -0,0 +1,4896 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_PROCESS_INSTANCE_COMMENT_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockBatch; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockHistoricProcessInstance; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEFAULTS; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; +import org.assertj.core.api.Assertions; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl; +import org.camunda.bpm.engine.impl.HistoryServiceImpl; +import org.camunda.bpm.engine.impl.ManagementServiceImpl; +import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.impl.batch.BatchEntity; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.management.SetJobRetriesByProcessAsyncBuilder; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceSuspensionStateDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.CorrelationMessageAsyncDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.DeleteProcessInstancesDto; +import org.camunda.bpm.engine.rest.dto.runtime.batch.SetVariablesAsyncDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.EqualsList; +import org.camunda.bpm.engine.rest.helper.EqualsMap; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.ExampleVariableObject; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.helper.variable.EqualsNullValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.util.JsonPathUtil; +import org.camunda.bpm.engine.rest.util.ModificationInstructionBuilder; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.MessageCorrelationAsyncBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceModificationInstantiationBuilder; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; +import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateSelectBuilder; +import org.camunda.bpm.engine.runtime.UpdateProcessInstanceSuspensionStateTenantBuilder; +import org.camunda.bpm.engine.runtime.UpdateProcessInstancesSuspensionStateBuilder; +import org.camunda.bpm.engine.task.Comment; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.LongValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.hamcrest.Matchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +public class ProcessInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + protected static final String TEST_DELETE_REASON = "test"; + protected static final String RETRIES = "retries"; + protected static final String FAIL_IF_NOT_EXISTS = "failIfNotExists"; + protected static final String DELETE_REASON = "deleteReason"; + protected static final String SKIP_IO_MAPPINGS = "skipIoMappings"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/process-instance"; + protected static final String SINGLE_PROCESS_INSTANCE_URL = PROCESS_INSTANCE_URL + "/{id}"; + protected static final String PROCESS_INSTANCE_VARIABLES_URL = SINGLE_PROCESS_INSTANCE_URL + "/variables"; + protected static final String PROCESS_INSTANCE_COMMENTS_URL = SINGLE_PROCESS_INSTANCE_URL + "/comment"; + protected static final String SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL = + PROCESS_INSTANCE_COMMENTS_URL + "/{commentId}"; + protected static final String DELETE_PROCESS_INSTANCES_ASYNC_URL = PROCESS_INSTANCE_URL + "/delete"; + protected static final String DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL = PROCESS_INSTANCE_URL + "/delete-historic-query-based"; + protected static final String SET_JOB_RETRIES_ASYNC_URL = PROCESS_INSTANCE_URL + "/job-retries"; + protected static final String SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL = PROCESS_INSTANCE_URL + "/job-retries-historic-query-based"; + protected static final String SINGLE_PROCESS_INSTANCE_VARIABLE_URL = PROCESS_INSTANCE_VARIABLES_URL + "/{varId}"; + protected static final String SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL = SINGLE_PROCESS_INSTANCE_VARIABLE_URL + "/data"; + protected static final String PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL = SINGLE_PROCESS_INSTANCE_URL + "/activity-instances"; + protected static final String EXAMPLE_PROCESS_INSTANCE_ID_WITH_NULL_VALUE_AS_VARIABLE = "aProcessInstanceWithNullValueAsVariable"; + protected static final String SINGLE_PROCESS_INSTANCE_SUSPENDED_URL = SINGLE_PROCESS_INSTANCE_URL + "/suspended"; + protected static final String PROCESS_INSTANCE_SUSPENDED_URL = PROCESS_INSTANCE_URL + "/suspended"; + protected static final String PROCESS_INSTANCE_SUSPENDED_ASYNC_URL = PROCESS_INSTANCE_URL + "/suspended-async"; + protected static final String PROCESS_INSTANCE_MODIFICATION_URL = SINGLE_PROCESS_INSTANCE_URL + "/modification"; + protected static final String PROCESS_INSTANCE_MODIFICATION_ASYNC_URL = SINGLE_PROCESS_INSTANCE_URL + "/modification-async"; + protected static final String PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL = PROCESS_INSTANCE_URL + "/variables-async"; + protected static final String PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL = PROCESS_INSTANCE_URL + "/message-async"; + + protected static final Answer RETURNS_SELF = invocation -> { + Object mock = invocation.getMock(); + if(invocation.getMethod().getReturnType().isInstance(mock)){ + return mock; + } + return RETURNS_DEFAULTS.answer(invocation); + }; + + protected static final VariableMap EXAMPLE_OBJECT_VARIABLES = Variables.createVariables(); + static { + ExampleVariableObject variableValue = new ExampleVariableObject(); + variableValue.setProperty1("aPropertyValue"); + variableValue.setProperty2(true); + + EXAMPLE_OBJECT_VARIABLES.putValueTyped(EXAMPLE_VARIABLE_KEY, + MockObjectValue + .fromObjectValue(Variables.objectValue(variableValue).serializationDataFormat("application/json").create()) + .objectTypeName(ExampleVariableObject.class.getName())); + } + + private List mockTaskComments; + private HistoricProcessInstanceQuery historicProcessInstanceQueryMock; + + private RuntimeServiceImpl runtimeServiceMock; + private ManagementServiceImpl mockManagementService; + private HistoryServiceImpl historyServiceMock; + private TaskService taskServiceMock; + + private UpdateProcessInstanceSuspensionStateTenantBuilder mockUpdateSuspensionStateBuilder; + private UpdateProcessInstanceSuspensionStateSelectBuilder mockUpdateSuspensionStateSelectBuilder; + private UpdateProcessInstancesSuspensionStateBuilder mockUpdateProcessInstancesSuspensionStateBuilder; + + private SetJobRetriesByProcessAsyncBuilder mockSetJobRetriesByProcessAsyncBuilder; + + @Before + public void setUpRuntimeData() { + runtimeServiceMock = mock(RuntimeServiceImpl.class); + mockManagementService = mock(ManagementServiceImpl.class); + historyServiceMock = mock(HistoryServiceImpl.class); + + // variables + when(runtimeServiceMock.getVariablesTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, true)).thenReturn(EXAMPLE_VARIABLES); + when(runtimeServiceMock.getVariablesTyped(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, true)).thenReturn(EXAMPLE_OBJECT_VARIABLES); + when(runtimeServiceMock.getVariablesTyped(EXAMPLE_PROCESS_INSTANCE_ID_WITH_NULL_VALUE_AS_VARIABLE, true)).thenReturn(EXAMPLE_VARIABLES_WITH_NULL_VALUE); + + // activity instances + when(runtimeServiceMock.getActivityInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)).thenReturn(EXAMPLE_ACTIVITY_INSTANCE); + + mockUpdateSuspensionStateSelectBuilder = mock(UpdateProcessInstanceSuspensionStateSelectBuilder.class); + when(runtimeServiceMock.updateProcessInstanceSuspensionState()).thenReturn(mockUpdateSuspensionStateSelectBuilder); + + mockUpdateSuspensionStateBuilder = mock(UpdateProcessInstanceSuspensionStateTenantBuilder.class); + when(mockUpdateSuspensionStateSelectBuilder.byProcessInstanceId(any())).thenReturn(mockUpdateSuspensionStateBuilder); + when(mockUpdateSuspensionStateSelectBuilder.byProcessDefinitionId(any())).thenReturn(mockUpdateSuspensionStateBuilder); + when(mockUpdateSuspensionStateSelectBuilder.byProcessDefinitionKey(any())).thenReturn(mockUpdateSuspensionStateBuilder); + + mockUpdateProcessInstancesSuspensionStateBuilder = mock(UpdateProcessInstancesSuspensionStateBuilder.class); + when(mockUpdateSuspensionStateSelectBuilder.byProcessInstanceIds(Mockito.>any())).thenReturn(mockUpdateProcessInstancesSuspensionStateBuilder); + when(mockUpdateSuspensionStateSelectBuilder.byProcessInstanceQuery(any())).thenReturn(mockUpdateProcessInstancesSuspensionStateBuilder); + when(mockUpdateSuspensionStateSelectBuilder.byHistoricProcessInstanceQuery(any())).thenReturn(mockUpdateProcessInstancesSuspensionStateBuilder); + + // tasks and task service + taskServiceMock = mock(TaskService.class); + when(processEngine.getTaskService()).thenReturn(taskServiceMock); + + mockTaskComments = MockProvider.createMockTaskComments(); + when(taskServiceMock.getProcessInstanceComments(EXAMPLE_PROCESS_INSTANCE_ID)).thenReturn(mockTaskComments); + + historicProcessInstanceQueryMock = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQueryMock); + when(historicProcessInstanceQueryMock.processInstanceId(eq(EXAMPLE_PROCESS_INSTANCE_ID))).thenReturn(historicProcessInstanceQueryMock); + HistoricProcessInstance historicProcessInstanceMock = createMockHistoricProcessInstance(); + when(historicProcessInstanceQueryMock.singleResult()).thenReturn(historicProcessInstanceMock); + + // runtime service + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + when(processEngine.getManagementService()).thenReturn(mockManagementService); + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + // jobs + mockSetJobRetriesByProcessAsyncBuilder = MockProvider.createMockSetJobRetriesByProcessAsyncBuilder(mockManagementService); + } + + public void mockHistoryFull() { + when(mockManagementService.getHistoryLevel()).thenReturn(ProcessEngineConfigurationImpl.HISTORYLEVEL_FULL); + } + + public void mockHistoryDisabled() { + when(mockManagementService.getHistoryLevel()).thenReturn(ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE); + } + + @Test + public void testGetActivityInstanceTree() { + Response response = given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", Matchers.equalTo(EXAMPLE_ACTIVITY_INSTANCE_ID)) + .body("parentActivityInstanceId", Matchers.equalTo(EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID)) + .body("activityId", Matchers.equalTo(EXAMPLE_ACTIVITY_ID)) + .body("processInstanceId", Matchers.equalTo(EXAMPLE_PROCESS_INSTANCE_ID)) + .body("processDefinitionId", Matchers.equalTo(EXAMPLE_PROCESS_DEFINITION_ID)) + .body("executionIds", Matchers.not(Matchers.empty())) + .body("executionIds[0]", Matchers.equalTo(EXAMPLE_EXECUTION_ID)) + .body("activityName", Matchers.equalTo(EXAMPLE_ACTIVITY_NAME)) + // "name" is deprecated and there for legacy reasons + .body("name", Matchers.equalTo(EXAMPLE_ACTIVITY_NAME)) + .body("incidentIds", Matchers.empty()) + .body("incidents", Matchers.not(Matchers.empty())) + .body("incidents[0].id", Matchers.equalTo("anIncidentId")) + .body("incidents[0].activityId", Matchers.equalTo("anActivityId")) + .body("childActivityInstances", Matchers.not(Matchers.empty())) + .body("childActivityInstances[0].id", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_INSTANCE_ID)) + .body("childActivityInstances[0].parentActivityInstanceId", Matchers.equalTo(CHILD_EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID)) + .body("childActivityInstances[0].activityId", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_ID)) + .body("childActivityInstances[0].activityType", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_TYPE)) + .body("childActivityInstances[0].activityName", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_NAME)) + .body("childActivityInstances[0].name", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_NAME)) + .body("childActivityInstances[0].processInstanceId", Matchers.equalTo(CHILD_EXAMPLE_PROCESS_INSTANCE_ID)) + .body("childActivityInstances[0].processDefinitionId", Matchers.equalTo(CHILD_EXAMPLE_PROCESS_DEFINITION_ID)) + .body("childActivityInstances[0].executionIds", Matchers.not(Matchers.empty())) + .body("childActivityInstances[0].childActivityInstances", Matchers.empty()) + .body("childActivityInstances[0].childTransitionInstances", Matchers.empty()) + .body("childActivityInstances[0].incidentIds", Matchers.not(Matchers.empty())) + .body("childActivityInstances[0].incidentIds[0]", Matchers.equalTo(EXAMPLE_INCIDENT_ID)) + .body("childActivityInstances[0].incidents[0].id", Matchers.equalTo("anIncidentId")) + .body("childActivityInstances[0].incidents[0].activityId", Matchers.equalTo("anActivityId")) + .body("childTransitionInstances", Matchers.not(Matchers.empty())) + .body("childTransitionInstances[0].id", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_INSTANCE_ID)) + .body("childTransitionInstances[0].parentActivityInstanceId", Matchers.equalTo(CHILD_EXAMPLE_PARENT_ACTIVITY_INSTANCE_ID)) + .body("childTransitionInstances[0].activityId", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_ID)) + .body("childTransitionInstances[0].activityName", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_NAME)) + .body("childTransitionInstances[0].activityType", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_TYPE)) + .body("childTransitionInstances[0].targetActivityId", Matchers.equalTo(CHILD_EXAMPLE_ACTIVITY_ID)) + .body("childTransitionInstances[0].processInstanceId", Matchers.equalTo(CHILD_EXAMPLE_PROCESS_INSTANCE_ID)) + .body("childTransitionInstances[0].processDefinitionId", Matchers.equalTo(CHILD_EXAMPLE_PROCESS_DEFINITION_ID)) + .body("childTransitionInstances[0].executionId", Matchers.equalTo(EXAMPLE_EXECUTION_ID)) + .body("childTransitionInstances[0].incidentIds", Matchers.not(Matchers.empty())) + .body("childTransitionInstances[0].incidentIds[0]", Matchers.equalTo(EXAMPLE_ANOTHER_INCIDENT_ID)) + .body("childTransitionInstances[0].incidents[0].id", Matchers.equalTo("anIncidentId")) + .body("childTransitionInstances[0].incidents[0].activityId", Matchers.equalTo("anActivityId")) + .when().get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL); + + Assert.assertEquals("Should return right number of properties", 13, + response.jsonPath().getMap("").size()); + } + + @Test + public void testGetActivityInstanceTreeForNonExistingProcessInstance() { + when(runtimeServiceMock.getActivityInstance(anyString())).thenReturn(null); + + given().pathParam("id", "aNonExistingProcessInstanceId") + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Process instance with id aNonExistingProcessInstanceId does not exist")) + .when().get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL); + } + + @Test + public void testGetActivityInstanceTreeWithInternalError() { + when(runtimeServiceMock.getActivityInstance(anyString())).thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", "aNonExistingProcessInstanceId") + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("expected exception")) + .when().get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL); + } + + @Test + public void testGetActivityInstanceTreeThrowsAuthorizationException() { + String message = "expected exception"; + when(runtimeServiceMock.getActivityInstance(anyString())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .get(PROCESS_INSTANCE_ACTIVIY_INSTANCES_URL); + } + + @Test + public void testGetVariables() { + Response response = given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, Matchers.notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value", Matchers.equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body(EXAMPLE_VARIABLE_KEY + ".type", Matchers.equalTo(String.class.getSimpleName())) + .when().get(PROCESS_INSTANCE_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + } + + @Test + public void testDeleteAsync() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + when(runtimeServiceMock.deleteProcessInstancesAsync(any(), any(), any(), anyString(), anyBoolean(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity()); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL); + + verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync(ids, null, null, TEST_DELETE_REASON, false, false, false); + } + + @Test + public void testDeleteAsyncWithSkipIoMappingsTrue() { + var ids = List.of(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + when(runtimeServiceMock.deleteProcessInstancesAsync(any(), any(), any(), anyString(), anyBoolean(), anyBoolean(), eq(true))).thenReturn(new BatchEntity()); + + var messageBodyJson = Map.of( + "processInstanceIds", ids, + DELETE_REASON, TEST_DELETE_REASON, + SKIP_IO_MAPPINGS, true + ); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL); + + verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync(ids, null, null, TEST_DELETE_REASON, false, false, true); + } + + @Test + public void testDeleteAsyncWithSkipIoMappingsFalse() { + var ids = List.of(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + when(runtimeServiceMock.deleteProcessInstancesAsync(any(), any(), any(), anyString(), anyBoolean(), anyBoolean(), eq(false))).thenReturn(new BatchEntity()); + + var messageBodyJson = Map.of( + "processInstanceIds", ids, + DELETE_REASON, TEST_DELETE_REASON, + SKIP_IO_MAPPINGS, false + ); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL); + + verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync(ids, null, null, TEST_DELETE_REASON, false, false, false); + } + + @Test + public void testDeleteAsyncWithQuery() { + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + messageBodyJson.put("processInstanceQuery", query); + + when(runtimeServiceMock.deleteProcessInstancesAsync(any(), any(), any(), anyString(), anyBoolean(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity()); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL); + + verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync( + any(), + any(), + any(), + eq(TEST_DELETE_REASON), + eq(false), + eq(false), + eq(false) + ); + } + + @Test + public void testDeleteAsyncWithBadRequestQuery() { + doThrow(new BadUserRequestException("process instance ids are empty")) + .when(runtimeServiceMock).deleteProcessInstancesAsync(eq(null), eq(null), any(), anyString(), anyBoolean(), anyBoolean(), anyBoolean()); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL); + } + + @Test + public void testDeleteAsyncWithSkipCustomListeners() { + when(runtimeServiceMock.deleteProcessInstancesAsync(any(), any(), any(), anyString(), anyBoolean(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity()); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + messageBodyJson.put("processInstanceIds", Arrays.asList("processInstanceId1", "processInstanceId2")); + messageBodyJson.put("skipCustomListeners", true); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL); + + verify(runtimeServiceMock).deleteProcessInstancesAsync( + anyList(), + any(), + any(), + eq(TEST_DELETE_REASON), + eq(true), + eq(false), + eq(false) + ); + } + + @Test + public void testDeleteAsyncWithSkipSubprocesses() { + when(runtimeServiceMock.deleteProcessInstancesAsync(any(), any(), any(), anyString(), anyBoolean(), anyBoolean(), anyBoolean())).thenReturn(new BatchEntity()); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + messageBodyJson.put("processInstanceIds", Arrays.asList("processInstanceId1", "processInstanceId2")); + messageBodyJson.put("skipSubprocesses", true); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_URL); + + verify(runtimeServiceMock).deleteProcessInstancesAsync( + anyList(), + any(), + any(), + eq(TEST_DELETE_REASON), + eq(false), + eq(true), + eq(false) + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithQuery() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + any(), + eq((ProcessInstanceQuery)null), + any(), + any(), + anyBoolean(), + anyBoolean(), + anyBoolean() + )) + .thenReturn(new BatchEntity()); + + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQueryImpl.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setHistoricProcessInstanceQuery(new HistoricProcessInstanceQueryDto()); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, + times(1)).deleteProcessInstancesAsync( + null, + null, + mockedHistoricProcessInstanceQuery, + null, + false, + false, + false + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithProcessInstanceIds() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + any(), + eq((ProcessInstanceQuery)null), + eq((HistoricProcessInstanceQuery)null), + any(), + anyBoolean(), + anyBoolean(), + anyBoolean() + )) + .thenReturn(new BatchEntity()); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setProcessInstanceIds(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, + times(1)).deleteProcessInstancesAsync( + Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), + null, + null, + null, + false, + false, + false + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithQueryAndProcessInstanceIds() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + any(), + eq((ProcessInstanceQuery)null), + any(), + any(), + anyBoolean(), + anyBoolean(), + anyBoolean() + )) + .thenReturn(new BatchEntity()); + + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQueryImpl.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setHistoricProcessInstanceQuery(new HistoricProcessInstanceQueryDto()); + body.setProcessInstanceIds(Collections.singletonList(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID)); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, + times(1)).deleteProcessInstancesAsync( + Collections.singletonList(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID), + null, + mockedHistoricProcessInstanceQuery, + null, + false, + false, + false + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithoutQueryAndWithoutProcessInstanceIds() { + doThrow(new BadUserRequestException("processInstanceIds is empty")) + .when(runtimeServiceMock).deleteProcessInstancesAsync( + eq((List)null), + eq((ProcessInstanceQuery)null), + eq((HistoricProcessInstanceQuery)null), + any(), + anyBoolean(), + anyBoolean(), + anyBoolean()); + + given() + .contentType(ContentType.JSON).body(new DeleteProcessInstancesDto()) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, + times(1)).deleteProcessInstancesAsync( + null, + null, + null, + null, + false, + false, + false + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithDeleteReason() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + any(), + any(), + any(), + any(), + anyBoolean(), + anyBoolean(), + anyBoolean() + )) + .thenReturn(new BatchEntity()); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setDeleteReason(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, + times(1)).deleteProcessInstancesAsync( + null, + null, + null, + MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON, + false, + false, + false + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithSkipCustomListenerTrue() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + eq((List)null), + eq((ProcessInstanceQuery)null), + any(), + any(), + anyBoolean(), + anyBoolean(), + anyBoolean() + )) + .thenReturn(new BatchEntity()); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setSkipCustomListeners(true); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, + times(1)).deleteProcessInstancesAsync( + null, + null, + null, + null, + true, + false, + false + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithSkipSubprocesses() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + eq((List)null), + eq((ProcessInstanceQuery)null), + eq((HistoricProcessInstanceQuery)null), + any(), + anyBoolean(), + anyBoolean(), + anyBoolean() + )) + .thenReturn(new BatchEntity()); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setSkipSubprocesses(true); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, + times(1)).deleteProcessInstancesAsync( + null, + null, + null, + null, + false, + true, + false + ); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithSkipIoMappingsTrue() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + eq(null), + eq(null), + eq(null), + any(), + anyBoolean(), + anyBoolean(), + eq(true) + )).thenReturn(new BatchEntity()); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setSkipIoMappings(true); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync(null, null, null, null, false, false, true); + } + + @Test + public void testDeleteAsyncHistoricQueryBasedWithSkipIoMappingsFalse() { + when(runtimeServiceMock.deleteProcessInstancesAsync( + eq(null), + eq(null), + eq(null), + any(), + anyBoolean(), + anyBoolean(), + eq(false) + )) + .thenReturn(new BatchEntity()); + + DeleteProcessInstancesDto body = new DeleteProcessInstancesDto(); + body.setSkipIoMappings(false); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_PROCESS_INSTANCES_ASYNC_HIST_QUERY_URL); + + verify(runtimeServiceMock, times(1)).deleteProcessInstancesAsync(null, null, null, null, false, false, false); + } + + @Test + public void testGetVariablesWithNullValue() { + Response response = given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID_WITH_NULL_VALUE_AS_VARIABLE) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_ANOTHER_VARIABLE_KEY, Matchers.notNullValue()) + .body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".value", Matchers.nullValue()) + .body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".type", Matchers.equalTo("Null")) + .when().get(PROCESS_INSTANCE_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + } + + @Test + public void testGetProcessInstanceComments() { + mockHistoryFull(); + + Response response = given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(1)) + .when() + .get(PROCESS_INSTANCE_COMMENTS_URL); + + verifyTaskComments(mockTaskComments, response); + verify(taskServiceMock).getProcessInstanceComments(EXAMPLE_PROCESS_INSTANCE_ID); + } + + @Test + public void testGetProcessInstanceCommentsWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testDeleteInstanceCommentThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock) + .deleteProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_PROCESS_INSTANCE_COMMENT_ID); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("commentId", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteInstanceComment() { + mockHistoryFull(); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("commentId", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL); + + verify(taskServiceMock).deleteProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_PROCESS_INSTANCE_COMMENT_ID); + } + + @Test + public void testDeleteInstanceCommentWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("commentId", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteInstanceCommentForNonExistingCommentId() { + mockHistoryFull(); + doThrow(new NullValueException()).when(taskServiceMock) + .deleteProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, NON_EXISTING_ID); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("commentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .delete(SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteInstanceCommentForNonExistingCommentIdWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("commentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteInstanceCommentForNonExistingProcessInstance() { + mockHistoryFull(); + historicProcessInstanceQueryMock = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQueryMock); + when(historicProcessInstanceQueryMock.processInstanceId(eq(NON_EXISTING_ID))).thenReturn( + historicProcessInstanceQueryMock); + when(historicProcessInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", NON_EXISTING_ID) + .pathParam("commentId", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No process instance found for id " + NON_EXISTING_ID)) + .when() + .delete(SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteInstanceCommentForNonExistingWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", NON_EXISTING_ID) + .pathParam("commentId", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_PROCESS_INSTANCE_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteProcessInstanceCommentsThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock) + .deleteProcessInstanceComments(MockProvider.EXAMPLE_TASK_ID); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .when() + .delete(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testDeleteProcessInstanceComments() { + mockHistoryFull(); + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(PROCESS_INSTANCE_COMMENTS_URL); + + verify(taskServiceMock).deleteProcessInstanceComments(EXAMPLE_PROCESS_INSTANCE_ID); + } + + @Test + public void testDeleteProcessInstanceCommentsWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testDeleteProcessInstanceCommentsForNonExisting() { + mockHistoryFull(); + historicProcessInstanceQueryMock = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQueryMock); + when(historicProcessInstanceQueryMock.processInstanceId(eq(NON_EXISTING_ID))).thenReturn( + historicProcessInstanceQueryMock); + when(historicProcessInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No process instance found for id " + NON_EXISTING_ID)) + .when() + .delete(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testDeleteProcessInstanceCommentsForNonExistingWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testUpdateProcessInstanceCommentCommentIdNull() { + mockHistoryFull(); + + String message = "expected exception"; + doThrow(new NullValueException(message)).when(taskServiceMock) + .updateProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, null, EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + + Map json = new HashMap<>(); + + json.put("id", null); + json.put("message", EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testUpdateProcessInstanceCommentMessageIsNull() { + mockHistoryFull(); + + String message = "expected exception"; + doThrow(new NullValueException(message)).when(taskServiceMock) + .updateProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_PROCESS_INSTANCE_COMMENT_ID, null); + + Map json = new HashMap<>(); + + json.put("id", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID); + json.put("message", null); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testUpdateProcessInstanceComment() { + mockHistoryFull(); + Map json = new HashMap<>(); + + json.put("id", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID); + json.put("message", EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_COMMENTS_URL); + + verify(taskServiceMock).updateProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, + EXAMPLE_PROCESS_INSTANCE_COMMENT_ID, EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + } + + @Test + public void testUpdateProcessInstanceCommentExtraProperties() { + mockHistoryFull(); + + Map json = new HashMap<>(); + //Only id and message are used + json.put("id", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID); + json.put("userId", "anyUserId"); + json.put("time", withTimezone("2014-01-01T00:00:00")); + json.put("message", EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + json.put("removalTime", withTimezone("2014-05-01T00:00:00")); + json.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_COMMENTS_URL); + + verify(taskServiceMock).updateProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, + EXAMPLE_PROCESS_INSTANCE_COMMENT_ID, EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + } + + @Test + public void testUpdateProcessInstanceCommentProcessInstanceIdNotFound() { + mockHistoryFull(); + historicProcessInstanceQueryMock = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(historicProcessInstanceQueryMock); + when(historicProcessInstanceQueryMock.processInstanceId(eq(NON_EXISTING_ID))).thenReturn( + historicProcessInstanceQueryMock); + when(historicProcessInstanceQueryMock.singleResult()).thenReturn(null); + + Map json = new HashMap<>(); + + json.put("id", EXAMPLE_PROCESS_INSTANCE_ID); + json.put("message", EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + + given().pathParam("id", NON_EXISTING_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body(containsString("No process instance found for id " + NON_EXISTING_ID)) + .when() + .put(PROCESS_INSTANCE_COMMENTS_URL); + } + + @Test + public void testUpdateProcessInstanceCommentThrowsAuthorizationException() { + mockHistoryFull(); + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock) + .updateProcessInstanceComment(EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_PROCESS_INSTANCE_COMMENT_ID, + EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + + Map json = new HashMap<>(); + json.put("id", EXAMPLE_PROCESS_INSTANCE_COMMENT_ID); + json.put("message", EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE); + + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .put(PROCESS_INSTANCE_COMMENTS_URL); + + } + + @Test + public void testGetFileVariable() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(mimeType).create(); + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), eq(true))) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON.toString()) + .and() + .body("valueInfo.mimeType", Matchers.equalTo(mimeType)) + .body("valueInfo.filename", Matchers.equalTo(filename)) + .body("value", Matchers.nullValue()) + .when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testGetNullFileVariable() { + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).mimeType(mimeType).create(); + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(Matchers.is(Matchers.equalTo(""))) + .when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(Matchers.is(Matchers.equalTo(new String(byteContent)))) + .when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithTypeAndEncoding() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(Matchers.is(Matchers.equalTo(new String(byteContent)))) + .when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + String contentType = response.contentType().replaceAll(" ", ""); + assertThat(contentType, Matchers.is(ContentType.TEXT + ";charset=" + encoding)); + } + + @Test + public void testGetFileVariableDownloadWithoutType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).create(); + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .and() + .body(Matchers.is(Matchers.equalTo(new String(byteContent)))) + .header("Content-Disposition", Matchers.containsString(filename)) + .when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testCannotDownloadVariableOtherThanFile() { + String variableKey = "aVariableKey"; + LongValue variableValue = Variables.longValue(123L); + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(MediaType.APPLICATION_JSON) + .and() + .when().get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testJavaObjectVariableSerialization() { + Response response = given().pathParam("id", MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, Matchers.notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value.property1", Matchers.equalTo("aPropertyValue")) + .body(EXAMPLE_VARIABLE_KEY + ".value.property2", Matchers.equalTo(true)) + .body(EXAMPLE_VARIABLE_KEY + ".type", Matchers.equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT))) + .body(EXAMPLE_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, Matchers.equalTo(ExampleVariableObject.class.getName())) + .body(EXAMPLE_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, Matchers.equalTo("application/json")) + .when().get(PROCESS_INSTANCE_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + } + + @Test + public void testGetObjectVariables() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(runtimeServiceMock.getVariablesTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", Matchers.equalTo(payload)) + .body(variableKey + ".type", Matchers.equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, Matchers.equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, Matchers.equalTo(ArrayList.class.getName())) + .when().get(PROCESS_INSTANCE_VARIABLES_URL); + + // then + verify(runtimeServiceMock).getVariablesTyped(EXAMPLE_PROCESS_INSTANCE_ID, true); + } + + @Test + public void testGetObjectVariablesSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(runtimeServiceMock.getVariablesTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .queryParam("deserializeValues", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", Matchers.equalTo("a serialized value")) + .body(variableKey + ".type", Matchers.equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, Matchers.equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, Matchers.equalTo(ArrayList.class.getName())) + .when().get(PROCESS_INSTANCE_VARIABLES_URL); + + // then + verify(runtimeServiceMock).getVariablesTyped(EXAMPLE_PROCESS_INSTANCE_ID, false); + } + + @Test + public void testGetVariablesForNonExistingProcessInstance() { + when(runtimeServiceMock.getVariablesTyped(anyString(), anyBoolean())).thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", "aNonExistingProcessInstanceId") + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", Matchers.equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", Matchers.equalTo("expected exception")) + .when().get(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testGetVariablesThrowsAuthorizationException() { + String message = "expected exception"; + when(runtimeServiceMock.getVariablesTyped(anyString(), anyBoolean())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .get(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testGetSingleInstance() { + ProcessInstance mockInstance = MockProvider.createMockInstance(); + ProcessInstanceQuery sampleInstanceQuery = mock(ProcessInstanceQuery.class); + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.processInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.singleResult()).thenReturn(mockInstance); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", Matchers.equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("ended", Matchers.equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED)) + .body("definitionId", Matchers.equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("definitionKey", Matchers.equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("businessKey", Matchers.equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY)) + .body("suspended", Matchers.equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED)) + .body("tenantId", Matchers.equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .when().get(SINGLE_PROCESS_INSTANCE_URL); + } + + @Test + public void testGetNonExistingProcessInstance() { + ProcessInstanceQuery sampleInstanceQuery = mock(ProcessInstanceQuery.class); + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.processInstanceId(anyString())).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.singleResult()).thenReturn(null); + + given().pathParam("id", "aNonExistingInstanceId") + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Process instance with id aNonExistingInstanceId does not exist")) + .when().get(SINGLE_PROCESS_INSTANCE_URL); + } + + @Test + public void testDeleteProcessInstance() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false); + } + + @Test + public void testDeleteNonExistingProcessInstance() { + doThrow(new NotFoundException()).when(runtimeServiceMock).deleteProcessInstance(any(), any(), anyBoolean(), anyBoolean(), anyBoolean() ,anyBoolean()); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .when().delete(SINGLE_PROCESS_INSTANCE_URL); + } + + @Test + public void testDeleteNonExistingProcessInstanceIfExists() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParam("failIfNotExists", false) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstanceIfExists(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false); + } + + @Test + public void testDeleteProcessInstanceThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).deleteProcessInstance(any(), any(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .delete(SINGLE_PROCESS_INSTANCE_URL); + } + + @Test + public void testNoGivenDeleteReason1() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false); + } + + @Test + public void testDeleteProcessInstanceSkipCustomListeners() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipCustomListeners", true).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, true, true, false, false); + } + + @Test + public void testDeleteProcessInstanceWithCustomListeners() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipCustomListeners", false).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false); + } + + @Test + public void testDeleteProcessInstanceSkipIoMappings() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipIoMappings", true).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, true, false); + } + + @Test + public void testDeleteProcessInstanceWithoutSkipingIoMappings() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipIoMappings", false).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false); + } + + @Test + public void testDeleteProcessInstanceSkipSubprocesses() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipSubprocesses", true).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, true); + } + + @Test + public void testDeleteProcessInstanceWithoutSkipSubprocesses() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParams("skipSubprocesses", false).then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()).when().delete(SINGLE_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).deleteProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, null, false, true, false, false); + } + + @Test + public void testVariableModification() { + String variableKey = "aKey"; + int variableValue = 123; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + List deletions = new ArrayList<>(); + deletions.add("deleteKey"); + messageBodyJson.put("deletions", deletions); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + + Map expectedModifications = new HashMap<>(); + expectedModifications.put(variableKey, variableValue); + verify(runtimeServiceMock).updateVariables(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), argThat(new EqualsMap(expectedModifications)), + argThat(new EqualsList(deletions))); + } + + @Test + public void testVariableModificationWithUnparseableInteger() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot modify variables for process instance: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableShort() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot modify variables for process instance: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableLong() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot modify variables for process instance: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableDouble() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot modify variables for process instance: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithUnparseableDate() { + String variableKey = "aKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot modify variables for process instance: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot modify variables for process instance: Unsupported value type 'X'")) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationForNonExistingProcessInstance() { + doThrow(new ProcessEngineException("expected exception")).when(runtimeServiceMock).updateVariables(any(), any(), any()); + + String variableKey = "aKey"; + int variableValue = 123; + + Map messageBodyJson = new HashMap<>(); + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(messageBodyJson) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", Matchers.equalTo(RestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot modify variables for process instance " + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID + ": expected exception")) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testEmptyVariableModification() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testVariableModificationThrowsAuthorizationException() { + String variableKey = "aKey"; + int variableValue = 123; + Map messageBodyJson = new HashMap<>(); + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + String message = "excpected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).updateVariables(any(), any(), any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", Matchers.is(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .post(PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void testGetSingleVariable() { + String variableKey = "aVariableKey"; + int variableValue = 123; + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), eq(true))) + .thenReturn(Variables.integerValue(variableValue)); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", Matchers.is(123)) + .body("type", Matchers.is("Integer")) + .when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testNonExistingVariable() { + String variableKey = "aVariableKey"; + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(null); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.is("process instance variable with name " + variableKey + " does not exist")) + .when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testGetSingleVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "excpected exception"; + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", Matchers.is(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testGetSingleLocalVariableData() { + + when(runtimeServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_BYTES_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE_BYTES); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", EXAMPLE_BYTES_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .when() + .get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).getVariableTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_BYTES_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalVariableDataNonExisting() { + + when(runtimeServiceMock.getVariableTyped(anyString(), eq("nonExisting"), eq(false))).thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", "nonExisting") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.is("process instance variable with name " + "nonExisting" + " does not exist")) + .when() + .get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).getVariableTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, "nonExisting", false); + } + + @Test + public void testGetSingleLocalVariabledataNotBinary() { + + when(runtimeServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).getVariableTyped(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, EXAMPLE_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalObjectVariable() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(runtimeServiceMock.getVariableTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given().pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", Matchers.equalTo(payload)) + .body("type", Matchers.equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, Matchers.equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, Matchers.equalTo(ArrayList.class.getName())) + .when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + // then + verify(runtimeServiceMock).getVariableTyped(EXAMPLE_PROCESS_INSTANCE_ID, variableKey, true); + } + + @Test + public void testGetSingleLocalObjectVariableSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(runtimeServiceMock.getVariableTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", Matchers.equalTo("a serialized value")) + .body("type", Matchers.equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, Matchers.equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, Matchers.equalTo(ArrayList.class.getName())) + .when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + // then + verify(runtimeServiceMock).getVariableTyped(EXAMPLE_PROCESS_INSTANCE_ID, variableKey, false); + } + + @Test + public void testGetVariableForNonExistingInstance() { + String variableKey = "aVariableKey"; + + when(runtimeServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), eq(true))) + .thenThrow(new ProcessEngineException("expected exception")); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(RestException.class.getSimpleName())) + .body("message", Matchers.is("Cannot get process instance variable " + variableKey + ": expected exception")) + .when().get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsUntypedValue.matcher().value(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeString() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + String type = "String"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.stringValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeInteger() { + String variableKey = "aVariableKey"; + Integer variableValue = 123; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.integerValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableInteger() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot put process instance variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class))) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeShort() { + String variableKey = "aVariableKey"; + Short variableValue = 123; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.shortValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableShort() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot put process instance variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class))) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeLong() { + String variableKey = "aVariableKey"; + Long variableValue = 123L; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.longValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableLong() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot put process instance variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class))) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeDouble() { + String variableKey = "aVariableKey"; + Double variableValue = 123.456; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.doubleValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDouble() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot put process instance variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class))) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeBoolean() { + String variableKey = "aVariableKey"; + Boolean variableValue = true; + String type = "Boolean"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.booleanValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeDate() throws Exception { + Date now = new Date(); + + String variableKey = "aVariableKey"; + String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now); + String type = "Date"; + + Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.dateValue(expectedValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDate() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Date"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot put process instance variable aVariableKey: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class))) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "X"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot put process instance variable aVariableKey: Unsupported value type 'X'")) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "String"; + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).setVariable(anyString(), anyString(), any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleBinaryVariable() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleBinaryVariableWithValueType() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "Bytes", "text/plain") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleBinaryVariableWithNoValue() throws Exception { + byte[] bytes = new byte[0]; + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleBinaryVariableThrowsAuthorizationException() { + byte[] bytes = "someContent".getBytes(); + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).setVariable(anyString(), anyString(), any()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .multiPart("data", "unspecified", bytes) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testPutSingleSerializableVariable() throws Exception { + + ArrayList serializable = new ArrayList<>(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable))); + } + + @Test + public void testPutSingleSerializableVariableUnsupportedMediaType() throws Exception { + + ArrayList serializable = new ArrayList<>(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, "unsupported") + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(Matchers.containsString("Unrecognized content type for serialized java type: unsupported")) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + verify(runtimeServiceMock, never()).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + eq(serializable)); + } + + @Test + public void testPutSingleVariableFromSerialized() throws Exception { + String serializedValue = "{\"prop\" : \"value\"}"; + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, ValueType.OBJECT.getName(), "aDataFormat", "aRootType"); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable( + eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher() + .serializedValue(serializedValue) + .serializationFormat("aDataFormat") + .objectTypeName("aRootType"))); + } + + @Test + public void testPutSingleVariableFromInvalidSerialized() throws Exception { + String serializedValue = "{\"prop\" : \"value\"}"; + + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, "aNonExistingType", null, null); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.equalTo("Cannot put process instance variable aVariableKey: Unsupported value type 'aNonExistingType'")) + .when() + .put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableFromSerializedWithNoValue() { + String variableKey = "aVariableKey"; + Map requestJson = VariablesBuilder + .getObjectValueMap(null, ValueType.OBJECT.getName(), null, null); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(requestJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable( + eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher())); + } + + @Test + public void testPutSingleVariableWithNoValue() { + String variableKey = "aVariableKey"; + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), + argThat(EqualsNullValue.matcher())); + } + + @Test + public void testPutVariableForNonExistingInstance() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new ProcessEngineException("expected exception")) + .when(runtimeServiceMock) + .setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), any()); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(RestException.class.getSimpleName())) + .body("message", Matchers.is("Cannot put process instance variable " + variableKey + ": expected exception")) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void shouldReturnErrorOnSettingVariable() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new ProcessEngineException("foo", 123)) + .when(runtimeServiceMock) + .setVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey), any()); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(RestException.class.getSimpleName())) + .body("message", Matchers.is("Cannot put process instance variable aVariableKey: foo")) + .body("code", Matchers.is(123)) + .when().put(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testPostSingleFileVariableWithEncodingAndMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype + "; encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), Matchers.is(encoding)); + assertThat(captured.getFilename(), Matchers.is(filename)); + assertThat(captured.getMimeType(), Matchers.is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), Matchers.is(value)); + } + + @Test + public void testPostSingleFileVariableWithMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), Matchers.is(Matchers.nullValue())); + assertThat(captured.getFilename(), Matchers.is(filename)); + assertThat(captured.getMimeType(), Matchers.is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), Matchers.is(value)); + } + + @Test + public void testPostSingleFileVariableWithEncoding() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, "encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + //when the user passes an encoding, he has to provide the type, too + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleFileVariableOnlyFilename() throws Exception { + + String variableKey = "aVariableKey"; + String filename = "test.txt"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, new byte[0]) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_PROCESS_INSTANCE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(runtimeServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), Matchers.is(Matchers.nullValue())); + assertThat(captured.getFilename(), Matchers.is(filename)); + assertThat(captured.getMimeType(), Matchers.is(MediaType.APPLICATION_OCTET_STREAM)); + assertThat(captured.getValue().available(), Matchers.is(0)); + } + + @Test + public void testDeleteSingleVariable() { + String variableKey = "aVariableKey"; + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + + verify(runtimeServiceMock).removeVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey)); + } + + @Test + public void testDeleteVariableForNonExistingInstance() { + String variableKey = "aVariableKey"; + + doThrow(new ProcessEngineException("expected exception")) + .when(runtimeServiceMock).removeVariable(eq(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID), eq(variableKey)); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(RestException.class.getSimpleName())) + .body("message", Matchers.is("Cannot delete process instance variable " + variableKey + ": expected exception")) + .when().delete(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testDeleteVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(runtimeServiceMock).removeVariable(anyString(), anyString()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.is(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .delete(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + + @Test + public void testActivateInstance() { + ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto(); + dto.setSuspended(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + verify(mockUpdateSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateThrowsProcessEngineException() { + ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto(); + dto.setSuspended(false); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockUpdateSuspensionStateBuilder) + .activate(); + + given() + .pathParam("id", MockProvider.EXAMPLE_NON_EXISTENT_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(ProcessEngineException.class.getSimpleName())) + .body("message", Matchers.is(expectedMessage)) + .when() + .put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testActivateThrowsAuthorizationException() { + ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto(); + dto.setSuspended(false); + + String message = "expectedMessage"; + + doThrow(new AuthorizationException(message)) + .when(mockUpdateSuspensionStateBuilder) + .activate(); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(dto) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendInstance() { + ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto(); + dto.setSuspended(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + verify(mockUpdateSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendThrowsProcessEngineException() { + ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto(); + dto.setSuspended(true); + + String expectedMessage = "expectedMessage"; + + doThrow(new ProcessEngineException(expectedMessage)) + .when(mockUpdateSuspensionStateBuilder) + .suspend(); + + given() + .pathParam("id", MockProvider.EXAMPLE_NON_EXISTENT_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(ProcessEngineException.class.getSimpleName())) + .body("message", Matchers.is(expectedMessage)) + .when() + .put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendThrowsAuthorizationException() { + ProcessInstanceSuspensionStateDto dto = new ProcessInstanceSuspensionStateDto(); + dto.setSuspended(true); + + String message = "expectedMessage"; + + doThrow(new AuthorizationException(message)) + .when(mockUpdateSuspensionStateBuilder) + .suspend(); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(dto) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .put(SINGLE_PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockUpdateSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockUpdateSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(ProcessEngineException.class.getSimpleName())) + .body("message", Matchers.is(expectedException)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionKeyThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "expectedMessage"; + + doThrow(new AuthorizationException(message)) + .when(mockUpdateSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionKey() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockUpdateSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionKeyWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockUpdateSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(ProcessEngineException.class.getSimpleName())) + .body("message", Matchers.is(expectedException)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionKeyThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "expectedMessage"; + + doThrow(new AuthorizationException(message)) + .when(mockUpdateSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionKeyAndTenantId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockUpdateSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(mockUpdateSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionKeyWithoutTenantId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionWithoutTenantId", true); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockUpdateSuspensionStateBuilder).processDefinitionWithoutTenantId(); + verify(mockUpdateSuspensionStateBuilder).activate(); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionKeyAndTenantId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionTenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockUpdateSuspensionStateBuilder).processDefinitionTenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(mockUpdateSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionKeyWithoutTenantId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + params.put("processDefinitionWithoutTenantId", true); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockUpdateSuspensionStateBuilder).processDefinitionWithoutTenantId(); + verify(mockUpdateSuspensionStateBuilder).suspend(); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockUpdateSuspensionStateBuilder).activate(); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockUpdateSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(ProcessEngineException.class.getSimpleName())) + .body("message", Matchers.is(expectedException)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testActivateProcessInstanceByProcessDefinitionIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String message = "expectedMessage"; + + doThrow(new AuthorizationException(message)) + .when(mockUpdateSuspensionStateBuilder) + .activate(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionId() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(mockUpdateSuspensionStateBuilder).suspend(); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionIdWithException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String expectedException = "expectedException"; + doThrow(new ProcessEngineException(expectedException)) + .when(mockUpdateSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", Matchers.is(ProcessEngineException.class.getSimpleName())) + .body("message", Matchers.is(expectedException)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessInstanceByProcessDefinitionIdThrowsAuthorizationException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + String message = "expectedMessage"; + + doThrow(new AuthorizationException(message)) + .when(mockUpdateSuspensionStateBuilder) + .suspend(); + + given() + .contentType(ContentType.JSON) + .body(params) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testActivateProcessInstanceByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", false); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessInstanceByIdShouldThrowException() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendWithMultipleByParameters() { + Map params = new HashMap<>(); + params.put("suspended", true); + params.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + params.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + String message = "Only one of processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + @Test + public void testSuspendProcessInstanceByNothing() { + Map params = new HashMap<>(); + params.put("suspended", true); + + String message = "Either processDefinitionId or processDefinitionKey should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + } + + + @Test + public void testSuspendInstances() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("suspended", true); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend(); + } + + + @Test + public void testActivateInstances() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("suspended", false); + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).activate(); + } + + @Test + public void testSuspendInstancesMultipleGroupOperations() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("processInstanceQuery", query); + messageBodyJson.put("suspended", true); + + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).byProcessInstanceQuery(query.toQuery(processEngine)); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend(); + } + + + @Test + public void testSuspendProcessInstanceQuery() { + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceQuery", query); + messageBodyJson.put("suspended", true); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine)); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend(); + } + + + @Test + public void testActivateProcessInstanceQuery() { + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceQuery", query); + messageBodyJson.put("suspended", false); + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine)); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).activate(); + } + + + @Test + public void testSuspendHistoricProcessInstanceQuery() { + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("historicProcessInstanceQuery", query); + messageBodyJson.put("suspended", true); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byHistoricProcessInstanceQuery(any()); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspend(); + } + + + @Test + public void testActivateHistoricProcessInstanceQuery() { + HistoricProcessInstanceDto query = new HistoricProcessInstanceDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("historicProcessInstanceQuery", query); + messageBodyJson.put("suspended", false); + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(PROCESS_INSTANCE_SUSPENDED_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byHistoricProcessInstanceQuery(any()); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).activate(); + } + + @Test + public void testSuspendAsyncWithProcessInstances() { + Map messageBodyJson = new HashMap<>(); + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("suspended", true); + + when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity()); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync(); + } + + @Test + public void testActivateAsyncWithProcessInstances() { + Map messageBodyJson = new HashMap<>(); + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("suspended", false); + + when(mockUpdateProcessInstancesSuspensionStateBuilder.activateAsync()).thenReturn(new BatchEntity()); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).activateAsync(); + } + + @Test + public void testSuspendAsyncWithProcessInstanceQuery() { + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceQuery", query); + messageBodyJson.put("suspended", true); + + + when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity()); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine)); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync(); + } + + @Test + public void testActivateAsyncWithProcessInstanceQuery() { + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceQuery", query); + messageBodyJson.put("suspended", false); + + when(mockUpdateProcessInstancesSuspensionStateBuilder.activateAsync()).thenReturn(new BatchEntity()); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceQuery(query.toQuery(processEngine)); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).activateAsync(); + } + + @Test + public void testSuspendAsyncWithHistoricProcessInstanceQuery() { + Map messageBodyJson = new HashMap<>(); + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("suspended", true); + + when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity()); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync(); + } + + @Test + public void testActivateAsyncWithHistoricProcessInstanceQuery() { + Map messageBodyJson = new HashMap<>(); + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("suspended", false); + + when(mockUpdateProcessInstancesSuspensionStateBuilder.activateAsync()).thenReturn(new BatchEntity()); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).activateAsync(); + } + + @Test + public void testSuspendAsyncWithMultipleGroupOperations() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstanceIds", ids); + messageBodyJson.put("processInstanceQuery", query); + messageBodyJson.put("suspended", true); + + when(mockUpdateProcessInstancesSuspensionStateBuilder.suspendAsync()).thenReturn(new BatchEntity()); + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + verify(mockUpdateSuspensionStateSelectBuilder).byProcessInstanceIds(ids); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).byProcessInstanceQuery(query.toQuery(processEngine)); + verify(mockUpdateProcessInstancesSuspensionStateBuilder).suspendAsync(); + } + + + @Test + public void testSuspendAsyncWithNothing() { + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("suspended", true); + + String message = "Either processInstanceIds, processInstanceQuery or historicProcessInstanceQuery should be set to update the suspension state."; + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.is(message)) + .when() + .post(PROCESS_INSTANCE_SUSPENDED_ASYNC_URL); + + } + + @Test + public void testProcessInstanceModification() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + + Map json = new HashMap<>(); + json.put("skipCustomListeners", true); + json.put("skipIoMappings", true); + + List> instructions = new ArrayList<>(); + + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.cancellation().activityInstanceId("activityInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.cancellation().transitionInstanceId("transitionInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore() + .activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter() + .activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + instructions.add(ModificationInstructionBuilder.startTransition() + .transitionId("transitionId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson()); + + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID)); + + InOrder inOrder = inOrder(mockModificationBuilder); + inOrder.verify(mockModificationBuilder).cancelAllForActivity("activityId"); + inOrder.verify(mockModificationBuilder).cancelActivityInstance("activityInstanceId"); + inOrder.verify(mockModificationBuilder).cancelTransitionInstance("transitionInstanceId"); + inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId"); + inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId", "ancestorActivityInstanceId"); + inOrder.verify(mockModificationBuilder).startAfterActivity("activityId"); + inOrder.verify(mockModificationBuilder).startAfterActivity("activityId", "ancestorActivityInstanceId"); + inOrder.verify(mockModificationBuilder).startTransition("transitionId"); + inOrder.verify(mockModificationBuilder).startTransition("transitionId", "ancestorActivityInstanceId"); + + inOrder.verify(mockModificationBuilder).execute(true, true); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testProcessInstanceModificationWithVariables() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + + Map json = new HashMap<>(); + + List> instructions = new ArrayList<>(); + + instructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", "value", "String", false) + .variable("varLocal", "valueLocal", "String", true) + .getVariables()) + .getJson()); + instructions.add( + ModificationInstructionBuilder.startAfter() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", 52, "Integer", false) + .variable("varLocal", 74, "Integer", true) + .getVariables()) + .getJson()); + + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID)); + + InOrder inOrder = inOrder(mockModificationBuilder); + inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId"); + + verify(mockModificationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.stringValue("valueLocal"))); + verify(mockModificationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.stringValue("value"))); + + inOrder.verify(mockModificationBuilder).startAfterActivity("activityId"); + + verify(mockModificationBuilder).setVariable(eq("var"), argThat(EqualsPrimitiveValue.integerValue(52))); + verify(mockModificationBuilder).setVariableLocal(eq("varLocal"), argThat(EqualsPrimitiveValue.integerValue(74))); + + inOrder.verify(mockModificationBuilder).execute(false, false); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testInvalidModification() { + Map json = new HashMap<>(); + + // start before: missing activity id + List> instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startBefore().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("'activityId' must be set")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + // start after: missing ancestor activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startAfter().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("'activityId' must be set")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + // start transition: missing ancestor activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startTransition().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("'transitionId' must be set")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + // cancel: missing activity id and activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.cancellation().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("For instruction type 'cancel': exactly one, " + + "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + // cancel: both, activity id and activity instance id, set + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("anActivityId") + .activityInstanceId("anActivityInstanceId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("For instruction type 'cancel': exactly one, " + + "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + } + + @Test + public void testModifyProcessInstanceThrowsAuthorizationException() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(mockModificationBuilder).execute(anyBoolean(), anyBoolean()); + + Map json = new HashMap<>(); + + List> instructions = new ArrayList<>(); + + instructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", "value", "String", false) + .variable("varLocal", "valueLocal", "String", true) + .getVariables()) + .getJson()); + instructions.add( + ModificationInstructionBuilder.startAfter() + .activityId("activityId") + .variables(VariablesBuilder.create() + .variable("var", 52, "Integer", false) + .variable("varLocal", 74, "Integer", true) + .getVariables()) + .getJson()); + + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + } + + @Test + public void testSyncProcessInstanceModificationWithAnnotation() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + + Map json = new HashMap<>(); + + List> instructions = new ArrayList<>(); + instructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .getJson()); + json.put("instructions", instructions); + json.put("annotation", "anAnnotation"); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID)); + + InOrder inOrder = inOrder(mockModificationBuilder); + inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId"); + inOrder.verify(mockModificationBuilder).setAnnotation("anAnnotation"); + + + inOrder.verify(mockModificationBuilder).execute(false, false); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testSetRetriesByProcessAsync() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstances", ids); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + + Response response = given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceQuery(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncWithDueDate() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstances", ids); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + Date newDueDate = new Date(1675752840000L); + messageBodyJson.put("dueDate", newDueDate); + + Response response = + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceQuery(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).dueDate(eq(newDueDate)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncWithNullDueDate() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstances", ids); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + messageBodyJson.put("dueDate", null); + + Response response = + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceQuery(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).dueDate(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncWithQueryAndDueDate() { + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + messageBodyJson.put("processInstanceQuery", query); + Date newDueDate = new Date(1675752840000L); + messageBodyJson.put("dueDate", newDueDate); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(SET_JOB_RETRIES_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceQuery(any(ProcessInstanceQuery.class)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).dueDate(newDueDate); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncWithQuery() { + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(new ProcessInstanceQueryImpl()); + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + ProcessInstanceQueryDto query = new ProcessInstanceQueryDto(); + messageBodyJson.put("processInstanceQuery", query); + + Response response = + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceQuery(any(ProcessInstanceQuery.class)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessWithBadRequestQuery() { + doThrow(new BadUserRequestException("job ids are empty")) + .when(mockSetJobRetriesByProcessAsyncBuilder).executeAsync(); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(SET_JOB_RETRIES_ASYNC_URL); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceQuery(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessWithoutRetries() { + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put("processInstances", null); + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(SET_JOB_RETRIES_ASYNC_URL); + } + + @Test + public void testSetRetriesByProcessWithNegativeRetries() { + doThrow(new BadUserRequestException("retries are negative")) + .when(mockManagementService).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES)); + + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + messageBodyJson.put("processInstanceQuery", query); + + given() + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_URL); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES)); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithQuery() { + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery); + List historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances(); + when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances); + + Map body = new HashMap<>(); + body.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + body.put("historicProcessInstanceQuery", new HistoricProcessInstanceQueryDto()); + + Response response = given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).historicProcessInstanceQuery(any()); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithQueryAndDueDate() { + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery); + List historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances(); + when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances); + + Map body = new HashMap<>(); + body.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + body.put("historicProcessInstanceQueryDto", new HistoricProcessInstanceQueryDto()); + Date newDueDate = new Date(1675752840000L); + body.put("dueDate", newDueDate); + + Response response = + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).historicProcessInstanceQuery(any()); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).dueDate(newDueDate); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithQueryAndNullDueDate() { + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery); + List historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances(); + when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances); + + Map body = new HashMap<>(); + body.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + body.put("historicProcessInstanceQuery", new HistoricProcessInstanceQueryDto()); + body.put("dueDate",null); + + Response response = + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verifyBatchJson(response.asString()); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).historicProcessInstanceQuery(any()); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).dueDate(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithProcessInstanceIds() { + Map messageBodyJson = new HashMap<>(); + messageBodyJson.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + messageBodyJson.put("processInstances", Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).historicProcessInstanceQuery(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithProcessInstanceIdsAndDueDate() { + Map body = new HashMap<>(); + body.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + body.put("processInstances", Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + Date newDueDate = new Date(1675752840000L); + body.put("dueDate", newDueDate); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).historicProcessInstanceQuery(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).dueDate(newDueDate); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithQueryAndProcessInstanceIds() { + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery); + List historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances(); + when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances); + + Map body = new HashMap<>(); + body.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + body.put("processInstances", Arrays.asList(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID)); + body.put("historicProcessInstanceQuery", new HistoricProcessInstanceQueryDto()); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(Arrays.asList(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).historicProcessInstanceQuery(any()); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithBadRequestQuery() { + doThrow(new BadUserRequestException("jobIds is empty")) + .when(mockSetJobRetriesByProcessAsyncBuilder).executeAsync(); + + Map body = new HashMap<>(); + body.put(RETRIES, MockProvider.EXAMPLE_JOB_RETRIES); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_JOB_RETRIES)); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).processInstanceIds(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).historicProcessInstanceQuery(null); + verify(mockSetJobRetriesByProcessAsyncBuilder, times(1)).executeAsync(); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testSetRetriesByProcessAsyncHistoricQueryBasedWithNegativeRetries() { + doThrow(new BadUserRequestException("retries are negative")) + .when(mockManagementService).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES)); + + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedHistoricProcessInstanceQuery); + List historicProcessInstances = MockProvider.createMockRunningHistoricProcessInstances(); + when(mockedHistoricProcessInstanceQuery.list()).thenReturn(historicProcessInstances); + + Map body = new HashMap<>(); + body.put(RETRIES, MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES); + body.put("historicProcessInstanceQuery", new HistoricProcessInstanceQueryDto()); + + given() + .contentType(ContentType.JSON).body(body) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(SET_JOB_RETRIES_ASYNC_HIST_QUERY_URL); + + verify(mockManagementService, times(1)).setJobRetriesByProcessAsync(eq(MockProvider.EXAMPLE_NEGATIVE_JOB_RETRIES)); + verifyNoMoreInteractions(mockSetJobRetriesByProcessAsyncBuilder); + } + + @Test + public void testProcessInstanceModificationAsync() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + Batch batchMock = createMockBatch(); + when(mockModificationBuilder.executeAsync(anyBoolean(), anyBoolean())).thenReturn(batchMock); + + Map json = new HashMap<>(); + json.put("skipCustomListeners", true); + json.put("skipIoMappings", true); + + List> instructions = new ArrayList<>(); + + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.cancellation().activityInstanceId("activityInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.cancellation().transitionInstanceId("transitionInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startBefore() + .activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + instructions.add(ModificationInstructionBuilder.startAfter() + .activityId("activityId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson()); + instructions.add(ModificationInstructionBuilder.startTransition().transitionId("transitionId").getJson()); + instructions.add(ModificationInstructionBuilder.startTransition() + .transitionId("transitionId").ancestorActivityInstanceId("ancestorActivityInstanceId").getJson()); + + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID)); + + InOrder inOrder = inOrder(mockModificationBuilder); + inOrder.verify(mockModificationBuilder).cancelAllForActivity("activityId"); + inOrder.verify(mockModificationBuilder).cancelActivityInstance("activityInstanceId"); + inOrder.verify(mockModificationBuilder).cancelTransitionInstance("transitionInstanceId"); + inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId"); + inOrder.verify(mockModificationBuilder).startBeforeActivity("activityId", "ancestorActivityInstanceId"); + inOrder.verify(mockModificationBuilder).startAfterActivity("activityId"); + inOrder.verify(mockModificationBuilder).startAfterActivity("activityId", "ancestorActivityInstanceId"); + inOrder.verify(mockModificationBuilder).startTransition("transitionId"); + inOrder.verify(mockModificationBuilder).startTransition("transitionId", "ancestorActivityInstanceId"); + + inOrder.verify(mockModificationBuilder).executeAsync(true, true); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testInvalidModificationAsync() { + Map json = new HashMap<>(); + + // start before: missing activity id + List> instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startBefore().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("'activityId' must be set")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + // start after: missing ancestor activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startAfter().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("'activityId' must be set")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + // start transition: missing ancestor activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.startTransition().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("'transitionId' must be set")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + // cancel: missing activity id and activity instance id + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.cancellation().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("For instruction type 'cancel': exactly one, " + + "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + // cancel: both, activity id and activity instance id, set + instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("anActivityId") + .activityInstanceId("anActivityInstanceId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", Matchers.is(InvalidRequestException.class.getSimpleName())) + .body("message", Matchers.containsString("For instruction type 'cancel': exactly one, " + + "'activityId', 'activityInstanceId', or 'transitionInstanceId', is required")) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + } + + @Test + public void testModifyProcessInstanceAsyncThrowsAuthorizationException() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(mockModificationBuilder).executeAsync(anyBoolean(), anyBoolean()); + + Map json = new HashMap<>(); + + List> instructions = new ArrayList<>(); + + instructions.add( + ModificationInstructionBuilder.startBefore() + .activityId("activityId") + .getJson()); + instructions.add( + ModificationInstructionBuilder.startAfter() + .activityId("activityId") + .getJson()); + + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", Matchers.equalTo(AuthorizationException.class.getSimpleName())) + .body("message", Matchers.equalTo(message)) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + } + + + @Test + public void testAsyncProcessInstanceModificationWithAnnotation() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + Batch batchMock = createMockBatch(); + when(mockModificationBuilder.executeAsync(anyBoolean(), anyBoolean())).thenReturn(batchMock); + + Map json = new HashMap<>(); + + List> instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + + json.put("instructions", instructions); + json.put("annotation", "anAnnotation"); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + verify(runtimeServiceMock).createProcessInstanceModification(eq(EXAMPLE_PROCESS_INSTANCE_ID)); + + InOrder inOrder = inOrder(mockModificationBuilder); + inOrder.verify(mockModificationBuilder).cancelAllForActivity("activityId"); + inOrder.verify(mockModificationBuilder).setAnnotation("anAnnotation"); + + inOrder.verify(mockModificationBuilder).executeAsync(false, false); + + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testSyncProcessInstanceModificationCancellationSource() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + + Map json = new HashMap<>(); + List> instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_URL); + + verify(mockModificationBuilder).cancellationSourceExternal(true); + } + + @Test + public void testAsyncProcessInstanceModificationCancellationSource() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = setUpMockModificationBuilder(); + when(runtimeServiceMock.createProcessInstanceModification(anyString())).thenReturn(mockModificationBuilder); + Batch batchMock = createMockBatch(); + when(mockModificationBuilder.executeAsync(anyBoolean(), anyBoolean())).thenReturn(batchMock); + + Map json = new HashMap<>(); + List> instructions = new ArrayList<>(); + instructions.add(ModificationInstructionBuilder.cancellation().activityId("activityId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_MODIFICATION_ASYNC_URL); + + verify(mockModificationBuilder).cancellationSourceExternal(true); + } + + @Test + public void shouldSetVariablesAsync() { + // given + Batch batchMock = createMockBatch(); + when(runtimeServiceMock.setVariablesAsync(any(), any(), any(), any())) + .thenReturn(batchMock); + + SetVariablesAsyncDto body = new SetVariablesAsyncDto(); + + VariableValueDto variableValueDto = new VariableValueDto(); + variableValueDto.setValue("bar"); + + body.setVariables(Collections.singletonMap("foo", variableValueDto)); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + + // then + ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); + verify(runtimeServiceMock).setVariablesAsync( + eq(null), + eq(null), + eq(null), + captor.capture() + ); + + Assertions.assertThat(captor.getValue().get("foo")).isEqualTo("bar"); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldThrowExceptionWhenSetVariablesAsync_UnsupportedType() { + // given + Batch batchMock = createMockBatch(); + when(runtimeServiceMock.setVariablesAsync(any(), any(), any(), any())) + .thenReturn(batchMock); + + SetVariablesAsyncDto body = new SetVariablesAsyncDto(); + + VariableValueDto variableValueDto = new VariableValueDto(); + variableValueDto.setValue("bar"); + variableValueDto.setType("unknown"); + + body.setVariables(Collections.singletonMap("foo", variableValueDto)); + + // when + then + given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set variables: Unsupported value type 'unknown'")) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + } + + /** + * Thrown when java serialization format is prohibited and java serialized variable is set + * or null value is given. + */ + @Test + public void shouldTransformProcessEngineExceptionToInvalidRequestException() { + // given + doThrow(new ProcessEngineException("message")) + .when(runtimeServiceMock).setVariablesAsync(any(), any(), any(), any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("message")) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + } + + @Test + public void shouldThrowExceptionWhenSetVariablesAsync_AuthorizationException() { + // given + doThrow(new AuthorizationException("message")) + .when(runtimeServiceMock).setVariablesAsync(any(), any(), any(), any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(Matchers.containsString("{\"type\":\"AuthorizationException\"")) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + } + + @Test + public void shouldThrowExceptionWhenSetVariablesAsync_NullValueException() { + // given + doThrow(new NullValueException("message")) + .when(runtimeServiceMock).setVariablesAsync(any(), any(), any(), any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("message")) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + } + + @Test + public void shouldThrowExceptionWhenSetVariablesAsync_BadUserRequestException() { + // given + doThrow(new BadUserRequestException("message")) + .when(runtimeServiceMock).setVariablesAsync(any(), any(), any(), any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo("message")) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + } + + @Test + public void shouldSetVariablesAsync_RuntimeQuery() { + // given + Batch batchMock = createMockBatch(); + when(runtimeServiceMock.setVariablesAsync(any(), any(), any(), any())) + .thenReturn(batchMock); + + ProcessInstanceQuery mockedProcessInstanceQuery = mock(ProcessInstanceQuery.class); + when(runtimeServiceMock.createProcessInstanceQuery()) + .thenReturn(mockedProcessInstanceQuery); + + SetVariablesAsyncDto body = new SetVariablesAsyncDto(); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + processInstanceQueryDto.setProcessDefinitionId("foo"); + body.setProcessInstanceQuery(processInstanceQueryDto); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + + // then + + verify(mockedProcessInstanceQuery) + .processDefinitionId("foo"); + + verify(runtimeServiceMock).setVariablesAsync( + eq(null), + eq(mockedProcessInstanceQuery), + eq(null), + eq(null) + ); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldSetVariablesAsync_HistoryQuery() { + // given + Batch batchMock = createMockBatch(); + when(runtimeServiceMock.setVariablesAsync(any(), any(), any(), any())) + .thenReturn(batchMock); + + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = + mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()) + .thenReturn(mockedHistoricProcessInstanceQuery); + + SetVariablesAsyncDto body = new SetVariablesAsyncDto(); + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = + new HistoricProcessInstanceQueryDto(); + historicProcessInstanceQueryDto.setProcessDefinitionId("foo"); + body.setHistoricProcessInstanceQuery(historicProcessInstanceQueryDto); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + + // then + verify(mockedHistoricProcessInstanceQuery) + .processDefinitionId("foo"); + + verify(runtimeServiceMock).setVariablesAsync( + eq(null), + eq(null), + eq(mockedHistoricProcessInstanceQuery), + eq(null) + ); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldSetVariablesAsync_ByIds() { + // given + Batch batchMock = createMockBatch(); + when(runtimeServiceMock.setVariablesAsync(any(), any(), any(), any())) + .thenReturn(batchMock); + + SetVariablesAsyncDto body = new SetVariablesAsyncDto(); + + List processInstanceIds = Arrays.asList("foo", "bar"); + body.setProcessInstanceIds(processInstanceIds); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_SET_VARIABLES_ASYNC_URL); + + // then + verify(runtimeServiceMock).setVariablesAsync( + eq(processInstanceIds), + eq(null), + eq(null), + eq(null) + ); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldCorrelateMessageAsync() { + // given + Batch batchMock = createMockBatch(); + MessageCorrelationAsyncBuilder builderMock = mock(MessageCorrelationAsyncBuilder.class, RETURNS_SELF); + when(builderMock.correlateAllAsync()).thenReturn(batchMock); + when(runtimeServiceMock.createMessageCorrelationAsync(any())).thenReturn(builderMock); + + CorrelationMessageAsyncDto body = new CorrelationMessageAsyncDto(); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + + // then + verify(runtimeServiceMock).createMessageCorrelationAsync(null); + verify(builderMock).correlateAllAsync(); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldNotTransformProcessEngineExceptionToInvalidRequestExceptionWhenCorrelateMessageAsync() { + // given + doThrow(new ProcessEngineException("message")).when(runtimeServiceMock).createMessageCorrelationAsync(any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("message")) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + } + + @Test + public void shouldThrowExceptionWhenCorrelateMessageAsync_AuthorizationException() { + // given + doThrow(new AuthorizationException("message")).when(runtimeServiceMock).createMessageCorrelationAsync(any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(Matchers.containsString("{\"type\":\"AuthorizationException\"")) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + } + + @Test + public void shouldThrowExceptionWhenCorrelateMessageAsync_NullValueException() { + // given + doThrow(new NullValueException("message")).when(runtimeServiceMock).createMessageCorrelationAsync(any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("message")) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + } + + @Test + public void shouldThrowExceptionWhenCorrelateMessageAsync_BadUserRequestException() { + // given + doThrow(new BadUserRequestException("message")).when(runtimeServiceMock).createMessageCorrelationAsync(any()); + + // when + then + given() + .contentType(ContentType.JSON) + .body("{}") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo("message")) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + } + + @Test + public void shouldCorrelateMessageAsync_RuntimeQuery() { + // given + Batch batchMock = createMockBatch(); + MessageCorrelationAsyncBuilder builderMock = mock(MessageCorrelationAsyncBuilder.class, RETURNS_SELF); + when(builderMock.correlateAllAsync()).thenReturn(batchMock); + when(runtimeServiceMock.createMessageCorrelationAsync(any())).thenReturn(builderMock); + + ProcessInstanceQuery mockedProcessInstanceQuery = mock(ProcessInstanceQuery.class); + when(runtimeServiceMock.createProcessInstanceQuery()).thenReturn(mockedProcessInstanceQuery); + + CorrelationMessageAsyncDto body = new CorrelationMessageAsyncDto(); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + processInstanceQueryDto.setProcessDefinitionId("foo"); + body.setProcessInstanceQuery(processInstanceQueryDto); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + + // then + + verify(mockedProcessInstanceQuery) + .processDefinitionId("foo"); + + verify(runtimeServiceMock).createMessageCorrelationAsync(null); + verify(builderMock).processInstanceQuery(mockedProcessInstanceQuery); + verify(builderMock).correlateAllAsync(); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldCorrelateMessageAsync_HistoryQuery() { + // given + Batch batchMock = createMockBatch(); + MessageCorrelationAsyncBuilder builderMock = mock(MessageCorrelationAsyncBuilder.class, RETURNS_SELF); + when(builderMock.correlateAllAsync()).thenReturn(batchMock); + when(runtimeServiceMock.createMessageCorrelationAsync(any())).thenReturn(builderMock); + + HistoricProcessInstanceQuery mockedHistoricProcessInstanceQuery = + mock(HistoricProcessInstanceQuery.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()) + .thenReturn(mockedHistoricProcessInstanceQuery); + + CorrelationMessageAsyncDto body = new CorrelationMessageAsyncDto(); + + HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto = + new HistoricProcessInstanceQueryDto(); + historicProcessInstanceQueryDto.setProcessDefinitionId("foo"); + body.setHistoricProcessInstanceQuery(historicProcessInstanceQueryDto); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + + // then + verify(mockedHistoricProcessInstanceQuery) + .processDefinitionId("foo"); + + verify(runtimeServiceMock).createMessageCorrelationAsync(null); + verify(builderMock).historicProcessInstanceQuery(mockedHistoricProcessInstanceQuery); + verify(builderMock).correlateAllAsync(); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldCorrelateMessageAsync_ByIds() { + // given + Batch batchMock = createMockBatch(); + MessageCorrelationAsyncBuilder builderMock = mock(MessageCorrelationAsyncBuilder.class, RETURNS_SELF); + when(builderMock.correlateAllAsync()).thenReturn(batchMock); + when(runtimeServiceMock.createMessageCorrelationAsync(any())).thenReturn(builderMock); + + CorrelationMessageAsyncDto body = new CorrelationMessageAsyncDto(); + + List processInstanceIds = Arrays.asList("foo", "bar"); + body.setProcessInstanceIds(processInstanceIds); + + // when + Response response = given() + .contentType(ContentType.JSON) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_CORRELATE_MESSAGE_ASYNC_URL); + + // then + verify(runtimeServiceMock).createMessageCorrelationAsync(null); + verify(builderMock).processInstanceIds(processInstanceIds); + verify(builderMock).correlateAllAsync(); + + verifyBatchJson(response.asString()); + } + + @SuppressWarnings("unchecked") + protected ProcessInstanceModificationInstantiationBuilder setUpMockModificationBuilder() { + ProcessInstanceModificationInstantiationBuilder mockModificationBuilder = + mock(ProcessInstanceModificationInstantiationBuilder.class); + + when(mockModificationBuilder.cancelActivityInstance(anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.cancelAllForActivity(anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.cancellationSourceExternal(anyBoolean())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.startAfterActivity(anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.startAfterActivity(anyString(), anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.startBeforeActivity(anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.startBeforeActivity(anyString(), anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.startTransition(anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.startTransition(anyString(), anyString())).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.setVariables(any(Map.class))).thenReturn(mockModificationBuilder); + when(mockModificationBuilder.setVariablesLocal(any(Map.class))).thenReturn(mockModificationBuilder); + + return mockModificationBuilder; + + } + + protected void verifyBatchJson(String batchJson) { + BatchDto batch = JsonPathUtil.from(batchJson).getObject("", BatchDto.class); + assertNotNull("The returned batch should not be null.", batch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId()); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void verifyTaskComments(List mockTaskComments, Response response) { + List list = response.as(List.class); + assertEquals(1, list.size()); + + LinkedHashMap resourceHashMap = (LinkedHashMap) list.get(0); + + String returnedId = resourceHashMap.get("id"); + String returnedUserId = resourceHashMap.get("userId"); + String returnedTaskId = resourceHashMap.get("taskId"); + Date returnedTime = DateTimeUtil.parseDate(resourceHashMap.get("time")); + String returnedFullMessage = resourceHashMap.get("message"); + + Comment mockComment = mockTaskComments.get(0); + + assertEquals(mockComment.getId(), returnedId); + assertEquals(mockComment.getTaskId(), returnedTaskId); + assertEquals(mockComment.getUserId(), returnedUserId); + assertEquals(mockComment.getTime(), returnedTime); + assertEquals(mockComment.getFullMessage(), returnedFullMessage); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ee047680a00238700e64e688da5f1d65b06e2494 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/ProcessInstanceRestServiceQueryTest.java @@ -0,0 +1,1618 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.anySet; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.impl.ProcessInstanceQueryImpl; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.dto.runtime.ProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class ProcessInstanceRestServiceQueryTest extends + AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_INSTANCE_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/process-instance"; + protected static final String PROCESS_INSTANCE_COUNT_QUERY_URL = PROCESS_INSTANCE_QUERY_URL + "/count"; + private static final String TEST_VAR_NAME = "varName"; + private static final String TEST_VAR_VALUE = "varValue"; + protected ProcessInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockInstanceQuery(createMockInstanceList()); + } + + private ProcessInstanceQuery setUpMockInstanceQuery(List mockedInstances) { + ProcessInstanceQuery sampleInstanceQuery = mock(ProcessInstanceQuery.class); + when(sampleInstanceQuery.list()).thenReturn(mockedInstances); + when(sampleInstanceQuery.count()).thenReturn((long) mockedInstances.size()); + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(sampleInstanceQuery); + return sampleInstanceQuery; + } + + private List createMockInstanceList() { + List mocks = new ArrayList(); + + mocks.add(MockProvider.createMockInstance()); + return mocks; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given().queryParam("processDefinitionKey", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + } + + @Test + public void testInvalidVariableRequests() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_" + invalidComparator + "_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid variable comparator specified: " + invalidComparator)) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + // invalid format + queryValue = "invalidFormattedVariableQuery"; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("variable query parameter has to have format KEY_OPERATOR_VALUE")) + .when().get(PROCESS_INSTANCE_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "definitionId") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + } + + @Test + public void testInstanceRetrieval() { + String queryKey = "key"; + Response response = given().queryParam("processDefinitionKey", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).processDefinitionKey(queryKey); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one process definition returned.", 1, instances.size()); + Assert.assertNotNull("There should be one process definition returned", instances.get(0)); + + String returnedInstanceId = from(content).getString("[0].id"); + Boolean returnedIsEnded = from(content).getBoolean("[0].ended"); + String returnedDefinitionId = from(content).getString("[0].definitionId"); + String returnedBusinessKey = from(content).getString("[0].businessKey"); + Boolean returnedIsSuspended = from(content).getBoolean("[0].suspended"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED, returnedIsEnded); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY, returnedBusinessKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED, returnedIsSuspended); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testIncompleteProcessInstance() { + setUpMockInstanceQuery(createIncompleteMockInstances()); + Response response = expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + String content = response.asString(); + String returnedBusinessKey = from(content).getString("[0].businessKey"); + Assert.assertNull("Should be null, as it is also null in the original process instance on the server.", + returnedBusinessKey); + } + + private List createIncompleteMockInstances() { + List mocks = new ArrayList(); + ProcessInstance mockInstance = mock(ProcessInstance.class); + when(mockInstance.getId()).thenReturn(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + mocks.add(mockInstance); + return mocks; + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testAdditionalParametersExcludingVariables() { + Map queryParameters = getCompleteQueryParameters(); + + given().queryParams(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).caseInstanceId(queryParameters.get("caseInstanceId")); + verify(mockedQuery).processInstanceBusinessKey(queryParameters.get("businessKey")); + verify(mockedQuery).processInstanceBusinessKeyLike(queryParameters.get("businessKeyLike")); + verify(mockedQuery).processDefinitionKey(queryParameters.get("processDefinitionKey")); + verify(mockedQuery).processDefinitionId(queryParameters.get("processDefinitionId")); + verify(mockedQuery).deploymentId(queryParameters.get("deploymentId")); + verify(mockedQuery).superProcessInstanceId(queryParameters.get("superProcessInstance")); + verify(mockedQuery).subProcessInstanceId(queryParameters.get("subProcessInstance")); + verify(mockedQuery).superCaseInstanceId(queryParameters.get("superCaseInstance")); + verify(mockedQuery).subCaseInstanceId(queryParameters.get("subCaseInstance")); + verify(mockedQuery).suspended(); + verify(mockedQuery).active(); + verify(mockedQuery).incidentId(queryParameters.get("incidentId")); + verify(mockedQuery).incidentMessage(queryParameters.get("incidentMessage")); + verify(mockedQuery).incidentMessageLike(queryParameters.get("incidentMessageLike")); + verify(mockedQuery).incidentType(queryParameters.get("incidentType")); + verify(mockedQuery).rootProcessInstanceId(queryParameters.get("rootProcessInstanceId")); + verify(mockedQuery).list(); + } + + private Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("businessKey", "aBusinessKey"); + parameters.put("businessKeyLike", "aKeyLike"); + parameters.put("processDefinitionKey", "aProcDefKey"); + parameters.put("processDefinitionId", "aProcDefId"); + parameters.put("deploymentId", "deploymentId"); + parameters.put("superProcessInstance", "aSuperProcInstId"); + parameters.put("subProcessInstance", "aSubProcInstId"); + parameters.put("superCaseInstance", "aSuperCaseInstId"); + parameters.put("subCaseInstance", "aSubCaseInstId"); + parameters.put("suspended", "true"); + parameters.put("active", "true"); + parameters.put("incidentId", "incId"); + parameters.put("incidentMessage", "incMessage"); + parameters.put("incidentMessageLike", "incMessageLike"); + parameters.put("incidentType", "incType"); + parameters.put("caseInstanceId", "aCaseInstanceId"); + parameters.put("rootProcessInstanceId", "aRootProcessInstanceId"); + + return parameters; + } + + @Test + public void testVariableValueEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThan(variableName, variableValue); + } + + @Test + public void testVariableValueLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lteq_" + variableValue; + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("variables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThan("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLikeAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + @Test + public void testVariableValueNotEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + + @Test + public void testVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName1, variableValue1); + verify(mockedQuery).variableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).variableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testDateVariableParameter() { + String variableName = "varName"; + String variableValue = withTimezone("2014-06-16T10:00:00"); + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + Date date = DateTimeUtil.parseDate(variableValue); + + verify(mockedQuery).variableValueEquals(variableName, date); + } + + @Test + public void testDateVariableParameterAsPost() { + String variableName = "varName"; + String variableValue = withTimezone("2014-06-16T10:00:00"); + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + Date date = DateTimeUtil.parseDate(variableValue); + + verify(mockedQuery).variableValueEquals(variableName, date); + } + + @Test + public void testCompletePostParameters() { + Map queryParameters = getCompleteQueryParameters(); + + given().contentType(POST_JSON_CONTENT_TYPE).body(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).caseInstanceId(queryParameters.get("caseInstanceId")); + verify(mockedQuery).processInstanceBusinessKey(queryParameters.get("businessKey")); + verify(mockedQuery).processInstanceBusinessKeyLike(queryParameters.get("businessKeyLike")); + verify(mockedQuery).processDefinitionKey(queryParameters.get("processDefinitionKey")); + verify(mockedQuery).processDefinitionId(queryParameters.get("processDefinitionId")); + verify(mockedQuery).deploymentId(queryParameters.get("deploymentId")); + verify(mockedQuery).superProcessInstanceId(queryParameters.get("superProcessInstance")); + verify(mockedQuery).subProcessInstanceId(queryParameters.get("subProcessInstance")); + verify(mockedQuery).superCaseInstanceId(queryParameters.get("superCaseInstance")); + verify(mockedQuery).subCaseInstanceId(queryParameters.get("subCaseInstance")); + verify(mockedQuery).suspended(); + verify(mockedQuery).active(); + verify(mockedQuery).incidentId(queryParameters.get("incidentId")); + verify(mockedQuery).incidentMessage(queryParameters.get("incidentMessage")); + verify(mockedQuery).incidentMessageLike(queryParameters.get("incidentMessageLike")); + verify(mockedQuery).incidentType(queryParameters.get("incidentType")); + verify(mockedQuery).rootProcessInstanceId(queryParameters.get("rootProcessInstanceId")); + verify(mockedQuery).list(); + } + + @Test + public void testGetProcessInstancesForRootProcessInstanceId() { + Response response = given().queryParam("rootProcessInstanceId", MockProvider.EXAMPLE_ROOT_PROCESS_INSTANCE_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertThat(instances).size().isGreaterThan(0); + + String returnedProcessInstanceId = from(content).getString("[0].id"); + String returnedProcessDefinitionId = from(content).getString("[0].definitionId"); + String returnedProcessInstanceBusinessKey = from(content).getString("[0].businessKey"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + Boolean returnedIsEnded = from(content).getBoolean("[0].ended"); + Boolean returnedIsSuspended = from(content).getBoolean("[0].suspended"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY, returnedProcessInstanceBusinessKey); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_ENDED, returnedIsEnded); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED, returnedIsSuspended); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockInstanceQuery(createMockProcessInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertThat(instances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdParameter() { + mockedQuery = setUpMockInstanceQuery(Arrays.asList(MockProvider.createMockInstance(null))); + + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockInstanceQuery(createMockProcessInstancesTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdPostParameter() { + mockedQuery = setUpMockInstanceQuery(Arrays.asList(MockProvider.createMockInstance(null))); + + Map queryParameters = new HashMap(); + queryParameters.put("withoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + private List createMockProcessInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockInstance(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + + @Test + public void testActivityIdListParameter() { + given() + .queryParam("activityIdIn", MockProvider.EXAMPLE_ACTIVITY_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).activityIdIn(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID); + verify(mockedQuery).list(); + } + + @Test + public void testActivityIdListPostParameter() { + Map queryParameters = new HashMap(); + queryParameters.put("activityIdIn", MockProvider.EXAMPLE_ACTIVITY_ID_LIST.split(",")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).activityIdIn(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID); + verify(mockedQuery).list(); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("businessKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByBusinessKey(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("definitionKey").desc() + .orderBy("definitionId").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(PROCESS_INSTANCE_QUERY_URL); + + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given().queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given().queryParam("firstResult", firstResult) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(PROCESS_INSTANCE_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(PROCESS_INSTANCE_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testInstanceRetrievalByList() { + List mockProcessInstanceList = new ArrayList(); + + mockProcessInstanceList.add(MockProvider.createMockInstance()); + mockProcessInstanceList.add(MockProvider.createAnotherMockInstance()); + + ProcessInstanceQuery instanceQuery = mock(ProcessInstanceQuery.class); + + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(instanceQuery); + when(instanceQuery.list()).thenReturn(mockProcessInstanceList); + + Response response = given() + .queryParam("processInstanceIds", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(instanceQuery); + Set expectedSet = MockProvider.createMockSetFromList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST); + + inOrder.verify(instanceQuery).processInstanceIds(expectedSet); + inOrder.verify(instanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be two process definitions returned.", 2, instances.size()); + + String returnedInstanceId1 = from(content).getString("[0].id"); + String returnedInstanceId2 = from(content).getString("[1].id"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId1); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId2); + } + + @Test + public void testInstanceRetrievalByListAsPost() { + List mockProcessInstanceList = new ArrayList(); + + mockProcessInstanceList.add(MockProvider.createMockInstance()); + mockProcessInstanceList.add(MockProvider.createAnotherMockInstance()); + + ProcessInstanceQuery instanceQuery = mock(ProcessInstanceQuery.class); + + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(instanceQuery); + when(instanceQuery.list()).thenReturn(mockProcessInstanceList); + + Map> params = new HashMap>(); + Set processInstanceIds = MockProvider.createMockSetFromList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST); + params.put("processInstanceIds", processInstanceIds); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(instanceQuery); + + inOrder.verify(instanceQuery).processInstanceIds(processInstanceIds); + inOrder.verify(instanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be two process definitions returned.", 2, instances.size()); + + String returnedInstanceId1 = from(content).getString("[0].id"); + String returnedInstanceId2 = from(content).getString("[1].id"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId1); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId2); + } + + @Test + public void testInstanceRetrievalByListWithDuplicate() { + List mockProcessInstanceList = new ArrayList(); + + mockProcessInstanceList.add(MockProvider.createMockInstance()); + mockProcessInstanceList.add(MockProvider.createAnotherMockInstance()); + + ProcessInstanceQuery instanceQuery = mock(ProcessInstanceQuery.class); + + when(instanceQuery.list()).thenReturn(mockProcessInstanceList); + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(instanceQuery); + + Response response = given() + .queryParam("processInstanceIds", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST_WITH_DUP) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(instanceQuery); + Set expectedSet = MockProvider.createMockSetFromList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST); + + inOrder.verify(instanceQuery).processInstanceIds(expectedSet); + inOrder.verify(instanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be two process definitions returned.", 2, instances.size()); + + String returnedInstanceId1 = from(content).getString("[0].id"); + String returnedInstanceId2 = from(content).getString("[1].id"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId1); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId2); + } + + @Test + public void testInstanceRetrievalByListWithDuplicateAsPost() { + List mockProcessInstanceList = new ArrayList(); + + mockProcessInstanceList.add(MockProvider.createMockInstance()); + mockProcessInstanceList.add(MockProvider.createAnotherMockInstance()); + + ProcessInstanceQuery instanceQuery = mock(ProcessInstanceQuery.class); + + when(instanceQuery.list()).thenReturn(mockProcessInstanceList); + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(instanceQuery); + + Map> params = new HashMap>(); + Set processInstanceIds = MockProvider.createMockSetFromList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID_LIST); + params.put("processInstanceIds", processInstanceIds); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(instanceQuery); + inOrder.verify(instanceQuery).processInstanceIds(processInstanceIds); + inOrder.verify(instanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be two process definitions returned.", 2, instances.size()); + + String returnedInstanceId1 = from(content).getString("[0].id"); + String returnedInstanceId2 = from(content).getString("[1].id"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId1); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID, returnedInstanceId2); + } + + @Test + public void testInstanceRetrievalByListWithEmpty() { + ProcessInstanceQuery instanceQuery = mock(ProcessInstanceQuery.class); + + when(instanceQuery.list()).thenReturn(null); + String expectedExceptionMessage = "Set of process instance ids is empty"; + doThrow(new ProcessEngineException(expectedExceptionMessage)).when(instanceQuery).processInstanceIds(anySet()); + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(instanceQuery); + + String emptyList = ""; + given() + .queryParam("processInstanceIds", emptyList) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo(expectedExceptionMessage)) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + } + + @Test + public void testInstanceRetrievalByListWithEmptyAsPost() { + ProcessInstanceQuery instanceQuery = mock(ProcessInstanceQuery.class); + + when(instanceQuery.list()).thenReturn(null); + String expectedExceptionMessage = "Set of process instance ids is empty"; + doThrow(new ProcessEngineException(expectedExceptionMessage)).when(instanceQuery).processInstanceIds(anySet()); + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(instanceQuery); + + Map> params = new HashMap>(); + params.put("processInstanceIds", new HashSet()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo(expectedExceptionMessage)) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + } + + @Test + public void testQueryRootProcessInstances() { + given() + .queryParam("rootProcessInstances", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).rootProcessInstances(); + } + + @Test + public void testQueryRootProcessInstancesAsPost() { + Map params =new HashMap(); + params.put("rootProcessInstances", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).rootProcessInstances(); + } + + @Test + public void testQueryLeafProcessInstances() { + given() + .queryParam("leafProcessInstances", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).leafProcessInstances(); + } + + @Test + public void testQueryLeafProcessInstancesAsPost() { + Map params =new HashMap(); + params.put("leafProcessInstances", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).leafProcessInstances(); + } + + @Test + public void testQueryProcessDefinitionWithoutTenantId() { + given() + .queryParam("processDefinitionWithoutTenantId", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).processDefinitionWithoutTenantId(); + } + + @Test + public void testQueryProcessDefinitionWithoutTenantIdAsPost() { + Map params = new HashMap<>(); + params.put("processDefinitionWithoutTenantId", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).processDefinitionWithoutTenantId(); + } + + @Test + public void testQueryProcessInstanceWithIncident() { + given() + .queryParam("withIncident", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).withIncident(); + } + + @Test + public void testQueryProcessInstanceWithIncidentAsPost() { + Map params = new HashMap(); + params.put("withIncident", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).withIncident(); + } + + @Test + public void testProcessDefinitionKeyInParameter() { + given() + .queryParam("processDefinitionKeyIn", MockProvider.EXAMPLE_KEY_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).processDefinitionKeyIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockedQuery).list(); + } + + @Test + public void testProcessDefinitionKeyInPostParameter() { + Map queryParameters = new HashMap(); + queryParameters.put("processDefinitionKeyIn", MockProvider.EXAMPLE_KEY_LIST.split(",")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).processDefinitionKeyIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockedQuery).list(); + } + + @Test + public void testProcessDefinitionKeyNotInParameter() { + given() + .queryParam("processDefinitionKeyNotIn", MockProvider.EXAMPLE_KEY_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).processDefinitionKeyNotIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockedQuery).list(); + } + + @Test + public void testProcessDefinitionKeyNotInPostParameter() { + Map queryParameters = new HashMap(); + queryParameters.put("processDefinitionKeyNotIn", MockProvider.EXAMPLE_KEY_LIST.split(",")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + verify(mockedQuery).processDefinitionKeyNotIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY); + verify(mockedQuery).list(); + } + + @Test + public void testOrQuery() { + // given + ProcessInstanceQuery mockedQuery = mock(ProcessInstanceQueryImpl.class); + when(processEngine.getRuntimeService().createProcessInstanceQuery()).thenReturn(mockedQuery); + + ProcessInstanceQueryDto processInstanceQueryDto = new ProcessInstanceQueryDto(); + + ProcessInstanceQueryDto orQuery = new ProcessInstanceQueryDto(); + orQuery.setProcessDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + orQuery.setBusinessKey(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + + processInstanceQueryDto.setOrQueries(Collections.singletonList(orQuery)); + + // when + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header(ACCEPT_JSON_HEADER) + .body(processInstanceQueryDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(PROCESS_INSTANCE_QUERY_URL); + + ArgumentCaptor argument = ArgumentCaptor.forClass(ProcessInstanceQueryImpl.class); + verify(((ProcessInstanceQueryImpl) mockedQuery)).addOrQuery(argument.capture()); + + // then + assertThat(argument.getValue().getProcessDefinitionId()).isEqualTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertThat(argument.getValue().getBusinessKey()).isEqualTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/RestartProcessInstanceRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/RestartProcessInstanceRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d6740a830e0627353b0ecfc8115cac9b7d8de81e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/RestartProcessInstanceRestServiceTest.java @@ -0,0 +1,639 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockBatch; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.*; + +import io.restassured.http.ContentType; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.ModificationInstructionBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.RestartProcessInstanceBuilder; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +public class RestartProcessInstanceRestServiceTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_DEFINITION_URL = TEST_RESOURCE_ROOT_PATH + "/process-definition"; + protected static final String SINGLE_PROCESS_DEFINITION_URL = PROCESS_DEFINITION_URL + "/{id}"; + protected static final String RESTART_PROCESS_INSTANCE_URL = SINGLE_PROCESS_DEFINITION_URL + "/restart"; + protected static final String RESTART_PROCESS_INSTANCE_ASYNC_URL = SINGLE_PROCESS_DEFINITION_URL + "/restart-async"; + + RuntimeService runtimeServiceMock; + HistoryService historyServiceMock; + RestartProcessInstanceBuilder builderMock; + + @Before + public void setUpRuntimeData() { + runtimeServiceMock = mock(RuntimeService.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + + historyServiceMock = mock(HistoryService.class); + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + builderMock = mock(RestartProcessInstanceBuilder.class); + when(builderMock.startAfterActivity(anyString())).thenReturn(builderMock); + when(builderMock.startBeforeActivity(anyString())).thenReturn(builderMock); + when(builderMock.startTransition(anyString())).thenReturn(builderMock); + when(builderMock.processInstanceIds(anyList())).thenReturn(builderMock); + when(builderMock.historicProcessInstanceQuery(any(HistoricProcessInstanceQuery.class))).thenReturn(builderMock); + when(builderMock.skipCustomListeners()).thenReturn(builderMock); + when(builderMock.skipIoMappings()).thenReturn(builderMock); + when(builderMock.initialSetOfVariables()).thenReturn(builderMock); + when(builderMock.withoutBusinessKey()).thenReturn(builderMock); + + Batch batchMock = createMockBatch(); + when(builderMock.executeAsync()).thenReturn(batchMock); + + when(runtimeServiceMock.restartProcessInstances(anyString())).thenReturn(builderMock); + } + + @Test + public void testRestartProcessInstanceSync() { + + HashMap json = new HashMap(); + ArrayList> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("processInstanceIds", Arrays.asList("processInstanceId1", "processInstanceId2")); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).restartProcessInstances(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(builderMock).startAfterActivity("activityId"); + verify(builderMock).processInstanceIds(Arrays.asList("processInstanceId1", "processInstanceId2")); + verify(builderMock).execute(); + } + + @Test + public void testRestartProcessInstanceAsync() { + HashMap json = new HashMap(); + ArrayList> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startAfter().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("processInstanceIds", Arrays.asList("processInstanceId1", "processInstanceId2")); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + + verify(runtimeServiceMock).restartProcessInstances(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(builderMock).startAfterActivity("activityId"); + verify(builderMock).processInstanceIds(Arrays.asList("processInstanceId1", "processInstanceId2")); + verify(builderMock).executeAsync(); + } + + @Test + public void testRestartProcessInstanceWithNullProcessInstanceIdsSync() { + doThrow(new BadUserRequestException("processInstanceIds is null")).when(builderMock).execute(); + + HashMap json = new HashMap(); + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + } + + @Test + public void testRestartProcessInstanceWithNullProcessInstanceIdsAsync() { + doThrow(new BadUserRequestException("processInstanceIds is null")).when(builderMock).executeAsync(); + + HashMap json = new HashMap(); + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + } + + @Test + public void testRestartProcessInstanceWithHistoricProcessInstanceQuerySync() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + HashMap json = new HashMap(); + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + query.setProcessInstanceBusinessKey("businessKey"); + + json.put("historicProcessInstanceQuery", query); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + + verify(runtimeServiceMock).restartProcessInstances(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).historicProcessInstanceQuery(query.toQuery(processEngine)); + verify(builderMock).execute(); + } + + @Test + public void testRestartProcessInstanceWithHistoricProcessInstanceQueryAsync() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + HashMap json = new HashMap(); + List> instructions = new ArrayList>(); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + query.setProcessInstanceBusinessKey("businessKey"); + + json.put("historicProcessInstanceQuery", query); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + + verify(runtimeServiceMock).restartProcessInstances(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).historicProcessInstanceQuery(query.toQuery(processEngine)); + verify(builderMock).executeAsync(); + } + + @Test + public void testRestartProcessInstanceWithNullInstructionsSync() { + doThrow(new BadUserRequestException("instructions is null")).when(builderMock).execute(); + + HashMap json = new HashMap(); + json.put("processInstanceIds", "processInstanceId"); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + } + + @Test + public void testRestartProcessInstanceWithNullInstructionsAsync() { + doThrow(new BadUserRequestException("instructions is null")).when(builderMock).executeAsync(); + + HashMap json = new HashMap(); + json.put("processInstanceIds", "processInstanceId"); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + } + + @Test + public void testRestartProcessInstanceWithInvalidModificationInstructionForStartAfterSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startAfter().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startAfterActivity': 'activityId' must be set")) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + } + + @Test + public void testRestartProcessInstanceWithInvalidModificationInstructionForStartAfterAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startAfter().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startAfterActivity': 'activityId' must be set")) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + } + + @Test + public void testRestartProcessInstanceWithInvalidModificationInstructionForStartBeforeSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startBefore().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startBeforeActivity': 'activityId' must be set")) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + } + + @Test + public void testRestartProcessInstanceWithInvalidModificationInstructionForStartBeforeAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startBefore().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startBeforeActivity': 'activityId' must be set")) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + } + + @Test + public void testRestartProcessInstanceWithInvalidModificationInstructionForStartTransitionSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startTransition().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startTransition': 'transitionId' must be set")) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + } + + @Test + public void testRestartProcessInstanceWithInvalidModificationInstructionForStartTransitionAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("200", "100")); + instructions.add(ModificationInstructionBuilder.startTransition().getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("For instruction type 'startTransition': 'transitionId' must be set")) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + } + + @Test + public void testRestartProcessInstanceWithInitialVariablesAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("processInstance1", "processInstance2")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("initialVariables", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + + verify(builderMock).processInstanceIds(Arrays.asList("processInstance1", "processInstance2")); + verify(builderMock).initialSetOfVariables(); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).executeAsync(); + } + + @Test + public void testRestartProcessInstanceWithInitialVariablesSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("processInstance1", "processInstance2")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("initialVariables", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + + verify(builderMock).processInstanceIds(Arrays.asList("processInstance1", "processInstance2")); + verify(builderMock).initialSetOfVariables(); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).execute(); + } + + @Test + public void testRestartProcessInstanceWithSkipCustomListenersAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("processInstance1", "processInstance2")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("skipCustomListeners", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + + verify(builderMock).processInstanceIds(Arrays.asList("processInstance1", "processInstance2")); + verify(builderMock).skipCustomListeners(); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).executeAsync(); + } + + @Test + public void testRestartProcessInstanceWithSkipCustomListenersSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("processInstance1", "processInstance2")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("skipCustomListeners", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + + verify(builderMock).processInstanceIds(Arrays.asList("processInstance1", "processInstance2")); + verify(builderMock).skipCustomListeners(); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).execute(); + } + + @Test + public void testRestartProcessInstanceWithSkipIoMappingsAsync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("processInstance1", "processInstance2")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("skipIoMappings", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + + verify(builderMock).processInstanceIds(Arrays.asList("processInstance1", "processInstance2")); + verify(builderMock).skipIoMappings(); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).executeAsync(); + } + + @Test + public void testRestartProcessInstanceWithSkipIoMappingsSync() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("processInstance1", "processInstance2")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("skipIoMappings", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + + verify(builderMock).processInstanceIds(Arrays.asList("processInstance1", "processInstance2")); + verify(builderMock).skipIoMappings(); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).execute(); + } + + @Test + public void testRestartProcessInstanceWithoutBusinessKey() { + Map json = new HashMap(); + List> instructions = new ArrayList>(); + + json.put("processInstanceIds", Arrays.asList("processInstance1", "processInstance2")); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + json.put("withoutBusinessKey", true); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + + verify(builderMock).processInstanceIds(Arrays.asList("processInstance1", "processInstance2")); + verify(builderMock).withoutBusinessKey(); + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).execute(); + } + + @Test + public void testRestartProcessInstanceWithoutProcessInstanceIdsSync() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + Map json = new HashMap(); + List> instructions = new ArrayList>(); + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + query.setFinished(true); + json.put("historicProcessInstanceQuery", query); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_URL); + + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).historicProcessInstanceQuery(query.toQuery(processEngine)); + verify(builderMock).execute(); + verifyNoMoreInteractions(builderMock); + } + + @Test + public void testRestartProcessInstanceWithoutProcessInstanceIdsAsync() { + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(new HistoricProcessInstanceQueryImpl()); + Map json = new HashMap(); + List> instructions = new ArrayList>(); + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + query.setFinished(true); + json.put("historicProcessInstanceQuery", query); + instructions.add(ModificationInstructionBuilder.startBefore().activityId("activityId").getJson()); + json.put("instructions", instructions); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .contentType(ContentType.JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(RESTART_PROCESS_INSTANCE_ASYNC_URL); + + verify(builderMock).startBeforeActivity("activityId"); + verify(builderMock).historicProcessInstanceQuery(query.toQuery(processEngine)); + verify(builderMock).executeAsync(); + verifyNoMoreInteractions(builderMock); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/SchemaLogRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/SchemaLogRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0487562430b43b94d9cf51c6bdf761d6fcdf9aff --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/SchemaLogRestServiceQueryTest.java @@ -0,0 +1,126 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.impl.persistence.entity.SchemaLogEntryEntity; +import org.camunda.bpm.engine.management.SchemaLogEntry; +import org.camunda.bpm.engine.management.SchemaLogQuery; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +/** + * @author Miklas Boskamp + * + */ +public class SchemaLogRestServiceQueryTest extends AbstractRestServiceTest { + + /** + * + */ + private static final String SCHEMA_LOG_URL = TEST_RESOURCE_ROOT_PATH + SchemaLogRestService.PATH; + + private static final String SCHEMA_LOG_ENTRY_MOCK_ID = "schema-log-entry-mock-id"; + private static final String SCHEMA_LOG_ENTRY_MOCK_VERSION = "schema-log-entry-mock-version"; + private static final Date SCHEMA_LOG_ENTRY_MOCK_TIMESTAMP = new Date(); + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + private SchemaLogQuery mockedQuery; + + private List mockedSchemaLogEntries; + + @Before + public void init() { + mockedQuery = Mockito.mock(SchemaLogQuery.class); + + mockedSchemaLogEntries = createMockedSchemaLogEntries(); + when(mockedQuery.list()).thenReturn(mockedSchemaLogEntries); + + when(processEngine.getManagementService().createSchemaLogQuery()).thenReturn(mockedQuery); + } + + private List createMockedSchemaLogEntries(){ + List entries = new ArrayList(); + SchemaLogEntryEntity entry = new SchemaLogEntryEntity(); + + entry.setId(SCHEMA_LOG_ENTRY_MOCK_ID); + entry.setVersion(SCHEMA_LOG_ENTRY_MOCK_VERSION); + entry.setTimestamp(SCHEMA_LOG_ENTRY_MOCK_TIMESTAMP); + + entries.add(entry); + return entries; + } + + @Test + public void testGetSchemaLog() { + given() + .queryParam("version", SCHEMA_LOG_ENTRY_MOCK_VERSION) + .queryParam("sortBy", "timestamp") + .queryParam("sortOrder", "asc") + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_JSON) + .body("[0].version", is(SCHEMA_LOG_ENTRY_MOCK_VERSION)) + .body("[0].timestamp", notNullValue()) + .when().get(SCHEMA_LOG_URL); + + verify(mockedQuery).version(SCHEMA_LOG_ENTRY_MOCK_VERSION); + verify(mockedQuery).orderByTimestamp(); + verify(mockedQuery).list(); + } + + @Test + public void testGetSchemaLogAsPost() { + Map params = new HashMap(); + params.put("version", SCHEMA_LOG_ENTRY_MOCK_VERSION); + params.put("sortBy", "timestamp"); + params.put("sortOrder", "asc"); + + given() + .contentType(MediaType.APPLICATION_JSON) + .body(params) + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_JSON) + .body("[0].version", is(SCHEMA_LOG_ENTRY_MOCK_VERSION)) + .body("[0].timestamp", notNullValue()) + .when().post(SCHEMA_LOG_URL); + + verify(mockedQuery).version(SCHEMA_LOG_ENTRY_MOCK_VERSION); + verify(mockedQuery).orderByTimestamp(); + verify(mockedQuery).list(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/SignalRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/SignalRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..535018c985259f9bae60c6b00a3673334ec10541 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/SignalRestServiceTest.java @@ -0,0 +1,524 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.impl.SignalEventReceivedBuilderImpl; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.SignalEventReceivedBuilder; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +import javax.ws.rs.core.Response.Status; +import java.util.HashMap; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * @author Tassilo Weidner + */ +public class SignalRestServiceTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String SIGNAL_URL = TEST_RESOURCE_ROOT_PATH + SignalRestService.PATH; + + private RuntimeService runtimeServiceMock; + private SignalEventReceivedBuilder signalBuilderMock; + + @Before + public void setupMocks() { + runtimeServiceMock = mock(RuntimeService.class); + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + + signalBuilderMock = mock(SignalEventReceivedBuilderImpl.class); + when(runtimeServiceMock.createSignalEvent(anyString())).thenReturn(signalBuilderMock); + when(signalBuilderMock.setVariables(Mockito.any())).thenReturn(signalBuilderMock); + when(signalBuilderMock.executionId(anyString())).thenReturn(signalBuilderMock); + when(signalBuilderMock.tenantId(anyString())).thenReturn(signalBuilderMock); + when(signalBuilderMock.withoutTenantId()).thenReturn(signalBuilderMock); + } + + @Test + public void shouldBroadcast() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent(requestBody.get("name")); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldBroadcastWithVariables() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("variables", + VariablesBuilder.create() + .variable("total", 420) + .variable("invoiceId", "ABC123") + .getVariables()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + + Map expectedVariables = new HashMap(); + expectedVariables.put("total", 420); + expectedVariables.put("invoiceId", "ABC123"); + verify(signalBuilderMock).setVariables(expectedVariables); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldBroadcastWithTenant() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("tenantId", "aTenantId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + verify(signalBuilderMock).tenantId((String) requestBody.get("tenantId")); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldBroadcastWithVariablesAndTenant() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("variables", + VariablesBuilder.create() + .variable("total", 420) + .variable("invoiceId", "ABC123") + .getVariables()); + requestBody.put("tenantId", "aTenantId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + + Map expectedVariables = new HashMap(); + expectedVariables.put("total", 420); + expectedVariables.put("invoiceId", "ABC123"); + verify(signalBuilderMock).setVariables(expectedVariables); + verify(signalBuilderMock).tenantId((String) requestBody.get("tenantId")); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldBroadcastWithoutTenant() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("withoutTenantId", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + verify(signalBuilderMock).withoutTenantId(); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldBroadcastWithoutTenantAndWithVariables() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("variables", + VariablesBuilder.create() + .variable("total", 420) + .variable("invoiceId", "ABC123") + .getVariables()); + requestBody.put("withoutTenantId", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + Map expectedVariables = new HashMap(); + expectedVariables.put("total", 420); + expectedVariables.put("invoiceId", "ABC123"); + verify(signalBuilderMock).setVariables(expectedVariables); + verify(signalBuilderMock).withoutTenantId(); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldDeliverToSingleExecution() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("executionId", "anExecutionId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent(requestBody.get("name")); + verify(signalBuilderMock).executionId(requestBody.get("executionId")); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldDeliverToSingleExecutionWithVariables() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("executionId", "anExecutionId"); + requestBody.put("variables", + VariablesBuilder.create() + .variable("total", 420) + .variable("invoiceId", "ABC123") + .getVariables()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + Map expectedVariables = new HashMap(); + expectedVariables.put("total", 420); + expectedVariables.put("invoiceId", "ABC123"); + verify(signalBuilderMock).setVariables(expectedVariables); + verify(signalBuilderMock).executionId((String) requestBody.get("executionId")); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldDeliverToSingleExecutionWithTenant() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("tenantId", "aTenantId"); + requestBody.put("executionId", "anExecutionId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + verify(signalBuilderMock).tenantId((String) requestBody.get("tenantId")); + verify(signalBuilderMock).executionId((String) requestBody.get("executionId")); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldDeliverToSingleExecutionWithVariablesAndTenant() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("executionId", "anExecutionId"); + requestBody.put("variables", + VariablesBuilder.create() + .variable("total", 420) + .variable("invoiceId", "ABC123") + .getVariables()); + requestBody.put("tenantId", "aTenantId"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + verify(signalBuilderMock).executionId((String) requestBody.get("executionId")); + Map expectedVariables = new HashMap(); + expectedVariables.put("total", 420); + expectedVariables.put("invoiceId", "ABC123"); + verify(signalBuilderMock).setVariables(expectedVariables); + verify(signalBuilderMock).tenantId((String) requestBody.get("tenantId")); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldDeliverToSingleExecutionWithoutTenant() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("executionId", "anExecutionId"); + requestBody.put("withoutTenantId", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + verify(signalBuilderMock).executionId((String) requestBody.get("executionId")); + verify(signalBuilderMock).withoutTenantId(); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldDeliverToSingleExecutionWithoutTenantAndWithVariables() { + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("executionId", "anExecutionId"); + requestBody.put("withoutTenantId", true); + requestBody.put("variables", + VariablesBuilder.create() + .variable("total", 420) + .variable("invoiceId", "ABC123") + .getVariables()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SIGNAL_URL); + + verify(runtimeServiceMock).createSignalEvent((String) requestBody.get("name")); + verify(signalBuilderMock).executionId((String) requestBody.get("executionId")); + verify(signalBuilderMock).withoutTenantId(); + Map expectedVariables = new HashMap(); + expectedVariables.put("total", 420); + expectedVariables.put("invoiceId", "ABC123"); + verify(signalBuilderMock).setVariables(expectedVariables); + verify(signalBuilderMock).send(); + verifyNoMoreInteractions(signalBuilderMock); + } + + @Test + public void shouldThrowExceptionByMissingName() { + Map requestBody = new HashMap(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No signal name given")) + .when() + .post(SIGNAL_URL); + } + + @Test + public void shouldThrowBadUserRequestException() { + String message = "expected exception"; + doThrow(new BadUserRequestException(message)).when(signalBuilderMock).send(); + + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SIGNAL_URL); + } + + @Test + public void shouldThrowAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(signalBuilderMock).send(); + + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SIGNAL_URL); + } + + @Test + public void shouldThrowProcessEngineException() { + String message = "expected exception"; + doThrow(new ProcessEngineException(message)).when(signalBuilderMock).send(); + + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SIGNAL_URL); + } + + @Test + public void shouldReturnInternalServerErrorResponseForNotFoundException() { + String message = "expected exception"; + doThrow(new NotFoundException(message)).when(signalBuilderMock).send(); + + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + requestBody.put("executionId", "foo"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SIGNAL_URL); + } + + @Test + public void shouldReturnInternalServerErrorResponseJsonWithTypeAndMessage() { + String message = "expected exception"; + doThrow(new IllegalArgumentException(message)).when(signalBuilderMock).send(); + + Map requestBody = new HashMap(); + requestBody.put("name", "aSignalName"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(IllegalArgumentException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SIGNAL_URL); + } + + @Test + public void shouldReturnError() { + doThrow(new ProcessEngineException("foo", 123)) + .when(signalBuilderMock).send(); + + Map requestBody = new HashMap<>(); + requestBody.put("name", "aSignalName"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("foo")) + .body("code", equalTo(123)) + .when() + .post(SIGNAL_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/StatisticsRestTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/StatisticsRestTest.java new file mode 100644 index 0000000000000000000000000000000000000000..36a8fe1d064b2557c80f84ffde6384d4922a4712 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/StatisticsRestTest.java @@ -0,0 +1,409 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.impl.ActivityStatisticsQueryImpl; +import org.camunda.bpm.engine.impl.ProcessDefinitionStatisticsQueryImpl; +import org.camunda.bpm.engine.management.ActivityStatistics; +import org.camunda.bpm.engine.management.ActivityStatisticsQuery; +import org.camunda.bpm.engine.management.ProcessDefinitionStatistics; +import org.camunda.bpm.engine.management.ProcessDefinitionStatisticsQuery; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; + +public class StatisticsRestTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_DEFINITION_STATISTICS_URL = TEST_RESOURCE_ROOT_PATH + "/process-definition/statistics"; + protected static final String ACTIVITY_STATISTICS_URL = TEST_RESOURCE_ROOT_PATH + "/process-definition/{id}/statistics"; + protected static final String ACTIVITY_STATISTICS_BY_KEY_URL = TEST_RESOURCE_ROOT_PATH + "/process-definition/key/{key}/statistics"; + private ProcessDefinitionStatisticsQuery processDefinitionStatisticsQueryMock; + private ActivityStatisticsQuery activityQueryMock; + private ProcessDefinitionQuery processDefinitionQueryMock; + + @Before + public void setUpRuntimeData() { + setupProcessDefinitionStatisticsMock(); + setupActivityStatisticsMock(); + setupProcessDefinitionMock(); + } + + private void setupActivityStatisticsMock() { + List mocks = MockProvider.createMockActivityStatistics(); + + activityQueryMock = mock(ActivityStatisticsQueryImpl.class); + when(activityQueryMock.unlimitedList()).thenReturn(mocks); + when(processEngine.getManagementService().createActivityStatisticsQuery(any(String.class))).thenReturn(activityQueryMock); + } + + private void setupProcessDefinitionStatisticsMock() { + List mocks = MockProvider.createMockProcessDefinitionStatistics(); + + processDefinitionStatisticsQueryMock = mock(ProcessDefinitionStatisticsQueryImpl.class); + when(processDefinitionStatisticsQueryMock.unlimitedList()).thenReturn(mocks); + when(processEngine.getManagementService().createProcessDefinitionStatisticsQuery()).thenReturn(processDefinitionStatisticsQueryMock); + } + + private void setupProcessDefinitionMock() { + ProcessDefinition mockDefinition = MockProvider.createMockDefinition(); + processDefinitionQueryMock = mock(ProcessDefinitionQuery.class); + when(processDefinitionQueryMock.processDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.tenantIdIn(anyString())).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.withoutTenantId()).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.latestVersion()).thenReturn(processDefinitionQueryMock); + when(processDefinitionQueryMock.singleResult()).thenReturn(mockDefinition); + when(processDefinitionQueryMock.list()).thenReturn(Collections.singletonList(mockDefinition)); + when(processDefinitionQueryMock.count()).thenReturn(1L); + when(processEngine.getRepositoryService().createProcessDefinitionQuery()).thenReturn(processDefinitionQueryMock); + } + + @Test + public void testStatisticsRetrievalPerProcessDefinitionVersion() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("definition.size()", is(2)) + .body("definition.id", hasItems(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, MockProvider.ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID)) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + } + + @Test + public void testProcessDefinitionStatisticsRetrieval() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("[0].definition.id", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("[0].definition.key", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("[0].definition.category", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY)) + .body("[0].definition.name", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME)) + .body("[0].definition.description", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DESCRIPTION)) + .body("[0].definition.deploymentId", equalTo(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .body("[0].definition.version", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION)) + .body("[0].definition.resource", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME)) + .body("[0].definition.diagram", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME)) + .body("[0].definition.tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("[0].definition.versionTag", equalTo(MockProvider.EXAMPLE_VERSION_TAG)) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + } + + @Test + public void testActivityStatisticsRetrieval() { + given().pathParam("id", "aDefinitionId") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("id", hasItems(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID)) + .when().get(ACTIVITY_STATISTICS_URL); + } + + @Test + public void testActivityStatisticsRetrievalByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("id", hasItems(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID)) + .when().get(ACTIVITY_STATISTICS_BY_KEY_URL); + } + + @Test + public void testAdditionalFailedJobsOption() { + given().queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(processDefinitionStatisticsQueryMock); + inOrder.verify(processDefinitionStatisticsQueryMock).includeFailedJobs(); + inOrder.verify(processDefinitionStatisticsQueryMock).unlimitedList(); + } + + @Test + public void testAdditionalIncidentsOption() { + given().queryParam("incidents", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(processDefinitionStatisticsQueryMock); + inOrder.verify(processDefinitionStatisticsQueryMock).includeIncidents(); + inOrder.verify(processDefinitionStatisticsQueryMock).unlimitedList(); + } + + @Test + public void testAdditionalIncidentsForTypeOption() { + given().queryParam("incidentsForType", "failedJob") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(processDefinitionStatisticsQueryMock); + inOrder.verify(processDefinitionStatisticsQueryMock).includeIncidentsForType("failedJob"); + inOrder.verify(processDefinitionStatisticsQueryMock).unlimitedList(); + } + + @Test + public void testAdditionalIncidentsAndFailedJobsOption() { + given().queryParam("incidents", "true").queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(processDefinitionStatisticsQueryMock); + inOrder.verify(processDefinitionStatisticsQueryMock).includeFailedJobs(); + inOrder.verify(processDefinitionStatisticsQueryMock).includeIncidents(); + inOrder.verify(processDefinitionStatisticsQueryMock).unlimitedList(); + } + + @Test + public void testAdditionalIncidentsForTypeAndFailedJobsOption() { + given().queryParam("incidentsForType", "failedJob").queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(processDefinitionStatisticsQueryMock); + inOrder.verify(processDefinitionStatisticsQueryMock).includeFailedJobs(); + inOrder.verify(processDefinitionStatisticsQueryMock).includeIncidentsForType("failedJob"); + inOrder.verify(processDefinitionStatisticsQueryMock).unlimitedList(); + } + + @Test + public void testAdditionalIncidentsAndIncidentsForType() { + given().queryParam("incidents", "true").queryParam("incidentsForType", "anIncidentTpye") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + } + + @Test + public void testActivityStatisticsWithFailedJobs() { + given().pathParam("id", "aDefinitionId").queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeFailedJobs(); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivityStatisticsWithFailedJobsByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY).queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_BY_KEY_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeFailedJobs(); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivityStatisticsWithIncidents() { + given().pathParam("id", "aDefinitionId").queryParam("incidents", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeIncidents(); + inOrder.verify(((ActivityStatisticsQueryImpl)activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivityStatisticsWithIncidentsByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY).queryParam("incidents", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_BY_KEY_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeIncidents(); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivityStatisticsIncidentsForTypeTypeOption() { + given().pathParam("id", "aDefinitionId").queryParam("incidentsForType", "failedJob") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeIncidentsForType("failedJob"); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivityStatisticsIncidentsForTypeTypeOptionByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY).queryParam("incidentsForType", "failedJob") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_BY_KEY_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeIncidentsForType("failedJob"); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivtyStatisticsIncidentsAndFailedJobsOption() { + given().pathParam("id", "aDefinitionId") + .queryParam("incidents", "true").queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeFailedJobs(); + inOrder.verify(activityQueryMock).includeIncidents(); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivtyStatisticsIncidentsAndFailedJobsOptionByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("incidents", "true").queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_BY_KEY_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeFailedJobs(); + inOrder.verify(activityQueryMock).includeIncidents(); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivtyStatisticsIncidentsForTypeAndFailedJobsOption() { + given().pathParam("id", "aDefinitionId") + .queryParam("incidentsForType", "failedJob").queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeFailedJobs(); + inOrder.verify(activityQueryMock).includeIncidentsForType("failedJob"); + inOrder.verify((activityQueryMock)).unlimitedList(); + } + + @Test + public void testActivtyStatisticsByIdThrowsAuthorizationException() { + String message = "expected exception"; + when((activityQueryMock).unlimitedList()).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", "aDefinitionId") + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(ACTIVITY_STATISTICS_URL); + } + + @Test + public void testActivtyStatisticsIncidentsForTypeAndFailedJobsOptionByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("incidentsForType", "failedJob").queryParam("failedJobs", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_BY_KEY_URL); + + InOrder inOrder = Mockito.inOrder(activityQueryMock); + inOrder.verify(activityQueryMock).includeFailedJobs(); + inOrder.verify(activityQueryMock).includeIncidentsForType("failedJob"); + inOrder.verify(activityQueryMock).unlimitedList(); + } + + @Test + public void testActivtyStatisticsIncidentsAndIncidentsForType() { + given().pathParam("id", "aDefinitionId") + .queryParam("incidents", "true").queryParam("incidentsForType", "anIncidentTpye") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_URL); + } + + @Test + public void testActivtyStatisticsIncidentsAndIncidentsForTypeByKey() { + given().pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .queryParam("incidents", "true").queryParam("incidentsForType", "anIncidentTpye") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(ACTIVITY_STATISTICS_BY_KEY_URL); + } + + @Test + public void testActivtyStatisticsByIdThrowsAuthorizationExceptionByKey() { + String message = "expected exception"; + when((activityQueryMock).unlimitedList()) + .thenThrow(new AuthorizationException(message)); + + given() + .pathParam("key", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(ACTIVITY_STATISTICS_BY_KEY_URL); + } + + @Test + public void testProcessDefinitionStatisticsWithRootIncidents() { + given().queryParam("rootIncidents", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(PROCESS_DEFINITION_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(processDefinitionStatisticsQueryMock);; + inOrder.verify(processDefinitionStatisticsQueryMock).includeRootIncidents(); + inOrder.verify(processDefinitionStatisticsQueryMock).unlimitedList(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskReportRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskReportRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..28b7d026de467945c3b79ee34174df96700603e5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskReportRestServiceTest.java @@ -0,0 +1,183 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.rest.dto.converter.TaskReportResultToCsvConverter; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.task.TaskCountByCandidateGroupResult; +import org.camunda.bpm.engine.task.TaskReport; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import javax.ws.rs.core.Response.Status; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_GROUP_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_COUNT_BY_CANDIDATE_GROUP; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockTaskCountByCandidateGroupReport; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * @author Roman Smirnov + * + */ +public class TaskReportRestServiceTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String TASK_REPORT_URL = TEST_RESOURCE_ROOT_PATH + "/task/report"; + protected static final String CANDIDATE_GROUP_REPORT_URL = TASK_REPORT_URL + "/candidate-group-count"; + + protected TaskReport mockedReportQuery; + + @Before + public void setUpRuntimeData() { + mockedReportQuery = setUpMockHistoricProcessInstanceReportQuery(); + } + + private TaskReport setUpMockHistoricProcessInstanceReportQuery() { + TaskReport mockedReportQuery = mock(TaskReport.class); + + List taskCountByCandidateGroupResults = createMockTaskCountByCandidateGroupReport(); + when(mockedReportQuery.taskCountByCandidateGroup()).thenReturn(taskCountByCandidateGroupResults); + + when(processEngine.getTaskService().createTaskReport()).thenReturn(mockedReportQuery); + + return mockedReportQuery; + } + + @Test + public void testEmptyReport() { + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(CANDIDATE_GROUP_REPORT_URL); + + verify(mockedReportQuery).taskCountByCandidateGroup(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testMissingAuthorization() { + String message = "not authorized"; + when(mockedReportQuery.taskCountByCandidateGroup()).thenThrow(new AuthorizationException(message)); + + given() + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(CANDIDATE_GROUP_REPORT_URL); + } + + @Test + public void testTaskCountByCandidateGroupReport() { + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(CANDIDATE_GROUP_REPORT_URL); + + String content = response.asString(); + List reports = from(content).getList(""); + Assert.assertEquals("There should be one report returned.", 1, reports.size()); + Assert.assertNotNull("The returned report should not be null.", reports.get(0)); + + String returnedGroup = from(content).getString("[0].groupName"); + int returnedCount = from(content).getInt("[0].taskCount"); + + Assert.assertEquals(EXAMPLE_GROUP_ID, returnedGroup); + Assert.assertEquals(EXAMPLE_TASK_COUNT_BY_CANDIDATE_GROUP, returnedCount); + } + + + @Test + public void testEmptyCsvReport() { + given() + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .when() + .get(CANDIDATE_GROUP_REPORT_URL); + + verify(mockedReportQuery).taskCountByCandidateGroup(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testCsvTaskCountByCandidateGroupReport() { + Response response = given() + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"task-count-by-candidate-group.csv\"; " + + "filename*=UTF-8''task-count-by-candidate-group.csv") + .when() + .get(CANDIDATE_GROUP_REPORT_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(TaskReportResultToCsvConverter.CANDIDATE_GROUP_HEADER)); + assertTrue(responseContent.contains(EXAMPLE_GROUP_ID)); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_TASK_COUNT_BY_CANDIDATE_GROUP))); + } + + @Test + public void testApplicationCsvTaskCountByCandidateGroupReport() { + Response response = given() + .accept("application/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("application/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"task-count-by-candidate-group.csv\"; " + + "filename*=UTF-8''task-count-by-candidate-group.csv") + .when() + .get(CANDIDATE_GROUP_REPORT_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(TaskReportResultToCsvConverter.CANDIDATE_GROUP_HEADER)); + assertTrue(responseContent.contains(EXAMPLE_GROUP_ID)); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_TASK_COUNT_BY_CANDIDATE_GROUP))); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f14c7801f8d267a1499874739275d55a6c8d37ef --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskRestServiceInteractionTest.java @@ -0,0 +1,4362 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_CASE_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_CASE_EXECUTION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_CASE_INSTANCE_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_GROUP_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_GROUP_ID2; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ATTACHMENT_DESCRIPTION; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ATTACHMENT_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ATTACHMENT_NAME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ATTACHMENT_TYPE; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ATTACHMENT_URL; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_COMMENT_FULL_MESSAGE; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_COMMENT_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_COMMENT_ROOT_PROCESS_INSTANCE_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_COMMENT_TIME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_EXECUTION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_OWNER; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_PARENT_TASK_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_USER_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockHistoricTaskInstance; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.endsWith; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItem; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.assertj.core.api.Assertions; +import org.camunda.bpm.ProcessApplicationService; +import org.camunda.bpm.application.ProcessApplicationInfo; +import org.camunda.bpm.container.RuntimeContainerDelegate; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.FormService; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.exception.NullValueException; +import org.camunda.bpm.engine.form.TaskFormData; +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.GroupQuery; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.impl.form.CamundaFormRefImpl; +import org.camunda.bpm.engine.impl.form.validator.FormFieldValidationException; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.helper.EqualsMap; +import org.camunda.bpm.engine.rest.helper.EqualsVariableMap; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.util.EncodingUtil; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.task.Attachment; +import org.camunda.bpm.engine.task.Comment; +import org.camunda.bpm.engine.task.DelegationState; +import org.camunda.bpm.engine.task.IdentityLink; +import org.camunda.bpm.engine.task.IdentityLinkType; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.task.TaskQuery; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.path.json.JsonPath; +import io.restassured.response.Response; + +public class TaskRestServiceInteractionTest extends + AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String TASK_SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/task"; + protected static final String SINGLE_TASK_URL = TASK_SERVICE_URL + "/{id}"; + protected static final String CLAIM_TASK_URL = SINGLE_TASK_URL + "/claim"; + protected static final String UNCLAIM_TASK_URL = SINGLE_TASK_URL + "/unclaim"; + protected static final String COMPLETE_TASK_URL = SINGLE_TASK_URL + "/complete"; + protected static final String RESOLVE_TASK_URL = SINGLE_TASK_URL + "/resolve"; + protected static final String DELEGATE_TASK_URL = SINGLE_TASK_URL + "/delegate"; + protected static final String ASSIGNEE_TASK_URL = SINGLE_TASK_URL + "/assignee"; + protected static final String TASK_IDENTITY_LINKS_URL = SINGLE_TASK_URL + "/identity-links"; + + protected static final String TASK_FORM_URL = SINGLE_TASK_URL + "/form"; + protected static final String DEPLOYED_TASK_FORM_URL = SINGLE_TASK_URL + "/deployed-form"; + protected static final String RENDERED_FORM_URL = SINGLE_TASK_URL + "/rendered-form"; + protected static final String SUBMIT_FORM_URL = SINGLE_TASK_URL + "/submit-form"; + + protected static final String FORM_VARIABLES_URL = SINGLE_TASK_URL + "/form-variables"; + + protected static final String SINGLE_TASK_ADD_COMMENT_URL = SINGLE_TASK_URL + "/comment/create"; + protected static final String SINGLE_TASK_COMMENTS_URL = SINGLE_TASK_URL + "/comment"; + protected static final String SINGLE_TASK_SINGLE_COMMENT_URL = SINGLE_TASK_COMMENTS_URL + "/{commentId}"; + + protected static final String SINGLE_TASK_ADD_ATTACHMENT_URL = SINGLE_TASK_URL + "/attachment/create"; + protected static final String SINGLE_TASK_ATTACHMENTS_URL = SINGLE_TASK_URL + "/attachment"; + protected static final String SINGLE_TASK_SINGLE_ATTACHMENT_URL = SINGLE_TASK_ATTACHMENTS_URL + "/{attachmentId}"; + protected static final String SINGLE_TASK_DELETE_SINGLE_ATTACHMENT_URL = SINGLE_TASK_SINGLE_ATTACHMENT_URL; + protected static final String SINGLE_TASK_SINGLE_ATTACHMENT_DATA_URL = SINGLE_TASK_ATTACHMENTS_URL + "/{attachmentId}/data"; + + protected static final String TASK_CREATE_URL = TASK_SERVICE_URL + "/create"; + + protected static final String HANDLE_BPMN_ERROR_URL = SINGLE_TASK_URL + "/bpmnError"; + protected static final String HANDLE_BPMN_ESCALATION_URL = SINGLE_TASK_URL + "/bpmnEscalation"; + + private static final String LOCAL_VARIABLE_KEY = "aLocalVariableId"; + private static final List LOCAL_VARIABLE_PAYLOAD = Arrays.asList("aLocalValue", "bLocalValue"); + + private Task mockTask; + private TaskService taskServiceMock; + private TaskQuery mockQuery; + private FormService formServiceMock; + private ManagementService managementServiceMock; + private RepositoryService repositoryServiceMock; + + private IdentityLink mockAssigneeIdentityLink; + private IdentityLink mockOwnerIdentityLink; + private IdentityLink mockCandidateGroupIdentityLink; + private IdentityLink mockCandidateGroup2IdentityLink; + + private HistoricTaskInstanceQuery historicTaskInstanceQueryMock; + + private Comment mockTaskComment; + private List mockTaskComments; + + private Attachment mockTaskAttachment; + private List mockTaskAttachments; + + @Before + public void setUpRuntimeData() { + taskServiceMock = mock(TaskService.class); + when(processEngine.getTaskService()).thenReturn(taskServiceMock); + + mockTask = MockProvider.createMockTask(); + mockQuery = mock(TaskQuery.class); + when(mockQuery.initializeFormKeys()).thenReturn(mockQuery); + when(mockQuery.taskId(any())).thenReturn(mockQuery); + when(mockQuery.withCommentAttachmentInfo()).thenReturn(mockQuery); + when(mockQuery.singleResult()).thenReturn(mockTask); + when(taskServiceMock.createTaskQuery()).thenReturn(mockQuery); + + List identityLinks = new ArrayList<>(); + mockAssigneeIdentityLink = MockProvider.createMockUserAssigneeIdentityLink(); + identityLinks.add(mockAssigneeIdentityLink); + mockOwnerIdentityLink = MockProvider.createMockUserOwnerIdentityLink(); + identityLinks.add(mockOwnerIdentityLink); + mockCandidateGroupIdentityLink = MockProvider.createMockCandidateGroupIdentityLink(); + identityLinks.add(mockCandidateGroupIdentityLink); + mockCandidateGroup2IdentityLink = MockProvider.createAnotherMockCandidateGroupIdentityLink(); + identityLinks.add(mockCandidateGroup2IdentityLink); + when(taskServiceMock.getIdentityLinksForTask(EXAMPLE_TASK_ID)).thenReturn(identityLinks); + + mockTaskComment = MockProvider.createMockTaskComment(); + when(taskServiceMock.getTaskComment(EXAMPLE_TASK_ID, EXAMPLE_TASK_COMMENT_ID)).thenReturn(mockTaskComment); + mockTaskComments = MockProvider.createMockTaskComments(); + when(taskServiceMock.getTaskComments(EXAMPLE_TASK_ID)).thenReturn(mockTaskComments); + when(taskServiceMock.createComment(EXAMPLE_TASK_ID, null, EXAMPLE_TASK_COMMENT_FULL_MESSAGE)).thenReturn(mockTaskComment); + + mockTaskAttachment = MockProvider.createMockTaskAttachment(); + when(taskServiceMock.getTaskAttachment(EXAMPLE_TASK_ID, EXAMPLE_TASK_ATTACHMENT_ID)).thenReturn(mockTaskAttachment); + mockTaskAttachments = MockProvider.createMockTaskAttachments(); + when(taskServiceMock.getTaskAttachments(EXAMPLE_TASK_ID)).thenReturn(mockTaskAttachments); + when(taskServiceMock.createAttachment(any(), any(), any(), any(), any(), Mockito.any())).thenReturn(mockTaskAttachment); + when(taskServiceMock.createAttachment(any(), any(), any(), any(), any(), Mockito.any())).thenReturn(mockTaskAttachment); + when(taskServiceMock.getTaskAttachmentContent(EXAMPLE_TASK_ID, EXAMPLE_TASK_ATTACHMENT_ID)).thenReturn(new ByteArrayInputStream(createMockByteData())); + + ObjectValue localVariableValue = MockObjectValue.fromObjectValue( + Variables.objectValue(LOCAL_VARIABLE_PAYLOAD).serializationDataFormat("application/json").create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); + + when(taskServiceMock.getVariablesLocalTyped(EXAMPLE_TASK_ID, true)).thenReturn( + Variables.createVariables().putValueTyped(LOCAL_VARIABLE_KEY, localVariableValue)); + when(taskServiceMock.getVariablesTyped(EXAMPLE_TASK_ID, true)).thenReturn(EXAMPLE_VARIABLES); + + formServiceMock = mock(FormService.class); + when(processEngine.getFormService()).thenReturn(formServiceMock); + TaskFormData mockFormData = MockProvider.createMockTaskFormData(); + when(formServiceMock.getTaskFormData(any())).thenReturn(mockFormData); + when(formServiceMock.getTaskFormKey(any(), any())).thenReturn(MockProvider.EXAMPLE_FORM_KEY); + + VariableMap variablesMock = MockProvider.createMockFormVariables(); + when(formServiceMock.getTaskFormVariables(eq(EXAMPLE_TASK_ID), Mockito.any(), anyBoolean())).thenReturn(variablesMock); + + repositoryServiceMock = mock(RepositoryService.class); + when(processEngine.getRepositoryService()).thenReturn(repositoryServiceMock); + ProcessDefinition mockDefinition = MockProvider.createMockDefinition(); + when(repositoryServiceMock.getProcessDefinition(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(mockDefinition); + + managementServiceMock = mock(ManagementService.class); + when(processEngine.getManagementService()).thenReturn(managementServiceMock); + when(managementServiceMock.getProcessApplicationForDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID)).thenReturn(MockProvider.EXAMPLE_PROCESS_APPLICATION_NAME); + when(managementServiceMock.getHistoryLevel()).thenReturn(ProcessEngineConfigurationImpl.HISTORYLEVEL_FULL); + + HistoryService historyServiceMock = mock(HistoryService.class); + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + historicTaskInstanceQueryMock = mock(HistoricTaskInstanceQuery.class); + when(historyServiceMock.createHistoricTaskInstanceQuery()).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.taskId(eq(EXAMPLE_TASK_ID))).thenReturn(historicTaskInstanceQueryMock); + HistoricTaskInstance historicTaskInstanceMock = createMockHistoricTaskInstance(); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(historicTaskInstanceMock); + + // replace the runtime container delegate & process application service with a mock + + ProcessApplicationService processApplicationService = mock(ProcessApplicationService.class); + ProcessApplicationInfo appMock = MockProvider.createMockProcessApplicationInfo(); + when(processApplicationService.getProcessApplicationInfo(MockProvider.EXAMPLE_PROCESS_APPLICATION_NAME)).thenReturn(appMock); + + RuntimeContainerDelegate delegate = mock(RuntimeContainerDelegate.class); + when(delegate.getProcessApplicationService()).thenReturn(processApplicationService); + RuntimeContainerDelegate.INSTANCE.set(delegate); + } + + public void mockHistoryDisabled() { + when(managementServiceMock.getHistoryLevel()).thenReturn(ProcessEngineConfigurationImpl.HISTORYLEVEL_NONE); + } + + private byte[] createMockByteData() { + return "someContent".getBytes(); + } + + @Test + public void testGetSingleTask() { + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_TASK_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("created", equalTo(MockProvider.EXAMPLE_TASK_CREATE_TIME)) + .body("due", equalTo(MockProvider.EXAMPLE_TASK_DUE_DATE)) + .body("delegationState", equalTo(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString())) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("executionId", equalTo(MockProvider.EXAMPLE_TASK_EXECUTION_ID)) + .body("owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_TASK_PRIORITY)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("suspended", equalTo(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE)) + .body("caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("lastUpdated", equalTo(MockProvider.EXAMPLE_TASK_LAST_UPDATED)) + .body("taskState", equalTo(MockProvider.EXAMPLE_HISTORIC_TASK_STATE)) + .body("variables", equalTo(null)) + .body("attachment", equalTo(null)) + .body("comment", equalTo(null)) + .when().get(SINGLE_TASK_URL); + } + @Test + public void testGetSingleTaskWithCommentAttachment() { + given().pathParam("id", EXAMPLE_TASK_ID) + .queryParam("withCommentAttachmentInfo", true) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_TASK_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("created", equalTo(MockProvider.EXAMPLE_TASK_CREATE_TIME)) + .body("due", equalTo(MockProvider.EXAMPLE_TASK_DUE_DATE)) + .body("delegationState", equalTo(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString())) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("executionId", equalTo(MockProvider.EXAMPLE_TASK_EXECUTION_ID)) + .body("owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_TASK_PRIORITY)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("suspended", equalTo(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE)) + .body("caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("lastUpdated", equalTo(MockProvider.EXAMPLE_TASK_LAST_UPDATED)) + .body("attachment", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_STATE)) + .body("comment", equalTo(MockProvider.EXAMPLE_TASK_COMMENT_STATE)) + .body("variables", equalTo(null)) + .when().get(SINGLE_TASK_URL); + } + + @Test + public void testGetSingleTaskWithTaskVariablesInReturn() { + given().pathParam("id", EXAMPLE_TASK_ID) + .queryParam("withTaskVariablesInReturn", true) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_TASK_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("created", equalTo(MockProvider.EXAMPLE_TASK_CREATE_TIME)) + .body("due", equalTo(MockProvider.EXAMPLE_TASK_DUE_DATE)) + .body("delegationState", equalTo(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString())) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("executionId", equalTo(MockProvider.EXAMPLE_TASK_EXECUTION_ID)) + .body("owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_TASK_PRIORITY)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("suspended", equalTo(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE)) + .body("caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("lastUpdated", equalTo(MockProvider.EXAMPLE_TASK_LAST_UPDATED)) + .body("variables", notNullValue()) + .body("variables" + "." + EXAMPLE_VARIABLE_KEY, notNullValue()) + .body("variables" + "." + EXAMPLE_VARIABLE_KEY + ".type", + equalTo(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) + .body("variables" + "." + EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body("attachment", equalTo(null)) + .body("comment", equalTo(null)) + .when().get(SINGLE_TASK_URL); + } + + @Test + public void testGetSingleTaskWithTaskLocalVariablesInReturn() { + given().pathParam("id", EXAMPLE_TASK_ID) + .queryParam("withTaskLocalVariablesInReturn", true) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_TASK_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("created", equalTo(MockProvider.EXAMPLE_TASK_CREATE_TIME)) + .body("due", equalTo(MockProvider.EXAMPLE_TASK_DUE_DATE)) + .body("delegationState", equalTo(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString())) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("executionId", equalTo(MockProvider.EXAMPLE_TASK_EXECUTION_ID)) + .body("owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_TASK_PRIORITY)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("suspended", equalTo(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE)) + .body("caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("lastUpdated", equalTo(MockProvider.EXAMPLE_TASK_LAST_UPDATED)) + .body("variables", notNullValue()) + .body("variables" + "." + LOCAL_VARIABLE_KEY, notNullValue()) + .body("variables" + "." + LOCAL_VARIABLE_KEY + ".type", equalTo("Object")) + .body("variables" + "." + LOCAL_VARIABLE_KEY + ".value", equalTo(LOCAL_VARIABLE_PAYLOAD)) + .body("variables" + "." + LOCAL_VARIABLE_KEY + ".valueInfo." + + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, CoreMatchers.equalTo("application/json")) + .body( + "variables" + "." + LOCAL_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, + CoreMatchers.equalTo(ArrayList.class.getName())) + .body("attachment", equalTo(null)) + .body("comment", equalTo(null)) + .when().get(SINGLE_TASK_URL); + } + + @Test + public void testGetSingleTaskWithTaskVariablesCommentsAndAttachments() { + given().pathParam("id", EXAMPLE_TASK_ID) + .queryParam("withTaskVariablesInReturn", true) + .queryParam("withCommentAttachmentInfo", true) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_TASK_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("created", equalTo(MockProvider.EXAMPLE_TASK_CREATE_TIME)) + .body("due", equalTo(MockProvider.EXAMPLE_TASK_DUE_DATE)) + .body("delegationState", equalTo(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString())) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("executionId", equalTo(MockProvider.EXAMPLE_TASK_EXECUTION_ID)) + .body("owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_TASK_PRIORITY)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("suspended", equalTo(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE)) + .body("caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("lastUpdated", equalTo(MockProvider.EXAMPLE_TASK_LAST_UPDATED)) + .body("attachment", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_STATE)) + .body("comment", equalTo(MockProvider.EXAMPLE_TASK_COMMENT_STATE)) + .body("variables", notNullValue()) + .body("variables" + "." + EXAMPLE_VARIABLE_KEY, notNullValue()) + .body("variables" + "." + EXAMPLE_VARIABLE_KEY + ".type", + equalTo(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) + .body("variables" + "." + EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .when().get(SINGLE_TASK_URL); + } + + @Test + public void testGetSingleTaskWithTaskLocalVariablesCommentsAndAttachments() { + given().pathParam("id", EXAMPLE_TASK_ID) + .queryParam("withTaskLocalVariablesInReturn", true) + .queryParam("withCommentAttachmentInfo", true) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_TASK_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("created", equalTo(MockProvider.EXAMPLE_TASK_CREATE_TIME)) + .body("due", equalTo(MockProvider.EXAMPLE_TASK_DUE_DATE)) + .body("delegationState", equalTo(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString())) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("executionId", equalTo(MockProvider.EXAMPLE_TASK_EXECUTION_ID)) + .body("owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_TASK_PRIORITY)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("suspended", equalTo(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE)) + .body("caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("lastUpdated", equalTo(MockProvider.EXAMPLE_TASK_LAST_UPDATED)) + .body("attachment", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_STATE)) + .body("comment", equalTo(MockProvider.EXAMPLE_TASK_COMMENT_STATE)) + .body("variables", notNullValue()) + .body("variables" + "." + LOCAL_VARIABLE_KEY, notNullValue()) + .body("variables" + "." + LOCAL_VARIABLE_KEY + ".type", equalTo("Object")) + .body("variables" + "." + LOCAL_VARIABLE_KEY + ".value", equalTo(LOCAL_VARIABLE_PAYLOAD)) + .body("variables" + "." + LOCAL_VARIABLE_KEY + ".valueInfo." + + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, CoreMatchers.equalTo("application/json")) + .body( + "variables" + "." + LOCAL_VARIABLE_KEY + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, + CoreMatchers.equalTo(ArrayList.class.getName())) + .body("variables" + "." + EXAMPLE_VARIABLE_KEY, nullValue()) + .when().get(SINGLE_TASK_URL); + } + + @Test + @SuppressWarnings("unchecked") + public void testGetSingleTaskHal() { + + // setup user query mock + List mockUsers = Arrays.asList( + MockProvider.mockUser().id(EXAMPLE_TASK_ASSIGNEE_NAME).build(), + MockProvider.mockUser().id(EXAMPLE_TASK_OWNER).build() + ); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(sampleUserQuery.userIdIn(eq(EXAMPLE_TASK_ASSIGNEE_NAME), eq(EXAMPLE_TASK_OWNER))).thenReturn(sampleUserQuery); + when(sampleUserQuery.userIdIn(eq(EXAMPLE_TASK_OWNER), eq(EXAMPLE_TASK_ASSIGNEE_NAME))).thenReturn(sampleUserQuery); + when(sampleUserQuery.listPage(eq(0), eq(2))).thenReturn(mockUsers); + when(sampleUserQuery.count()).thenReturn((long) mockUsers.size()); + when(processEngine.getIdentityService().createUserQuery()).thenReturn(sampleUserQuery); + + // setup group query mock + List mockGroups = Arrays.asList( + MockProvider.mockGroup().id(mockCandidateGroupIdentityLink.getGroupId()).build(), + MockProvider.mockGroup().id(mockCandidateGroup2IdentityLink.getGroupId()).build() + ); + GroupQuery sampleGroupQuery = mock(GroupQuery.class); + when(sampleGroupQuery.groupIdIn(eq(EXAMPLE_GROUP_ID), eq(EXAMPLE_GROUP_ID2))).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.groupIdIn(eq(EXAMPLE_GROUP_ID2), eq(EXAMPLE_GROUP_ID))).thenReturn(sampleGroupQuery); + when(sampleGroupQuery.listPage(eq(0), eq(2))).thenReturn(mockGroups); + when(sampleGroupQuery.count()).thenReturn((long) mockGroups.size()); + when(processEngine.getIdentityService().createGroupQuery()).thenReturn(sampleGroupQuery); + + // setup process definition query mock + List mockDefinitions = MockProvider.createMockDefinitions(); + ProcessDefinitionQuery sampleProcessDefinitionQuery = mock(ProcessDefinitionQuery.class); + when(sampleProcessDefinitionQuery.listPage(0, 1)).thenReturn(mockDefinitions); + when(sampleProcessDefinitionQuery.processDefinitionIdIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(sampleProcessDefinitionQuery); + when(sampleProcessDefinitionQuery.count()).thenReturn(1l); + when(processEngine.getRepositoryService().createProcessDefinitionQuery()).thenReturn(sampleProcessDefinitionQuery); + + // setup case definition query mock + List mockCaseDefinitions = MockProvider.createMockCaseDefinitions(); + CaseDefinitionQuery sampleCaseDefinitionQuery = mock(CaseDefinitionQuery.class); + when(sampleCaseDefinitionQuery.listPage(0, 1)).thenReturn(mockCaseDefinitions); + when(sampleCaseDefinitionQuery.caseDefinitionIdIn(MockProvider.EXAMPLE_CASE_DEFINITION_ID)).thenReturn(sampleCaseDefinitionQuery); + when(sampleCaseDefinitionQuery.count()).thenReturn(1l); + when(processEngine.getRepositoryService().createCaseDefinitionQuery()).thenReturn(sampleCaseDefinitionQuery); + + Response response = given() + .header("accept", Hal.APPLICATION_HAL_JSON) + .pathParam("id", EXAMPLE_TASK_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(EXAMPLE_TASK_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_NAME)) + .body("assignee", equalTo(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("created", equalTo(MockProvider.EXAMPLE_TASK_CREATE_TIME)) + .body("due", equalTo(MockProvider.EXAMPLE_TASK_DUE_DATE)) + .body("delegationState", equalTo(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString())) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_DESCRIPTION)) + .body("executionId", equalTo(MockProvider.EXAMPLE_TASK_EXECUTION_ID)) + .body("owner", equalTo(MockProvider.EXAMPLE_TASK_OWNER)) + .body("parentTaskId", equalTo(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID)) + .body("priority", equalTo(MockProvider.EXAMPLE_TASK_PRIORITY)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("taskDefinitionKey", equalTo(MockProvider.EXAMPLE_TASK_DEFINITION_KEY)) + .body("suspended", equalTo(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE)) + .body("caseExecutionId", equalTo(MockProvider.EXAMPLE_CASE_EXECUTION_ID)) + .body("caseInstanceId", equalTo(MockProvider.EXAMPLE_CASE_INSTANCE_ID)) + .body("caseDefinitionId", equalTo(MockProvider.EXAMPLE_CASE_DEFINITION_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + + // links + .body("_links.assignee.href", endsWith(EXAMPLE_TASK_ASSIGNEE_NAME)) + .body("_links.caseDefinition.href", endsWith(EXAMPLE_CASE_DEFINITION_ID)) + .body("_links.caseExecution.href", endsWith(EXAMPLE_CASE_EXECUTION_ID)) + .body("_links.caseInstance.href", endsWith(EXAMPLE_CASE_INSTANCE_ID)) + .body("_links.execution.href", endsWith(EXAMPLE_TASK_EXECUTION_ID)) + .body("_links.owner.href", endsWith(EXAMPLE_TASK_OWNER)) + .body("_links.parentTask.href", endsWith(EXAMPLE_TASK_PARENT_TASK_ID)) + .body("_links.processDefinition.href", endsWith(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("_links.processInstance.href", endsWith(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("_links.identityLink.href", endsWith("/task/" + EXAMPLE_TASK_ID + "/identity-links")) + .body("_links.self.href", endsWith(EXAMPLE_TASK_ID)) + + .when().get(SINGLE_TASK_URL); + + String content = response.asString(); + + // validate embedded users: + List> embeddedUsers = from(content).getList("_embedded.user"); + Assert.assertEquals("There should be two users returned.", 2, embeddedUsers.size()); + + Map embeddedUser = embeddedUsers.get(0); + assertNotNull("The returned user should not be null.", embeddedUser); + assertEquals(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME, embeddedUser.get("id")); + assertEquals(MockProvider.EXAMPLE_USER_FIRST_NAME, embeddedUser.get("firstName")); + assertEquals(MockProvider.EXAMPLE_USER_LAST_NAME, embeddedUser.get("lastName")); + assertEquals(MockProvider.EXAMPLE_USER_EMAIL, embeddedUser.get("email")); + assertNull(embeddedUser.get("_embedded")); + Map links = (Map) embeddedUser.get("_links"); + assertEquals(1, links.size()); + assertHalLink(links, "self", UserRestService.PATH + "/" + MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME); + + embeddedUser = embeddedUsers.get(1); + assertNotNull("The returned user should not be null.", embeddedUser); + assertEquals(MockProvider.EXAMPLE_TASK_OWNER, embeddedUser.get("id")); + assertEquals(MockProvider.EXAMPLE_USER_FIRST_NAME, embeddedUser.get("firstName")); + assertEquals(MockProvider.EXAMPLE_USER_LAST_NAME, embeddedUser.get("lastName")); + assertEquals(MockProvider.EXAMPLE_USER_EMAIL, embeddedUser.get("email")); + assertNull(embeddedUser.get("_embedded")); + links = (Map) embeddedUser.get("_links"); + assertEquals(1, links.size()); + assertHalLink(links, "self", UserRestService.PATH + "/" + MockProvider.EXAMPLE_TASK_OWNER); + + // validate embedded groups: + List> embeddedGroups = from(content).getList("_embedded.group"); + Assert.assertEquals("There should be two groups returned.", 2, embeddedGroups.size()); + + Map embeddedGroup = embeddedGroups.get(0); + assertNotNull("The returned group should not be null.", embeddedGroup); + assertEquals(MockProvider.EXAMPLE_GROUP_ID, embeddedGroup.get("id")); + assertEquals(MockProvider.EXAMPLE_GROUP_NAME, embeddedGroup.get("name")); + assertEquals(MockProvider.EXAMPLE_GROUP_TYPE, embeddedGroup.get("type")); + assertNull(embeddedGroup.get("_embedded")); + links = (Map) embeddedGroup.get("_links"); + assertEquals(1, links.size()); + assertHalLink(links, "self", GroupRestService.PATH + "/" + MockProvider.EXAMPLE_GROUP_ID); + + embeddedGroup = embeddedGroups.get(1); + assertNotNull("The returned group should not be null.", embeddedGroup); + assertEquals(MockProvider.EXAMPLE_GROUP_ID2, embeddedGroup.get("id")); + assertEquals(MockProvider.EXAMPLE_GROUP_NAME, embeddedGroup.get("name")); + assertEquals(MockProvider.EXAMPLE_GROUP_TYPE, embeddedGroup.get("type")); + assertNull(embeddedGroup.get("_embedded")); + links = (Map) embeddedGroup.get("_links"); + assertEquals(1, links.size()); + assertHalLink(links, "self", GroupRestService.PATH + "/" + MockProvider.EXAMPLE_GROUP_ID2); + + // validate embedded processDefinitions: + List> embeddedDefinitions = from(content).getList("_embedded.processDefinition"); + Assert.assertEquals("There should be one processDefinition returned.", 1, embeddedDefinitions.size()); + Map embeddedProcessDefinition = embeddedDefinitions.get(0); + Assert.assertNotNull("The returned processDefinition should not be null.", embeddedProcessDefinition); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, embeddedProcessDefinition.get("id")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, embeddedProcessDefinition.get("key")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY, embeddedProcessDefinition.get("category")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME, embeddedProcessDefinition.get("name")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_DESCRIPTION, embeddedProcessDefinition.get("description")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION, embeddedProcessDefinition.get("version")); + Assert.assertEquals(MockProvider.EXAMPLE_VERSION_TAG, embeddedProcessDefinition.get("versionTag")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME, embeddedProcessDefinition.get("resource")); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, embeddedProcessDefinition.get("deploymentId")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME, embeddedProcessDefinition.get("diagram")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED, embeddedProcessDefinition.get("suspended")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH, embeddedProcessDefinition.get("contextPath")); + + links = (Map) embeddedProcessDefinition.get("_links"); + Assert.assertEquals(3, links.size()); + assertHalLink(links, "self", "/process-definition/" + MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + assertHalLink(links, "deployment", "/deployment/" + MockProvider.EXAMPLE_DEPLOYMENT_ID); + assertHalLink(links, "resource", "/deployment/" + MockProvider.EXAMPLE_DEPLOYMENT_ID + "/resources/" + + MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME); + + + // validate embedded caseDefinitions: + List> embeddedCaseDefinitions = from(content).getList("_embedded.caseDefinition"); + Assert.assertEquals("There should be one caseDefinition returned.", 1, embeddedCaseDefinitions.size()); + Map embeddedCaseDefinition = embeddedCaseDefinitions.get(0); + Assert.assertNotNull("The returned caseDefinition should not be null.", embeddedCaseDefinition); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, embeddedCaseDefinition.get("id")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_KEY, embeddedCaseDefinition.get("key")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_CATEGORY, embeddedCaseDefinition.get("category")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_NAME, embeddedCaseDefinition.get("name")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_VERSION, embeddedCaseDefinition.get("version")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_RESOURCE_NAME, embeddedCaseDefinition.get("resource")); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, embeddedCaseDefinition.get("deploymentId")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH, embeddedCaseDefinition.get("contextPath")); + + links = (Map) embeddedCaseDefinition.get("_links"); + Assert.assertEquals(3, links.size()); + assertHalLink(links, "self", "/case-definition/" + MockProvider.EXAMPLE_CASE_DEFINITION_ID); + assertHalLink(links, "deployment", "/deployment/" + MockProvider.EXAMPLE_DEPLOYMENT_ID); + assertHalLink(links, "resource", "/deployment/" + MockProvider.EXAMPLE_DEPLOYMENT_ID + "/resources/" + + MockProvider.EXAMPLE_CASE_DEFINITION_RESOURCE_NAME); + + // validate embedded identity links + List> embeddedIdentityLinks = from(content).getList("_embedded.identityLink"); + assertEquals("There should be three identityLink returned", 4, embeddedIdentityLinks.size()); + assertEmbeddedIdentityLink(mockAssigneeIdentityLink, embeddedIdentityLinks.get(0)); + assertEmbeddedIdentityLink(mockOwnerIdentityLink, embeddedIdentityLinks.get(1)); + assertEmbeddedIdentityLink(mockCandidateGroupIdentityLink, embeddedIdentityLinks.get(2)); + assertEmbeddedIdentityLink(mockCandidateGroup2IdentityLink, embeddedIdentityLinks.get(3)); + + } + + @SuppressWarnings("unchecked") + protected void assertHalLink(Map links, String key, String expectedLink) { + Map linkObject = (Map) links.get(key); + Assert.assertNotNull(linkObject); + + String actualLink = (String) linkObject.get("href"); + Assert.assertEquals(expectedLink, actualLink); + } + + @SuppressWarnings("unchecked") + protected void assertEmbeddedIdentityLink(IdentityLink expected, Map actual) { + assertNotNull("Embedded indentity link should not be null", actual); + assertEquals(expected.getType(), actual.get("type")); + assertEquals(expected.getUserId(), actual.get("userId")); + assertEquals(expected.getGroupId(), actual.get("groupId")); + assertEquals(expected.getTaskId(), actual.get("taskId")); + assertNull(actual.get("_embedded")); + + Map links = (Map) actual.get("_links"); + if (expected.getUserId() != null) { + assertHalLink(links, "user", UserRestService.PATH + "/" + expected.getUserId()); + } + if (expected.getGroupId() != null) { + assertHalLink(links, "group", GroupRestService.PATH + "/" + expected.getGroupId()); + } + if (expected.getTaskId() != null) { + assertHalLink(links, "task", TaskRestService.PATH + "/" + expected.getTaskId()); + } + } + + @Test + public void testGetForm() { + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("key", equalTo(MockProvider.EXAMPLE_FORM_KEY)) + .body("camundaFormRef", nullValue()) + .body("contextPath", equalTo(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH)) + .when().get(TASK_FORM_URL); + } + + @Test + public void testGetTaskshouldContainCamundaFormRef() { + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("camundaFormRef.key", equalTo(MockProvider.EXAMPLE_FORM_KEY)) + .body("camundaFormRef.binding", equalTo(MockProvider.EXAMPLE_FORM_REF_BINDING)) + .body("camundaFormRef.version", equalTo(MockProvider.EXAMPLE_FORM_REF_VERSION)) + .body("key", nullValue()) + .when().get(SINGLE_TASK_URL); + } + + /** + * Assuming the task belongs to a deployment that does not belong to any process application + */ + @Test + public void testGetFormForNonRegisteredDeployment() { + when(managementServiceMock.getProcessApplicationForDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID)).thenReturn(null); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("key", equalTo(MockProvider.EXAMPLE_FORM_KEY)) + .body("contextPath", nullValue()) + .when().get(TASK_FORM_URL); + } + + @Test + public void testGetForm_shouldReturnFormRef() { + TaskFormData mockTaskFormData = MockProvider.createMockTaskFormDataUsingFormRef(); + when(formServiceMock.getTaskFormData(EXAMPLE_TASK_ID)).thenReturn(mockTaskFormData); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("camundaFormRef.key", equalTo(MockProvider.EXAMPLE_FORM_KEY)) + .body("camundaFormRef.binding", equalTo(MockProvider.EXAMPLE_FORM_REF_BINDING)) + .body("camundaFormRef.version", equalTo(MockProvider.EXAMPLE_FORM_REF_VERSION)) + .body("key", nullValue()) + .body("contextPath", equalTo(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH)) + .when().get(TASK_FORM_URL); + } + + /** + * Assuming that the task belongs to no process definition + */ + @Test + public void getFormForIndependentTask() { + when(mockTask.getProcessDefinitionId()).thenReturn(null); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("key", equalTo(MockProvider.EXAMPLE_FORM_KEY)) + .body("contextPath", nullValue()) + .when().get(TASK_FORM_URL); + + verify(repositoryServiceMock, never()).getProcessDefinition(null); + } + + @Test + public void testGetForm_shouldReturnKeyContainingTaskId() { + TaskFormData mockTaskFormData = MockProvider.createMockTaskFormDataUsingFormFieldsWithoutFormKey(); + when(formServiceMock.getTaskFormData(EXAMPLE_TASK_ID)).thenReturn(mockTaskFormData); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("key", equalTo("embedded:engine://engine/:engine/task/" + EXAMPLE_TASK_ID + "/rendered-form")) + .body("contextPath", equalTo(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH)) + .when().get(TASK_FORM_URL); + } + + @Test + public void testGetForm__FormDataEqualsNull() { + when(formServiceMock.getTaskFormData(EXAMPLE_TASK_ID)).thenReturn(null); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("contextPath", equalTo(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH)) + .when().get(TASK_FORM_URL); + } + + @Test + public void testGetFormThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(formServiceMock).getTaskFormData(anyString()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(TASK_FORM_URL); + } + + @Test + public void testGetRenderedForm() { + String expectedResult = "anyContent"; + + when(formServiceMock.getRenderedTaskForm(EXAMPLE_TASK_ID)).thenReturn(expectedResult); + + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(XHTML_XML_CONTENT_TYPE) + .when() + .get(RENDERED_FORM_URL); + + String responseContent = response.asString(); + Assertions.assertThat(responseContent).isEqualTo(expectedResult); + } + + @Test + public void testGetRenderedFormForDifferentPlatformEncoding() throws NoSuchFieldException, IllegalAccessException, UnsupportedEncodingException { + String expectedResult = "unicode symbol: \u2200"; + when(formServiceMock.getRenderedTaskForm(MockProvider.EXAMPLE_TASK_ID)).thenReturn(expectedResult); + + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(XHTML_XML_CONTENT_TYPE) + .when() + .get(RENDERED_FORM_URL); + + String responseContent = new String(response.asByteArray(), EncodingUtil.DEFAULT_ENCODING); + Assertions.assertThat(responseContent).isEqualTo(expectedResult); + } + + @Test + public void testGetRenderedFormReturnsNotFound() { + when(formServiceMock.getRenderedTaskForm(anyString(), anyString())).thenReturn(null); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No matching rendered form for task with the id " + EXAMPLE_TASK_ID + " found.")) + .when() + .get(RENDERED_FORM_URL); + } + + @Test + public void testGetRenderedFormThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(formServiceMock).getRenderedTaskForm(anyString()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(RENDERED_FORM_URL); + } + + @Test + public void testSubmitForm() { + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SUBMIT_FORM_URL); + + verify(formServiceMock).submitTaskForm(EXAMPLE_TASK_ID, null); + } + + @Test + public void testSubmitFormWithVariablesInReturn() { + VariableMap variables = MockProvider.createMockSerializedVariables(); + when(formServiceMock.submitTaskFormWithVariablesInReturn(EXAMPLE_TASK_ID, null, false)).thenReturn(variables); + + Map queryParameters = new HashMap<>(); + queryParameters.put("withVariablesInReturn", true); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + //serialized variable + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(ArrayList.class.getName())) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + // deserialized variable should also returned as serialized variable + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(Object.class.getName())) + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + .when().post(SUBMIT_FORM_URL); + + verify(formServiceMock).submitTaskFormWithVariablesInReturn(EXAMPLE_TASK_ID, null, false); + } + + @Test + public void testSubmitFormWithParameters() { + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("anotherVariable", 42) + .variable("aThirdValue", Boolean.TRUE).getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SUBMIT_FORM_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aVariable", "aStringValue"); + expectedVariables.put("anotherVariable", 42); + expectedVariables.put("aThirdValue", Boolean.TRUE); + + verify(formServiceMock).submitTaskForm(eq(EXAMPLE_TASK_ID), argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testSubmitTaskFormWithBase64EncodedBytes() { + Map variables = VariablesBuilder.create() + .variable("aVariable", Base64.encodeBase64String("someBytes".getBytes()), "Bytes") + .getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SUBMIT_FORM_URL); + + verify(formServiceMock).submitTaskForm(eq(EXAMPLE_TASK_ID), argThat(new EqualsMap() + .matcher("aVariable", EqualsPrimitiveValue.bytesValue("someBytes".getBytes())))); + } + + @SuppressWarnings({ "unchecked" }) + @Test + public void testSubmitTaskFormWithFileValue() { + String variableKey = "aVariable"; + String filename = "test.txt"; + Map variables = VariablesBuilder.create().variable(variableKey, Base64.encodeBase64String("someBytes".getBytes()), "File") + .getVariables(); + ((Map)variables.get(variableKey)).put("valueInfo", Collections.singletonMap("filename", filename)); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SUBMIT_FORM_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(VariableMap.class); + verify(formServiceMock).submitTaskForm(eq(EXAMPLE_TASK_ID), captor.capture()); + VariableMap map = captor.getValue(); + FileValue fileValue = (FileValue) map.getValueTyped(variableKey); + assertThat(fileValue).isNotNull(); + assertThat(fileValue.getFilename()).isEqualTo(filename); + assertThat(IoUtil.readInputStream(fileValue.getValue(), null)).isEqualTo("someBytes".getBytes()); + } + + @Test + public void testSubmitFormWithUnparseableIntegerVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot submit task form anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormWithUnparseableShortVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot submit task form anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormWithUnparseableLongVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot submit task form anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormWithUnparseableDoubleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot submit task form anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormWithUnparseableDateVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot submit task form anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void shouldReturnErrorOnSubmitTaskForm() { + doThrow(new ProcessEngineException("foo", 123)) + .when(formServiceMock).submitTaskForm(anyString(), Mockito.any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body("{}") + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot submit task form anId: foo")) + .body("code", equalTo(123)) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormWithNotSupportedVariableType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot submit task form anId: Unsupported value type 'X'")) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testUnsuccessfulSubmitForm() { + doThrow(new ProcessEngineException("expected exception")).when(formServiceMock).submitTaskForm(any(String.class), Mockito.any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot submit task form " + EXAMPLE_TASK_ID + ": expected exception")) + .when().post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitFormThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(formServiceMock).submitTaskForm(anyString(), Mockito.any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SUBMIT_FORM_URL); + } + + @Test + public void testSubmitTaskFormThrowsFormFieldValidationException() { + String message = "expected exception"; + doThrow(new FormFieldValidationException("form-exception", message)).when(formServiceMock).submitTaskForm(anyString(), Mockito.any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot submit task form " + EXAMPLE_TASK_ID + ": " + message)) + .when() + .post(SUBMIT_FORM_URL); + } + + + @Test + public void testGetTaskFormVariables() { + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".type", + equalTo(VariableTypeHelper.toExpectedValueTypeName(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getType()))) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".value", + equalTo(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .when().get(FORM_VARIABLES_URL) + .body(); + + verify(formServiceMock, times(1)).getTaskFormVariables(EXAMPLE_TASK_ID, null, true); + } + + @Test + public void testGetTaskFormVariablesVarNames() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .queryParam("variableNames", "a,b,c") + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .when().get(FORM_VARIABLES_URL); + + verify(formServiceMock, times(1)).getTaskFormVariables(EXAMPLE_TASK_ID, Arrays.asList("a", "b", "c"), true); + } + + @Test + public void testGetTaskFormVariablesAndDoNotDeserializeVariables() { + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .queryParam("deserializeValues", false) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".type", + equalTo(VariableTypeHelper.toExpectedValueTypeName(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getType()))) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME+".value", + equalTo(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .when().get(FORM_VARIABLES_URL) + .body(); + + verify(formServiceMock, times(1)).getTaskFormVariables(EXAMPLE_TASK_ID, null, false); + } + + @Test + public void testGetTaskFormVariablesVarNamesAndDoNotDeserializeVariables() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .queryParam("deserializeValues", false) + .queryParam("variableNames", "a,b,c") + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .when().get(FORM_VARIABLES_URL); + + verify(formServiceMock, times(1)).getTaskFormVariables(EXAMPLE_TASK_ID, Arrays.asList("a", "b", "c"), false); + } + + @Test + public void testGetTaskFormVariablesThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(formServiceMock).getTaskFormVariables(anyString(), Mockito.any(), anyBoolean()); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(FORM_VARIABLES_URL); + } + + @Test + public void testClaimTask() { + Map json = new HashMap<>(); + json.put("userId", EXAMPLE_USER_ID); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(CLAIM_TASK_URL); + + verify(taskServiceMock).claim(EXAMPLE_TASK_ID, EXAMPLE_USER_ID); + } + + @Test + public void testMissingUserId() { + Map json = new HashMap<>(); + json.put("userId", null); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(CLAIM_TASK_URL); + + verify(taskServiceMock).claim(EXAMPLE_TASK_ID, null); + } + + @Test + public void testUnsuccessfulClaimTask() { + doThrow(new ProcessEngineException("expected exception")).when(taskServiceMock).claim(any(), any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when().post(CLAIM_TASK_URL); + } + + @Test + public void testClaimTaskThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).claim(any(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(CLAIM_TASK_URL); + } + + @Test + public void testUnclaimTask() { + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(UNCLAIM_TASK_URL); + + verify(taskServiceMock).setAssignee(EXAMPLE_TASK_ID, null); + } + + @Test + public void testUnsuccessfulUnclaimTask() { + doThrow(new ProcessEngineException("expected exception")).when(taskServiceMock).setAssignee(any(), any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when().post(UNCLAIM_TASK_URL); + } + + @Test + public void testUnclaimTaskThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).setAssignee(any(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(UNCLAIM_TASK_URL); + } + + @Test + public void testSetAssignee() { + Map json = new HashMap<>(); + json.put("userId", EXAMPLE_USER_ID); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(ASSIGNEE_TASK_URL); + + verify(taskServiceMock).setAssignee(EXAMPLE_TASK_ID, EXAMPLE_USER_ID); + } + + @Test + public void testMissingUserIdSetAssignee() { + Map json = new HashMap<>(); + json.put("userId", null); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(ASSIGNEE_TASK_URL); + + verify(taskServiceMock).setAssignee(EXAMPLE_TASK_ID, null); + } + + @Test + public void testUnsuccessfulSetAssignee() { + doThrow(new ProcessEngineException("expected exception")).when(taskServiceMock).setAssignee(any(), any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when().post(ASSIGNEE_TASK_URL); + } + + @Test + public void testSetAssigneeThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).setAssignee(any(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(ASSIGNEE_TASK_URL); + } + + protected Map toExpectedJsonMap(IdentityLink identityLink) { + Map result = new HashMap<>(); + result.put("userId", identityLink.getUserId()); + result.put("groupId", identityLink.getGroupId()); + result.put("type", identityLink.getType()); + return result; + } + + @Test + public void testGetIdentityLinks() { + Map expectedAssigneeIdentityLink = toExpectedJsonMap(mockAssigneeIdentityLink); + Map expectedOwnerIdentityLink = toExpectedJsonMap(mockOwnerIdentityLink); + Map expectedGroupIdentityLink = toExpectedJsonMap(mockCandidateGroupIdentityLink); + Map expectedGroupIdentityLink2 = toExpectedJsonMap(mockCandidateGroup2IdentityLink); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body("$.size()", equalTo(4)) + .body("$", hasItem(expectedAssigneeIdentityLink)) + .body("$", hasItem(expectedOwnerIdentityLink)) + .body("$", hasItem(expectedGroupIdentityLink)) + .body("$", hasItem(expectedGroupIdentityLink2)) + .when().get(TASK_IDENTITY_LINKS_URL); + + verify(taskServiceMock).getIdentityLinksForTask(EXAMPLE_TASK_ID); + } + + @Test + public void testGetIdentityLinksByType() { + Map expectedGroupIdentityLink = toExpectedJsonMap(mockCandidateGroupIdentityLink); + Map expectedGroupIdentityLink2 = toExpectedJsonMap(mockCandidateGroup2IdentityLink); + + given().pathParam("id", EXAMPLE_TASK_ID).queryParam("type", IdentityLinkType.CANDIDATE) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body("$.size()", equalTo(2)) + .body("$", hasItem(expectedGroupIdentityLink)) + .body("$", hasItem(expectedGroupIdentityLink2)) + .when().get(TASK_IDENTITY_LINKS_URL); + + verify(taskServiceMock).getIdentityLinksForTask(EXAMPLE_TASK_ID); + } + + @Test + public void testGetIdentityLinksThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).getIdentityLinksForTask(anyString()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(TASK_IDENTITY_LINKS_URL); + } + + @Test + public void testAddUserIdentityLink() { + String userId = "someUserId"; + String taskId = EXAMPLE_TASK_ID; + String type = "someType"; + + Map json = new HashMap<>(); + json.put("userId", userId); + json.put("taskId", taskId); + json.put("type", type); + + given().pathParam("id", taskId) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(TASK_IDENTITY_LINKS_URL); + + verify(taskServiceMock).addUserIdentityLink(taskId, userId, type); + } + + @Test + public void testAddGroupIdentityLink() { + String groupId = "someGroupId"; + String taskId = EXAMPLE_TASK_ID; + String type = "someType"; + + Map json = new HashMap<>(); + json.put("groupId", groupId); + json.put("taskId", taskId); + json.put("type", type); + + given().pathParam("id", taskId) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(TASK_IDENTITY_LINKS_URL); + + verify(taskServiceMock).addGroupIdentityLink(taskId, groupId, type); + } + + @Test + public void testInvalidAddIdentityLink() { + String groupId = "someGroupId"; + String userId = "someUserId"; + String taskId = EXAMPLE_TASK_ID; + String type = "someType"; + + Map json = new HashMap<>(); + json.put("groupId", groupId); + json.put("userId", userId); + json.put("taskId", taskId); + json.put("type", type); + + given().pathParam("id", taskId) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Identity Link requires userId or groupId, but not both")) + .when().post(TASK_IDENTITY_LINKS_URL); + + verify(taskServiceMock, never()).addGroupIdentityLink(anyString(), anyString(), anyString()); + verify(taskServiceMock, never()).addGroupIdentityLink(anyString(), anyString(), anyString()); + } + + @Test + public void testUnderspecifiedAddIdentityLink() { + String taskId = EXAMPLE_TASK_ID; + String type = "someType"; + + Map json = new HashMap<>(); + json.put("taskId", taskId); + json.put("type", type); + + given().pathParam("id", taskId) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Identity Link requires userId or groupId")) + .when().post(TASK_IDENTITY_LINKS_URL); + + verify(taskServiceMock, never()).addGroupIdentityLink(anyString(), anyString(), anyString()); + verify(taskServiceMock, never()).addGroupIdentityLink(anyString(), anyString(), anyString()); + } + + @Test + public void testAddGroupIdentityLinkThrowsAuthorizationException() { + String groupId = "someGroupId"; + String taskId = EXAMPLE_TASK_ID; + String type = "someType"; + + Map json = new HashMap<>(); + json.put("groupId", groupId); + json.put("taskId", taskId); + json.put("type", type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).addGroupIdentityLink(anyString(), anyString(), anyString()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(TASK_IDENTITY_LINKS_URL); + } + + @Test + public void testAddUserIdentityLinkThrowsAuthorizationException() { + String userId = "someUserId"; + String taskId = EXAMPLE_TASK_ID; + String type = "someType"; + + Map json = new HashMap<>(); + json.put("userId", userId); + json.put("taskId", taskId); + json.put("type", type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).addUserIdentityLink(anyString(), anyString(), anyString()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(TASK_IDENTITY_LINKS_URL); + } + + @Test + public void testDeleteUserIdentityLink() { + String deleteIdentityLinkUrl = TASK_IDENTITY_LINKS_URL + "/delete"; + + String taskId = EXAMPLE_TASK_ID; + String userId = EXAMPLE_USER_ID; + String type = "someIdentityLinkType"; + + Map json = new HashMap<>(); + json.put("userId", userId); + json.put("type", type); + + given().pathParam("id", taskId) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(deleteIdentityLinkUrl); + + verify(taskServiceMock).deleteUserIdentityLink(taskId, userId, type); + verify(taskServiceMock, never()).deleteGroupIdentityLink(anyString(), anyString(), anyString()); + } + + @Test + public void testDeleteGroupIdentityLink() { + String deleteIdentityLinkUrl = TASK_IDENTITY_LINKS_URL + "/delete"; + + String taskId = EXAMPLE_TASK_ID; + String groupId = MockProvider.EXAMPLE_GROUP_ID; + String type = "someIdentityLinkType"; + + Map json = new HashMap<>(); + json.put("groupId", groupId); + json.put("type", type); + + given().pathParam("id", taskId) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(deleteIdentityLinkUrl); + + verify(taskServiceMock).deleteGroupIdentityLink(taskId, groupId, type); + verify(taskServiceMock, never()).deleteUserIdentityLink(anyString(), anyString(), anyString()); + } + + @Test + public void testDeleteGroupIdentityLinkThrowsAuthorizationException() { + String deleteIdentityLinkUrl = TASK_IDENTITY_LINKS_URL + "/delete"; + + String taskId = EXAMPLE_TASK_ID; + String groupId = MockProvider.EXAMPLE_GROUP_ID; + String type = "someIdentityLinkType"; + + Map json = new HashMap<>(); + json.put("groupId", groupId); + json.put("type", type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).deleteGroupIdentityLink(anyString(), anyString(), anyString()); + + given() + .pathParam("id", taskId) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(deleteIdentityLinkUrl); + } + + @Test + public void testDeleteUserIdentityLinkThrowsAuthorizationException() { + String deleteIdentityLinkUrl = TASK_IDENTITY_LINKS_URL + "/delete"; + + String taskId = EXAMPLE_TASK_ID; + String userId = MockProvider.EXAMPLE_USER_ID; + String type = "someIdentityLinkType"; + + Map json = new HashMap<>(); + json.put("userId", userId); + json.put("type", type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).deleteUserIdentityLink(anyString(), anyString(), anyString()); + + given() + .pathParam("id", taskId) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(deleteIdentityLinkUrl); + } + + @Test + public void testCompleteTask() { + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(COMPLETE_TASK_URL); + + verify(taskServiceMock).complete(EXAMPLE_TASK_ID, null); + } + + @Test + public void testCompleteWithParameters() { + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("anotherVariable", 42) + .variable("aThirdValue", Boolean.TRUE).getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(COMPLETE_TASK_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aVariable", "aStringValue"); + expectedVariables.put("anotherVariable", 42); + expectedVariables.put("aThirdValue", Boolean.TRUE); + + verify(taskServiceMock).complete(eq(EXAMPLE_TASK_ID), argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testCompleteTaskWithVariablesInReturn() { + VariableMap variables = MockProvider.createMockSerializedVariables(); + when(taskServiceMock.completeWithVariablesInReturn(EXAMPLE_TASK_ID, null, false)).thenReturn(variables); + + Map json = new HashMap<>(); + json.put("withVariablesInReturn", Boolean.TRUE); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + //serialized variable + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(ArrayList.class.getName())) + .body(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + // deserialized variable should also returned as serialized variable + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".value", + equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE)) + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".type", + equalTo("Object")) + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.objectTypeName", + equalTo(Object.class.getName())) + .body(MockProvider.EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME + ".valueInfo.serializationDataFormat", + equalTo(MockProvider.FORMAT_APPLICATION_JSON)) + .when() + .post(COMPLETE_TASK_URL); + + verify(taskServiceMock).completeWithVariablesInReturn(EXAMPLE_TASK_ID, null, false); + } + + @Test + public void testCompleteWithUnparseableIntegerVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void testCompleteWithUnparseableShortVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void testCompleteWithUnparseableLongVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void testCompleteWithUnparseableDoubleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void testCompleteWithUnparseableDateVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void testCompleteWithNotSupportedVariableType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot complete task anId: Unsupported value type 'X'")) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void testUnsuccessfulCompleteTask() { + doThrow(new ProcessEngineException("expected exception")).when(taskServiceMock).complete(any(String.class), Mockito.any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot complete task " + EXAMPLE_TASK_ID + ": expected exception")) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void shouldReturnErrorOnCompletingTask() { + doThrow(new ProcessEngineException("foo", 123)) + .when(taskServiceMock).complete(any(String.class), Mockito.any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot complete task anId: foo")) + .body("code", equalTo(123)) + .when().post(COMPLETE_TASK_URL); + } + + @Test + public void testCompleteTaskThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).complete(anyString(), Mockito.any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(COMPLETE_TASK_URL); + } + + @Test + public void testResolveTask() { + Map variables = VariablesBuilder.create() + .variable("aVariable", "aStringValue") + .variable("anotherVariable", 42) + .variable("aThirdValue", Boolean.TRUE).getVariables(); + + Map json = new HashMap<>(); + json.put("variables", variables); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(RESOLVE_TASK_URL); + + Map expectedVariables = new HashMap<>(); + expectedVariables.put("aVariable", "aStringValue"); + expectedVariables.put("anotherVariable", 42); + expectedVariables.put("aThirdValue", Boolean.TRUE); + + verify(taskServiceMock).resolveTask(eq(EXAMPLE_TASK_ID), argThat(new EqualsMap(expectedVariables))); + } + + @Test + public void testResolveTaskWithUnparseableIntegerVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Integer"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot resolve task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Integer.class))) + .when().post(RESOLVE_TASK_URL); + } + + @Test + public void testResolveTaskWithUnparseableShortVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Short"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot resolve task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Short.class))) + .when().post(RESOLVE_TASK_URL); + } + + @Test + public void testResolveTaskWithUnparseableLongVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Long"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot resolve task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Long.class))) + .when().post(RESOLVE_TASK_URL); + } + + @Test + public void testResolveTaskWithUnparseableDoubleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Double"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot resolve task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Double.class))) + .when().post(RESOLVE_TASK_URL); + } + + @Test + public void testResolveTaskWithUnparseableDateVariable() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "Date"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot resolve task anId: " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, variableType, Date.class))) + .when().post(RESOLVE_TASK_URL); + } + + @Test + public void testResolveTaskWithNotSupportedVariableType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String variableType = "X"; + + Map variableJson = VariablesBuilder.create().variable(variableKey, variableValue, variableType).getVariables(); + + Map variables = new HashMap<>(); + variables.put("variables", variableJson); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(variables) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot resolve task anId: Unsupported value type 'X'")) + .when().post(RESOLVE_TASK_URL); + } + + @Test + public void testResolveTaskThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).resolveTask(anyString(), Mockito.any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(RESOLVE_TASK_URL); + } + + @Test + public void testUnsuccessfulResolving() { + doThrow(new ProcessEngineException("expected exception")).when(taskServiceMock).resolveTask(any(), any()); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when().post(RESOLVE_TASK_URL); + } + + @Test + public void testGetNonExistingTask() { + when(mockQuery.singleResult()).thenReturn(null); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("No matching task with id " + NON_EXISTING_ID)) + .when().get(SINGLE_TASK_URL); + } + + @Test + public void testGetNonExistingForm() { + when(formServiceMock.getTaskFormData(anyString())).thenThrow(new ProcessEngineException("Expected exception: task does not exist.")); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot get form for task " + NON_EXISTING_ID)) + .when().get(TASK_FORM_URL); + } + + @Test + public void testDelegateTask() { + Map json = new HashMap<>(); + json.put("userId", EXAMPLE_USER_ID); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(DELEGATE_TASK_URL); + + verify(taskServiceMock).delegateTask(EXAMPLE_TASK_ID, EXAMPLE_USER_ID); + } + + @Test + public void testUnsuccessfulDelegateTask() { + doThrow(new ProcessEngineException("expected exception")).when(taskServiceMock).delegateTask(any(String.class), any(String.class)); + + Map json = new HashMap<>(); + json.put("userId", EXAMPLE_USER_ID); + + given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("expected exception")) + .when().post(DELEGATE_TASK_URL); + } + + @Test + public void testDelegateTaskThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).delegateTask(any(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(DELEGATE_TASK_URL); + } + + @Test + public void testGetSingleTaskComment() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("id", equalTo(EXAMPLE_TASK_COMMENT_ID)) + .body("taskId", equalTo(EXAMPLE_TASK_ID)) + .body("userId", equalTo(EXAMPLE_USER_ID)) + .body("time", equalTo(EXAMPLE_TASK_COMMENT_TIME)) + .body("message", equalTo(EXAMPLE_TASK_COMMENT_FULL_MESSAGE)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("removalTime", equalTo(EXAMPLE_TASK_COMMENT_TIME)) + .body("rootProcessInstanceId", equalTo(EXAMPLE_TASK_COMMENT_ROOT_PROCESS_INSTANCE_ID)) + .when() + .get(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testGetSingleTaskCommentWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .get(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testGetSingleTaskCommentForNonExistingComment() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("commentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Task comment with id " + NON_EXISTING_ID + " does not exist for task id '" + EXAMPLE_TASK_ID + "'.")) + .when().get(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testGetSingleTaskCommentForNonExistingCommentWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("commentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when().get(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testGetSingleTaskCommentForNonExistingTask() { + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Task comment with id " + EXAMPLE_TASK_COMMENT_ID + " does not exist for task id '" + NON_EXISTING_ID + "'")) + .when() + .get(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testGetSingleTaskCommentForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .get(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testGetTaskComments() { + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(1)) + .when() + .get(SINGLE_TASK_COMMENTS_URL); + + verifyTaskComments(mockTaskComments, response); + verify(taskServiceMock).getTaskComments(EXAMPLE_TASK_ID); + } + + @Test + public void testGetTaskCommentsWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testGetTaskNonExistingComments() { + when(taskServiceMock.getTaskComments(EXAMPLE_TASK_ID)).thenReturn(Collections.emptyList()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testGetTaskNonExistingCommentsWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testGetTaskCommentsForNonExistingTask() { + when(historicTaskInstanceQueryMock.taskId(NON_EXISTING_ID)).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when() + .get(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testGetTaskCommentsForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testAddCompleteTaskComment() { + Map json = new HashMap<>(); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(SINGLE_TASK_ADD_COMMENT_URL); + + verify(taskServiceMock).createComment(EXAMPLE_TASK_ID, null, EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + verifyCreatedTaskComment(mockTaskComment, response); + } + + @Test + public void shouldAssignProcessInstanceIdToComment() { + when(taskServiceMock.createComment(EXAMPLE_TASK_ID, EXAMPLE_PROCESS_INSTANCE_ID, + EXAMPLE_TASK_COMMENT_FULL_MESSAGE)).thenReturn(mockTaskComment); + + Map json = new HashMap<>(); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + json.put("processInstanceId", EXAMPLE_PROCESS_INSTANCE_ID); + + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .post(SINGLE_TASK_ADD_COMMENT_URL); + + verify(taskServiceMock).createComment(EXAMPLE_TASK_ID, EXAMPLE_PROCESS_INSTANCE_ID, + EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + verifyCreatedTaskComment(mockTaskComment, response); + } + + @Test + public void testAddCompleteTaskCommentWithHistoryDisabled() { + + mockHistoryDisabled(); + + Map json = new HashMap<>(); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(ContentType.JSON) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .post(SINGLE_TASK_ADD_COMMENT_URL); + } + + @Test + public void testAddCommentToNonExistingTask() { + when(historicTaskInstanceQueryMock.taskId(eq(NON_EXISTING_ID))).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + Map json = new HashMap<>(); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + given() + .pathParam("id", NON_EXISTING_ID) + .contentType(ContentType.JSON) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when() + .post(SINGLE_TASK_ADD_COMMENT_URL); + } + + @Test + public void testAddCommentToNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + Map json = new HashMap<>(); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + given() + .pathParam("id", NON_EXISTING_ID) + .contentType(ContentType.JSON) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .post(SINGLE_TASK_ADD_COMMENT_URL); + } + + @Test + public void testAddTaskCommentWithoutBody() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode()) + .when() + .post(SINGLE_TASK_ADD_COMMENT_URL); + } + + @Test + public void testAddTaskCommentWithoutMessage() { + + doThrow(new ProcessEngineException("Message is null")).when(taskServiceMock).createComment(EXAMPLE_TASK_ID, null, null); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(ContentType.JSON) + .body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Not enough parameters submitted")) + .when() + .post(SINGLE_TASK_ADD_COMMENT_URL); + } + + @Test + public void testGetSingleTaskAttachment() { + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("attachmentId", MockProvider.EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body("id", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_ID)) + .body("taskId", equalTo(MockProvider.EXAMPLE_TASK_ID)) + .body("description", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_DESCRIPTION)) + .body("type", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_TYPE)) + .body("name", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_NAME)) + .body("url", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_URL)) + .body("createTime", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_CREATE_DATE)) + .body("removalTime", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_REMOVAL_DATE)) + .body("rootProcessInstanceId", equalTo(MockProvider.EXAMPLE_TASK_ATTACHMENT_ROOT_PROCESS_INSTANCE_ID)) + .when().get(SINGLE_TASK_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testGetSingleTaskAttachmentWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .get(SINGLE_TASK_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testGetSingleTaskAttachmentForNonExistingAttachmentId() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body(containsString("Task attachment with id " + NON_EXISTING_ID + " does not exist for task id '" + EXAMPLE_TASK_ID + "'.")) + .when().get(SINGLE_TASK_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testGetSingleTaskAttachmentForNonExistingAttachmentIdWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when().get(SINGLE_TASK_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testGetSingleTaskAttachmentForNonExistingTask() { + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Task attachment with id " + EXAMPLE_TASK_ATTACHMENT_ID + " does not exist for task id '" + NON_EXISTING_ID + "'")) + .when() + .get(SINGLE_TASK_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testGetSingleTaskAttachmentForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .get(SINGLE_TASK_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testGetTaskAttachments() { + Response response = given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body("$.size()", equalTo(1)) + .when().get(SINGLE_TASK_ATTACHMENTS_URL); + + verifyTaskAttachments(mockTaskAttachments, response); + verify(taskServiceMock).getTaskAttachments(MockProvider.EXAMPLE_TASK_ID); + } + + @Test + public void testGetTaskAttachmentsWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()).contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when().get(SINGLE_TASK_ATTACHMENTS_URL); + } + + @Test + public void testGetTaskAttachmentsForNonExistingTaskId() { + when(historicTaskInstanceQueryMock.taskId(NON_EXISTING_ID)).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when().get(SINGLE_TASK_ATTACHMENTS_URL); + } + + @Test + public void testGetTaskAttachmentsForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(SINGLE_TASK_ATTACHMENTS_URL); + } + + @Test + public void testGetTaskAttachmentsForNonExistingAttachments() { + when(taskServiceMock.getTaskAttachments(EXAMPLE_TASK_ID)).thenReturn(Collections.emptyList()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(SINGLE_TASK_ATTACHMENTS_URL); + } + + @Test + public void testGetTaskAttachmentsForNonExistingAttachmentsWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("$.size()", equalTo(0)) + .when() + .get(SINGLE_TASK_ATTACHMENTS_URL); + } + + @Test + public void testCreateCompleteTaskAttachmentWithContent() { + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .multiPart("attachment-name", EXAMPLE_TASK_ATTACHMENT_NAME) + .multiPart("attachment-description", EXAMPLE_TASK_ATTACHMENT_DESCRIPTION) + .multiPart("attachment-type", EXAMPLE_TASK_ATTACHMENT_TYPE) + .multiPart("content", createMockByteData()) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SINGLE_TASK_ADD_ATTACHMENT_URL); + + verifyCreatedTaskAttachment(mockTaskAttachment, response, false); + } + + @Test + public void testCreateTaskAttachmentWithContentToNonExistingTask() { + when(historicTaskInstanceQueryMock.taskId(eq(NON_EXISTING_ID))).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", NON_EXISTING_ID) + .multiPart("attachment-name", EXAMPLE_TASK_ATTACHMENT_NAME) + .multiPart("attachment-description", EXAMPLE_TASK_ATTACHMENT_DESCRIPTION) + .multiPart("attachment-type", EXAMPLE_TASK_ATTACHMENT_TYPE) + .multiPart("content", createMockByteData()) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when() + .post(SINGLE_TASK_ADD_ATTACHMENT_URL); + } + + @Test + public void testCreateCompleteTaskAttachmentWithUrl() { + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .multiPart("attachment-name", EXAMPLE_TASK_ATTACHMENT_NAME) + .multiPart("attachment-description", EXAMPLE_TASK_ATTACHMENT_DESCRIPTION) + .multiPart("attachment-type", EXAMPLE_TASK_ATTACHMENT_TYPE) + .multiPart("url", EXAMPLE_TASK_ATTACHMENT_URL) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(SINGLE_TASK_ADD_ATTACHMENT_URL); + + verifyCreatedTaskAttachment(mockTaskAttachment, response, true); + } + + @Test + public void testCreateCompleteTaskAttachmentWithUrlWithHistoryDisabled() { + + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .multiPart("attachment-name", EXAMPLE_TASK_ATTACHMENT_NAME) + .multiPart("attachment-description", EXAMPLE_TASK_ATTACHMENT_DESCRIPTION) + .multiPart("attachment-type", EXAMPLE_TASK_ATTACHMENT_TYPE) + .multiPart("url", EXAMPLE_TASK_ATTACHMENT_URL) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .post(SINGLE_TASK_ADD_ATTACHMENT_URL); + } + + @Test + public void testCreateTaskAttachmentWithUrlToNonExistingTask() { + when(historicTaskInstanceQueryMock.taskId(eq(NON_EXISTING_ID))).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", NON_EXISTING_ID) + .multiPart("attachment-name", EXAMPLE_TASK_ATTACHMENT_NAME) + .multiPart("attachment-description", EXAMPLE_TASK_ATTACHMENT_DESCRIPTION) + .multiPart("attachment-type", EXAMPLE_TASK_ATTACHMENT_TYPE) + .multiPart("url", EXAMPLE_TASK_ATTACHMENT_URL) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when() + .post(SINGLE_TASK_ADD_ATTACHMENT_URL); + } + + @Test + public void testCreateTaskAttachmentWithUrlToNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", NON_EXISTING_ID) + .multiPart("attachment-name", EXAMPLE_TASK_ATTACHMENT_NAME) + .multiPart("attachment-description", EXAMPLE_TASK_ATTACHMENT_DESCRIPTION) + .multiPart("attachment-type", EXAMPLE_TASK_ATTACHMENT_TYPE) + .multiPart("url", EXAMPLE_TASK_ATTACHMENT_URL) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .post(SINGLE_TASK_ADD_ATTACHMENT_URL); + } + + @Test + public void testCreateTaskAttachmentWithoutMultiparts() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode()) + .when() + .post(SINGLE_TASK_ADD_ATTACHMENT_URL); + } + + @Test + public void testGetSingleTaskAttachmentContent() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("attachmentId", MockProvider.EXAMPLE_TASK_ATTACHMENT_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(SINGLE_TASK_SINGLE_ATTACHMENT_DATA_URL); + + byte[] responseContent = IoUtil.readInputStream(response.asInputStream(), "attachmentContent"); + assertEquals("someContent", new String(responseContent)); + } + + @Test + public void testGetSingleTaskAttachmentContentWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .get(SINGLE_TASK_SINGLE_ATTACHMENT_DATA_URL); + } + + @Test + public void testGetSingleTaskAttachmentContentForNonExistingAttachmentId() { + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", NON_EXISTING_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Attachment content for attachment with id '" + NON_EXISTING_ID + "' does not exist for task id '" + EXAMPLE_TASK_ID + "'.")) + .when().get(SINGLE_TASK_SINGLE_ATTACHMENT_DATA_URL); + } + + @Test + public void testGetSingleTaskAttachmentContentForNonExistingAttachmentIdWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when().get(SINGLE_TASK_SINGLE_ATTACHMENT_DATA_URL); + } + + @Test + public void testGetSingleTaskAttachmentContentForNonExistingTask() { + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Attachment content for attachment with id '" + EXAMPLE_TASK_ATTACHMENT_ID + "' does not exist for task id '" + NON_EXISTING_ID + "'.")) + .when() + .get(SINGLE_TASK_SINGLE_ATTACHMENT_DATA_URL); + } + + @Test + public void testGetSingleTaskAttachmentContentForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .get(SINGLE_TASK_SINGLE_ATTACHMENT_DATA_URL); + } + + @Test + public void testDeleteSingleTaskAttachment() { + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("attachmentId", MockProvider.EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_TASK_DELETE_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testDeleteSingleTaskAttachmentWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_TASK_DELETE_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testDeleteSingleTaskAttachmentForNonExistingAttachmentId() { + doThrow(new ProcessEngineException()).when(taskServiceMock).deleteTaskAttachment(EXAMPLE_TASK_ID, NON_EXISTING_ID); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body(containsString("Deletion is not possible. No attachment exists for task id '" + EXAMPLE_TASK_ID + "' and attachment id '" + NON_EXISTING_ID + "'.")) + .when().delete(SINGLE_TASK_DELETE_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testDeleteSingleTaskAttachmentForNonExistingAttachmentIdWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("attachmentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when().delete(SINGLE_TASK_DELETE_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testDeleteSingleTaskAttachmentForNonExistingTask() { + doThrow(new ProcessEngineException()).when(taskServiceMock).deleteTaskAttachment(NON_EXISTING_ID, EXAMPLE_TASK_ATTACHMENT_ID); + + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Deletion is not possible. No attachment exists for task id '" + NON_EXISTING_ID + "' and attachment id '" + EXAMPLE_TASK_ATTACHMENT_ID + "'.")) + .when() + .delete(SINGLE_TASK_DELETE_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testDeleteSingleTaskAttachmentForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given() + .pathParam("id", NON_EXISTING_ID) + .pathParam("attachmentId", EXAMPLE_TASK_ATTACHMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_TASK_DELETE_SINGLE_ATTACHMENT_URL); + } + + @Test + public void testDeleteDeleteTask() { + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_TASK_URL); + + verify(taskServiceMock).deleteTask(EXAMPLE_TASK_ID); + } + + @Test + public void testPostCreateTask() { + Map json = new HashMap<>(); + + json.put("id", "anyTaskId"); + json.put("name", "A Task"); + json.put("description", "Some description"); + json.put("priority", 30); + json.put("assignee", "demo"); + json.put("owner", "mary"); + json.put("delegationState", "PENDING"); + json.put("due", withTimezone("2014-01-01T00:00:00")); + json.put("followUp", withTimezone("2014-01-01T00:00:00")); + json.put("parentTaskId", "aParentTaskId"); + json.put("caseInstanceId", "aCaseInstanceId"); + json.put("tenantId", MockProvider.EXAMPLE_TENANT_ID); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(anyString())).thenReturn(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(TASK_CREATE_URL); + + verify(taskServiceMock).newTask((String) json.get("id")); + verify(newTask).setName((String) json.get("name")); + verify(newTask).setDescription((String) json.get("description")); + verify(newTask).setPriority((Integer) json.get("priority")); + verify(newTask).setAssignee((String) json.get("assignee")); + verify(newTask).setOwner((String) json.get("owner")); + verify(newTask).setDelegationState(DelegationState.valueOf((String) json.get("delegationState"))); + verify(newTask).setDueDate(any(Date.class)); + verify(newTask).setFollowUpDate(any(Date.class)); + verify(newTask).setParentTaskId((String) json.get("parentTaskId")); + verify(newTask).setCaseInstanceId((String) json.get("caseInstanceId")); + verify(newTask).setTenantId((String) json.get("tenantId")); + verify(taskServiceMock).saveTask(newTask); + } + + @Test + public void testPostCreateTaskPartialProperties() { + Map json = new HashMap<>(); + + json.put("name", "A Task"); + json.put("description", "Some description"); + json.put("assignee", "demo"); + json.put("owner", "mary"); + json.put("due", withTimezone("2014-01-01T00:00:00")); + json.put("parentTaskId", "aParentTaskId"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(any())).thenReturn(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(TASK_CREATE_URL); + + verify(taskServiceMock).newTask(null); + verify(newTask).setName((String) json.get("name")); + verify(newTask).setDescription((String) json.get("description")); + verify(newTask).setPriority(0); + verify(newTask).setAssignee((String) json.get("assignee")); + verify(newTask).setOwner((String) json.get("owner")); + verify(newTask).setDelegationState(null); + verify(newTask).setDueDate(any(Date.class)); + verify(newTask).setFollowUpDate(null); + verify(newTask).setParentTaskId((String) json.get("parentTaskId")); + verify(newTask).setCaseInstanceId(null); + verify(newTask).setTenantId(null); + verify(taskServiceMock).saveTask(newTask); + } + + @Test + public void testPostCreateTaskDelegationStateResolved() { + Map json = new HashMap<>(); + + json.put("delegationState", "RESOLVED"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(any())).thenReturn(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(TASK_CREATE_URL); + + verify(taskServiceMock).newTask(null); + verify(newTask).setDelegationState(DelegationState.valueOf((String) json.get("delegationState"))); + verify(taskServiceMock).saveTask(newTask); + } + + @Test + public void testPostCreateTaskDelegationStatePending() { + Map json = new HashMap<>(); + + json.put("delegationState", "PENDING"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(any())).thenReturn(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(TASK_CREATE_URL); + + verify(taskServiceMock).newTask(null); + verify(newTask).setDelegationState(DelegationState.valueOf((String) json.get("delegationState"))); + verify(taskServiceMock).saveTask(newTask); + } + + @Test + public void testPostCreateTaskUnsupportedDelegationState() { + Map json = new HashMap<>(); + + json.put("delegationState", "unsupported"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(any())).thenReturn(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Valid values for property 'delegationState' are 'PENDING' or 'RESOLVED', but was 'unsupported'")) + .when() + .post(TASK_CREATE_URL); + } + + @Test + public void testPostCreateTaskLowercaseDelegationState() { + Map json = new HashMap<>(); + + json.put("delegationState", "pending"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(any())).thenReturn(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(TASK_CREATE_URL); + + verify(taskServiceMock).newTask(null); + verify(newTask).setDelegationState(DelegationState.PENDING); + verify(taskServiceMock).saveTask(newTask); + } + + @Test + public void testPostCreateTask_NotValidValueException() { + Map json = new HashMap<>(); + + json.put("id", "anyTaskId"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(anyString())).thenReturn(newTask); + + doThrow(new NotValidException("parent task is null")).when(taskServiceMock).saveTask(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Could not save task: parent task is null")) + .when().post(TASK_CREATE_URL); + } + + @Test + public void testPostCreateTaskThrowsAuthorizationException() { + Map json = new HashMap<>(); + json.put("id", "anyTaskId"); + + String message = "expected exception"; + when(taskServiceMock.newTask(anyString())).thenThrow(new AuthorizationException(message)); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when().post(TASK_CREATE_URL); + } + + @Test + public void testSaveNewTaskThrowsAuthorizationException() { + Map json = new HashMap<>(); + json.put("id", "anyTaskId"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(anyString())).thenReturn(newTask); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).saveTask(newTask); + + given() + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when().post(TASK_CREATE_URL); + } + + @Test + public void testPutUpdateTask() { + Map json = new HashMap<>(); + + json.put("id", "anyTaskId"); + json.put("name", "A Task"); + json.put("description", "Some description"); + json.put("priority", 30); + json.put("assignee", "demo"); + json.put("owner", "mary"); + json.put("delegationState", "PENDING"); + json.put("due", withTimezone("2014-01-01T00:00:00")); + json.put("followUp", withTimezone("2014-01-01T00:00:00")); + json.put("parentTaskId", "aParentTaskId"); + json.put("caseInstanceId", "aCaseInstanceId"); + json.put("tenantId", MockProvider.EXAMPLE_TENANT_ID); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_URL); + + verify(mockTask).setName((String) json.get("name")); + verify(mockTask).setDescription((String) json.get("description")); + verify(mockTask).setPriority((Integer) json.get("priority")); + verify(mockTask).setAssignee((String) json.get("assignee")); + verify(mockTask).setOwner((String) json.get("owner")); + verify(mockTask).setDelegationState(DelegationState.valueOf((String) json.get("delegationState"))); + verify(mockTask).setDueDate(any(Date.class)); + verify(mockTask).setFollowUpDate(any(Date.class)); + verify(mockTask).setParentTaskId((String) json.get("parentTaskId")); + verify(mockTask).setCaseInstanceId((String) json.get("caseInstanceId")); + verify(mockTask).setTenantId((String) json.get("tenantId")); + verify(taskServiceMock).saveTask(mockTask); + } + + @Test + public void testPutUpdateTaskPartialProperties() { + Map json = new HashMap<>(); + + json.put("name", "A Task"); + json.put("description", "Some description"); + json.put("assignee", "demo"); + json.put("owner", "mary"); + json.put("due", withTimezone("2014-01-01T00:00:00")); + json.put("parentTaskId", "aParentTaskId"); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_URL); + + verify(mockTask).setName((String) json.get("name")); + verify(mockTask).setDescription((String) json.get("description")); + verify(mockTask).setPriority(0); + verify(mockTask).setAssignee((String) json.get("assignee")); + verify(mockTask).setOwner((String) json.get("owner")); + verify(mockTask).setDelegationState(null); + verify(mockTask).setDueDate(any(Date.class)); + verify(mockTask).setFollowUpDate(null); + verify(mockTask).setParentTaskId((String) json.get("parentTaskId")); + verify(mockTask).setCaseInstanceId(null); + verify(mockTask).setTenantId(null); + verify(taskServiceMock).saveTask(mockTask); + } + + @Test + public void testPutUpdateTaskNotFound() { + when(mockQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .body(EMPTY_JSON_OBJECT) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("No matching task with id "+EXAMPLE_TASK_ID)) + .when() + .put(SINGLE_TASK_URL); + } + + @Test + public void testPutUpdateTaskDelegationStateResolved() { + Map json = new HashMap<>(); + + json.put("delegationState", "RESOLVED"); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_URL); + + verify(mockTask).setDelegationState(DelegationState.valueOf((String) json.get("delegationState"))); + verify(taskServiceMock).saveTask(mockTask); + } + + @Test + public void testPutUpdateTaskDelegationStatePending() { + Map json = new HashMap<>(); + + json.put("delegationState", "PENDING"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(anyString())).thenReturn(newTask); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_URL); + + verify(mockTask).setDelegationState(DelegationState.valueOf((String) json.get("delegationState"))); + verify(taskServiceMock).saveTask(mockTask); + } + + @Test + public void testPutUpdateTaskUnsupportedDelegationState() { + Map json = new HashMap<>(); + + json.put("delegationState", "unsupported"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(anyString())).thenReturn(newTask); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Valid values for property 'delegationState' are 'PENDING' or 'RESOLVED', but was 'unsupported'")) + .when() + .put(SINGLE_TASK_URL); + } + + @Test + public void testPutUpdateTaskLowercaseDelegationState() { + Map json = new HashMap<>(); + + json.put("delegationState", "pending"); + + Task newTask = mock(Task.class); + when(taskServiceMock.newTask(anyString())).thenReturn(newTask); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_URL); + + verify(mockTask).setDelegationState(DelegationState.PENDING); + verify(taskServiceMock).saveTask(mockTask); + } + + @Test + public void testPutUpdateTaskThrowsAuthorizationException() { + Map json = new HashMap<>(); + json.put("delegationState", "pending"); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).saveTask(any(Task.class)); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .contentType(ContentType.JSON) + .body(json) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(SINGLE_TASK_URL); + } + + @Test + public void testGetDeployedTaskForm() { + InputStream deployedFormMock = new ByteArrayInputStream("Test".getBytes()); + when(formServiceMock.getDeployedTaskForm(anyString())).thenReturn(deployedFormMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(equalTo("Test")) + .contentType(MediaType.APPLICATION_XHTML_XML) + .when() + .get(DEPLOYED_TASK_FORM_URL); + + verify(formServiceMock).getDeployedTaskForm(MockProvider.EXAMPLE_TASK_ID); + } + + @Test + public void testGetDeployedTaskFormJson() { + InputStream deployedFormMock = new ByteArrayInputStream("Test".getBytes()); + when(formServiceMock.getDeployedTaskForm(anyString())).thenReturn(deployedFormMock); + when(mockTask.getFormKey()).thenReturn("test.form"); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(equalTo("Test")) + .contentType(MediaType.APPLICATION_JSON) + .when() + .get(DEPLOYED_TASK_FORM_URL); + + verify(formServiceMock).getDeployedTaskForm(MockProvider.EXAMPLE_TASK_ID); + } + + @Test + public void testGetDeployedTaskFormJsonUsingFormRef() { + InputStream deployedFormMock = new ByteArrayInputStream("{\"id\":\"myForm\"}".getBytes()); + when(formServiceMock.getDeployedTaskForm(anyString())).thenReturn(deployedFormMock); + when(mockTask.getFormKey()).thenReturn(null); + when(mockTask.getCamundaFormRef()).thenReturn(new CamundaFormRefImpl("myForm", "latest")); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(equalTo("{\"id\":\"myForm\"}")) + .contentType(MediaType.APPLICATION_JSON) + .when() + .get(DEPLOYED_TASK_FORM_URL); + + verify(formServiceMock).getDeployedTaskForm(MockProvider.EXAMPLE_TASK_ID); + } + + @Test + public void testGetDeployedTaskFormWithoutAuthorization() { + String message = "unauthorized"; + when(formServiceMock.getDeployedTaskForm(anyString())) + .thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("message", equalTo(message)) + .when() + .get(DEPLOYED_TASK_FORM_URL); + } + + @Test + public void testGetDeployedTaskFormWithWrongFormKey() { + String message = "wrong key format"; + when(formServiceMock.getDeployedTaskForm(anyString())) + .thenThrow(new BadUserRequestException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", equalTo(message)) + .when() + .get(DEPLOYED_TASK_FORM_URL); + } + + @Test + public void testGetDeployedTaskFormWithUnexistingForm() { + String message = "not found"; + when(formServiceMock.getDeployedTaskForm(anyString())) + .thenThrow(new NotFoundException(message)); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("message",equalTo(message)) + .when() + .get(DEPLOYED_TASK_FORM_URL); + } + + @Test + public void testGetDeployedTaskFormWithUnexistingTask() { + InputStream deployedFormMock = new ByteArrayInputStream("Test".getBytes()); + when(formServiceMock.getDeployedTaskForm(anyString())).thenReturn(deployedFormMock); + when(mockQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("message", containsString("No task found for taskId")) + .when() + .get(DEPLOYED_TASK_FORM_URL); + } + + @Test + public void testHandleBpmnError() { + Map parameters = new HashMap<>(); + parameters.put("errorCode", "anErrorCode"); + parameters.put("errorMessage", "anErrorMessage"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_BPMN_ERROR_URL); + + verify(taskServiceMock).handleBpmnError("aTaskId", "anErrorCode", "anErrorMessage", null); + verifyNoMoreInteractions(taskServiceMock); + } + + @Test + public void testHandleBpmnErrorWithVariables() { + Map parameters = new HashMap<>(); + parameters.put("errorCode", "anErrorCode"); + Map variables = VariablesBuilder + .create() + .variable("var1", "val1") + .variable("var2", "val2", "String") + .variable("var3", ValueType.OBJECT.getName(), "val3", "aFormat", "aRootType") + .getVariables(); + parameters.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_BPMN_ERROR_URL); + + verify(taskServiceMock).handleBpmnError( + eq("aTaskId"), + eq("anErrorCode"), + isNull(), + argThat(EqualsVariableMap.matches() + .matcher("var1", EqualsUntypedValue.matcher().value("val1")) + .matcher("var2", EqualsPrimitiveValue.stringValue("val2")) + .matcher("var3", + EqualsObjectValue.objectValueMatcher() + .type(ValueType.OBJECT) + .serializedValue("val3") + .serializationFormat("aFormat") + .objectTypeName("aRootType")))); + verifyNoMoreInteractions(taskServiceMock); + } + + @Test + public void testHandleBpmnErrorNonExistingTask() { + doThrow(new NotFoundException()) + .when(taskServiceMock) + .handleBpmnError(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("errorCode", "anErrorCode"); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .when() + .post(HANDLE_BPMN_ERROR_URL); + } + + @Test + public void testHandleBpmnErrorNoErrorCode() { + doThrow(new BadUserRequestException()) + .when(taskServiceMock) + .handleBpmnError(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("errorCode", ""); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .when() + .post(HANDLE_BPMN_ERROR_URL); + } + + @Test + public void testHandleBpmnErrorThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")) + .when(taskServiceMock) + .handleBpmnError(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("errorCode", "errorCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_BPMN_ERROR_URL); + } + + @Test + public void testHandleBpmnErrorThrowsBadUserRequestException() { + doThrow(new BadUserRequestException("aMessage")) + .when(taskServiceMock) + .handleBpmnError(any(), any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("errorCode", "errorCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_BPMN_ERROR_URL); + } + + + @Test + public void testHandleBpmnEscalation() { + Map parameters = new HashMap<>(); + parameters.put("escalationCode", "anEscalationCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_BPMN_ESCALATION_URL); + + verify(taskServiceMock).handleEscalation("aTaskId", "anEscalationCode", null); + verifyNoMoreInteractions(taskServiceMock); + } + + @Test + public void testHandleBpmnEscalationWithVariables() { + Map parameters = new HashMap<>(); + parameters.put("escalationCode", "anEscalationCode"); + Map variables = VariablesBuilder + .create() + .variable("var1", "val1") + .variable("var2", "val2", "String") + .variable("var3", ValueType.OBJECT.getName(), "val3", "aFormat", "aRootType") + .getVariables(); + parameters.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(HANDLE_BPMN_ESCALATION_URL); + + verify(taskServiceMock).handleEscalation( + eq("aTaskId"), + eq("anEscalationCode"), + argThat(EqualsVariableMap.matches() + .matcher("var1", EqualsUntypedValue.matcher().value("val1")) + .matcher("var2", EqualsPrimitiveValue.stringValue("val2")) + .matcher("var3", + EqualsObjectValue.objectValueMatcher() + .type(ValueType.OBJECT) + .serializedValue("val3") + .serializationFormat("aFormat") + .objectTypeName("aRootType")))); + verifyNoMoreInteractions(taskServiceMock); + } + + @Test + public void testHandleBpmnEscalationNonExistingTask() { + doThrow(new NotFoundException("Task with id aTaskId does not exist")) + .when(taskServiceMock) + .handleEscalation(any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("escalationCode", "anEscalationCode"); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Task with id aTaskId does not exist")) + .when() + .post(HANDLE_BPMN_ESCALATION_URL); + } + + @Test + public void testHandleBpmnEscalationThrowsAuthorizationException() { + doThrow(new AuthorizationException("aMessage")) + .when(taskServiceMock) + .handleEscalation(any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("escalationCode", "escalationCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_BPMN_ESCALATION_URL); + } + + @Test + public void testHandleBpmnEscalationThrowsBadUserRequestException() { + doThrow(new BadUserRequestException("aMessage")) + .when(taskServiceMock) + .handleEscalation(any(), any(), any()); + + Map parameters = new HashMap<>(); + parameters.put("escalationCode", "escalationCode"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_BPMN_ESCALATION_URL); + } + + @Test + public void testHandleBpmnEscalationMissingEscalationCode() { + doThrow(new BadUserRequestException("aMessage")) + .when(taskServiceMock) + .handleEscalation(any(), any(), any()); + + Map parameters = new HashMap<>(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .pathParam("id", "aTaskId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("aMessage")) + .when() + .post(HANDLE_BPMN_ESCALATION_URL); + } + + @Test + public void testDeleteTaskCommentThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock) + .deleteTaskComment(MockProvider.EXAMPLE_TASK_ID, EXAMPLE_TASK_COMMENT_ID); + + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .when() + .delete(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteTaskComment() { + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_TASK_SINGLE_COMMENT_URL); + verify(taskServiceMock).deleteTaskComment(EXAMPLE_TASK_ID, EXAMPLE_TASK_COMMENT_ID); + } + + @Test + public void testDeleteTaskCommentWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteTaskCommentForNonExistingCommentId() { + doThrow(new NullValueException()).when(taskServiceMock).deleteTaskComment(EXAMPLE_TASK_ID, NON_EXISTING_ID); + + given().pathParam("id", EXAMPLE_TASK_ID) + .pathParam("commentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .delete(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteTaskCommentForNonExistingCommentIdWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", EXAMPLE_TASK_ID) + .pathParam("commentId", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteTaskCommentForNonExistingTask() { + when(historicTaskInstanceQueryMock.taskId(NON_EXISTING_ID)).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", NON_EXISTING_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when() + .delete(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteTaskCommentForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", NON_EXISTING_ID) + .pathParam("commentId", EXAMPLE_TASK_COMMENT_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_TASK_SINGLE_COMMENT_URL); + } + + @Test + public void testDeleteTaskCommentsThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).deleteTaskComments(MockProvider.EXAMPLE_TASK_ID); + + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .when() + .delete(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testDeleteTaskComments() { + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(SINGLE_TASK_COMMENTS_URL); + verify(taskServiceMock).deleteTaskComments(EXAMPLE_TASK_ID); + } + + @Test + public void testDeleteTaskCommentsWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testDeleteTaskCommentsForNonExistingTask() { + when(historicTaskInstanceQueryMock.taskId(NON_EXISTING_ID)).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when() + .delete(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testDeleteTaskCommentsForNonExistingTaskWithHistoryDisabled() { + mockHistoryDisabled(); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body(containsString("History is not enabled")) + .when() + .delete(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testUpdateTaskComment() { + Map json = new HashMap<>(); + + json.put("id", EXAMPLE_TASK_COMMENT_ID); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + given().pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_COMMENTS_URL); + + verify(taskServiceMock).updateTaskComment(EXAMPLE_TASK_ID, EXAMPLE_TASK_COMMENT_ID, + EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + } + + @Test + public void testUpdateTaskCommentCommentIdNull() { + String message = "expected exception"; + doThrow(new NullValueException(message)).when(taskServiceMock) + .updateTaskComment(EXAMPLE_TASK_ID, null, EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + Map json = new HashMap<>(); + + json.put("id", null); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + given().pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testUpdateTaskCommentMessageIdNull() { + String message = "expected exception"; + doThrow(new NullValueException(message)).when(taskServiceMock) + .updateTaskComment(EXAMPLE_TASK_ID, EXAMPLE_TASK_COMMENT_ID, null); + + Map json = new HashMap<>(); + + json.put("id", EXAMPLE_TASK_COMMENT_ID); + json.put("message", null); + + given().pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testUpdateTaskCommentExtraProperties() { + Map json = new HashMap<>(); + + //Only id and message are used + json.put("id", EXAMPLE_TASK_COMMENT_ID); + json.put("userId", "anyUserId"); + json.put("time", withTimezone("2014-01-01T00:00:00")); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + json.put("removalTime", withTimezone("2014-05-01T00:00:00")); + json.put("rootProcessInstanceId", EXAMPLE_TASK_COMMENT_ROOT_PROCESS_INSTANCE_ID); + json.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + + given().pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_COMMENTS_URL); + + verify(taskServiceMock).updateTaskComment(EXAMPLE_TASK_ID, EXAMPLE_TASK_COMMENT_ID, + EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + } + + @Test + public void testUpdateTaskCommentTaskIdNotFound() { + when(historicTaskInstanceQueryMock.taskId(NON_EXISTING_ID)).thenReturn(historicTaskInstanceQueryMock); + when(historicTaskInstanceQueryMock.singleResult()).thenReturn(null); + + Map json = new HashMap<>(); + + json.put("id", EXAMPLE_TASK_COMMENT_ID); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + given().pathParam("id", NON_EXISTING_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body(containsString("No task found for task id " + NON_EXISTING_ID)) + .when() + .put(SINGLE_TASK_COMMENTS_URL); + } + + @Test + public void testUpdateTaskCommentThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock) + .updateTaskComment(EXAMPLE_TASK_ID, EXAMPLE_TASK_COMMENT_ID, EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + when(historicTaskInstanceQueryMock.taskId(EXAMPLE_TASK_ID)).thenReturn(historicTaskInstanceQueryMock); + + Map json = new HashMap<>(); + json.put("id", EXAMPLE_TASK_COMMENT_ID); + json.put("message", EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + + given().pathParam("id", EXAMPLE_TASK_ID) + .body(json) + .contentType(ContentType.JSON) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .put(SINGLE_TASK_COMMENTS_URL); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void verifyTaskComments(List mockTaskComments, Response response) { + List list = response.as(List.class); + assertEquals(1, list.size()); + + LinkedHashMap resourceHashMap = (LinkedHashMap) list.get(0); + + String returnedId = resourceHashMap.get("id"); + String returnedUserId = resourceHashMap.get("userId"); + String returnedTaskId = resourceHashMap.get("taskId"); + Date returnedTime = DateTimeUtil.parseDate(resourceHashMap.get("time")); + String returnedFullMessage = resourceHashMap.get("message"); + + Comment mockComment = mockTaskComments.get(0); + + assertEquals(mockComment.getId(), returnedId); + assertEquals(mockComment.getTaskId(), returnedTaskId); + assertEquals(mockComment.getUserId(), returnedUserId); + assertEquals(mockComment.getTime(), returnedTime); + assertEquals(mockComment.getFullMessage(), returnedFullMessage); + } + + private void verifyCreatedTaskComment(Comment mockTaskComment, Response response) { + String content = response.asString(); + verifyTaskCommentValues(mockTaskComment, content); + verifyTaskCommentLink(mockTaskComment, content); + } + + private void verifyTaskCommentValues(Comment mockTaskComment, String responseContent) { + JsonPath path = from(responseContent); + String returnedId = path.get("id"); + String returnedUserId = path.get("userId"); + String returnedTaskId = path.get("taskId"); + String returnedProcessInstanceId = path.get("processInstanceId"); + Date returnedTime = DateTimeUtil.parseDate(path.get("time")); + String returnedFullMessage = path.get("message"); + + assertEquals(mockTaskComment.getId(), returnedId); + assertEquals(mockTaskComment.getTaskId(), returnedTaskId); + assertEquals(mockTaskComment.getProcessInstanceId(), returnedProcessInstanceId); + assertEquals(mockTaskComment.getUserId(), returnedUserId); + assertEquals(mockTaskComment.getTime(), returnedTime); + assertEquals(mockTaskComment.getFullMessage(), returnedFullMessage); + } + + private void verifyTaskCommentLink(Comment mockTaskComment, String responseContent) { + List> returnedLinks = from(responseContent).getList("links"); + assertEquals(1, returnedLinks.size()); + + Map returnedLink = returnedLinks.get(0); + assertEquals(HttpMethod.GET, returnedLink.get("method")); + assertTrue(returnedLink.get("href").endsWith(SINGLE_TASK_COMMENTS_URL.replace("{id}", mockTaskComment.getTaskId()) + "/" + mockTaskComment.getId())); + assertEquals("self", returnedLink.get("rel")); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void verifyTaskAttachments(List mockTaskAttachments, Response response) { + List list = response.as(List.class); + assertEquals(1, list.size()); + + LinkedHashMap resourceHashMap = (LinkedHashMap) list.get(0); + + String returnedId = resourceHashMap.get("id"); + String returnedTaskId = resourceHashMap.get("taskId"); + String returnedName = resourceHashMap.get("name"); + String returnedType = resourceHashMap.get("type"); + String returnedDescription = resourceHashMap.get("description"); + String returnedUrl = resourceHashMap.get("url"); + + Attachment mockAttachment = mockTaskAttachments.get(0); + + assertEquals(mockAttachment.getId(), returnedId); + assertEquals(mockAttachment.getTaskId(), returnedTaskId); + assertEquals(mockAttachment.getName(), returnedName); + assertEquals(mockAttachment.getType(), returnedType); + assertEquals(mockAttachment.getDescription(), returnedDescription); + assertEquals(mockAttachment.getUrl(), returnedUrl); + } + + private void verifyCreatedTaskAttachment(Attachment mockTaskAttachment, Response response, boolean urlExist) { + String content = response.asString(); + verifyTaskAttachmentValues(mockTaskAttachment, content, urlExist); + verifyTaskAttachmentLink(mockTaskAttachment, content); + } + + private void verifyTaskAttachmentValues(Attachment mockTaskAttachment, String responseContent, boolean urlExist) { + JsonPath path = from(responseContent); + String returnedId = path.get("id"); + String returnedTaskId = path.get("taskId"); + String returnedName = path.get("name"); + String returnedType = path.get("type"); + String returnedDescription = path.get("description"); + String returnedUrl = path.get("url"); + + Attachment mockAttachment = mockTaskAttachments.get(0); + + assertEquals(mockAttachment.getId(), returnedId); + assertEquals(mockAttachment.getTaskId(), returnedTaskId); + assertEquals(mockAttachment.getName(), returnedName); + assertEquals(mockAttachment.getType(), returnedType); + assertEquals(mockAttachment.getDescription(), returnedDescription); + if (urlExist) { + assertEquals(mockAttachment.getUrl(), returnedUrl); + } + } + + private void verifyTaskAttachmentLink(Attachment mockTaskAttachment, String responseContent) { + List> returnedLinks = from(responseContent).getList("links"); + assertEquals(1, returnedLinks.size()); + + Map returnedLink = returnedLinks.get(0); + assertEquals(HttpMethod.GET, returnedLink.get("method")); + assertTrue(returnedLink.get("href").endsWith(SINGLE_TASK_ATTACHMENTS_URL.replace("{id}", mockTaskAttachment.getTaskId()) + "/" + mockTaskAttachment.getId())); + assertEquals("self", returnedLink.get("rel")); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0fad23f974134ddfc2f9cec484152ffc5a2c9d41 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskRestServiceQueryTest.java @@ -0,0 +1,2307 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static junit.framework.TestCase.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.camunda.bpm.engine.rest.util.QueryParamUtils.arrayAsCommaSeperatedList; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.ProcessApplicationService; +import org.camunda.bpm.application.ProcessApplicationInfo; +import org.camunda.bpm.container.RuntimeContainerDelegate; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.impl.TaskQueryImpl; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.CaseDefinitionQuery; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.hal.Hal; +import org.camunda.bpm.engine.rest.helper.EqualsList; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.ValueGenerator; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.task.DelegationState; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.task.TaskQuery; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class TaskRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String TASK_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/task"; + protected static final String TASK_COUNT_QUERY_URL = TASK_QUERY_URL + "/count"; + + private static final String SAMPLE_VAR_NAME = "varName"; + private static final String SAMPLE_VAR_VALUE = "varValue"; + + private TaskQuery mockQuery; + + @Before + public void setUpRuntimeData() { + mockQuery = setUpMockTaskQuery(MockProvider.createMockTasks()); + } + + private TaskQuery setUpMockTaskQuery(List mockedTasks) { + TaskQuery sampleTaskQuery = mock(TaskQueryImpl.class); + when(sampleTaskQuery.list()).thenReturn(mockedTasks); + when(sampleTaskQuery.count()).thenReturn((long) mockedTasks.size()); + when(sampleTaskQuery.taskCandidateGroup(anyString())).thenReturn(sampleTaskQuery); + + when(processEngine.getTaskService().createTaskQuery()).thenReturn(sampleTaskQuery); + + return sampleTaskQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given().queryParam("name", queryKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + } + + @Test + public void testInvalidDateParameter() { + given().queryParams("due", "anInvalidDate") + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'due' to value 'anInvalidDate': " + + "Cannot convert value \"anInvalidDate\" to java type java.util.Date")) + .when().get(TASK_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "dueDate") + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(TASK_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(TASK_QUERY_URL); + } + + @Test + public void testSimpleTaskQuery() { + String queryName = "name"; + + Response response = given().queryParam("name", queryName) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).taskName(queryName); + inOrder.verify(mockQuery).list(); + + String content = response.asString(); + List> instances = from(content).getList(""); + assertThat(instances).hasSize(1).as("There should be one task returned."); + assertThat(instances.get(0)).isNotNull().as("The returned task should not be null."); + + String returnedTaskName = from(content).getString("[0].name"); + String returnedId = from(content).getString("[0].id"); + String returendAssignee = from(content).getString("[0].assignee"); + String returnedCreateTime = from(content).getString("[0].created"); + String returnedLastUpdated = from(content).getString("[0].lastUpdated"); + String returnedDueDate = from(content).getString("[0].due"); + String returnedFollowUpDate = from(content).getString("[0].followUp"); + String returnedDelegationState = from(content).getString("[0].delegationState"); + String returnedDescription = from(content).getString("[0].description"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedOwner = from(content).getString("[0].owner"); + String returnedParentTaskId = from(content).getString("[0].parentTaskId"); + int returnedPriority = from(content).getInt("[0].priority"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedTaskDefinitionKey = from(content).getString("[0].taskDefinitionKey"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedCaseExecutionId = from(content).getString("[0].caseExecutionId"); + boolean returnedSuspensionState = from(content).getBoolean("[0].suspended"); + String returnedFormKey = from(content).getString("[0].formKey"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + assertThat(MockProvider.EXAMPLE_TASK_NAME).isEqualTo(returnedTaskName); + assertThat(MockProvider.EXAMPLE_TASK_ID).isEqualTo(returnedId); + assertThat(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME).isEqualTo(returendAssignee); + assertThat(MockProvider.EXAMPLE_TASK_CREATE_TIME).isEqualTo(returnedCreateTime); + assertThat(MockProvider.EXAMPLE_TASK_LAST_UPDATED).isEqualTo(returnedLastUpdated); + assertThat(MockProvider.EXAMPLE_TASK_DUE_DATE).isEqualTo(returnedDueDate); + assertThat(MockProvider.EXAMPLE_FOLLOW_UP_DATE).isEqualTo(returnedFollowUpDate); + assertThat(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString()).isEqualTo(returnedDelegationState); + assertThat(MockProvider.EXAMPLE_TASK_DESCRIPTION).isEqualTo(returnedDescription); + assertThat(MockProvider.EXAMPLE_TASK_EXECUTION_ID).isEqualTo(returnedExecutionId); + assertThat(MockProvider.EXAMPLE_TASK_OWNER).isEqualTo(returnedOwner); + assertThat(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID).isEqualTo(returnedParentTaskId); + assertThat(MockProvider.EXAMPLE_TASK_PRIORITY).isEqualTo(returnedPriority); + assertThat(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID).isEqualTo(returnedProcessDefinitionId); + assertThat(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).isEqualTo(returnedProcessInstanceId); + assertThat(MockProvider.EXAMPLE_TASK_DEFINITION_KEY).isEqualTo(returnedTaskDefinitionKey); + assertThat(MockProvider.EXAMPLE_CASE_DEFINITION_ID).isEqualTo(returnedCaseDefinitionId); + assertThat(MockProvider.EXAMPLE_CASE_INSTANCE_ID).isEqualTo(returnedCaseInstanceId); + assertThat(MockProvider.EXAMPLE_CASE_EXECUTION_ID).isEqualTo(returnedCaseExecutionId); + assertThat(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE).isEqualTo(returnedSuspensionState); + assertThat(MockProvider.EXAMPLE_FORM_KEY).isEqualTo(returnedFormKey); + assertThat(MockProvider.EXAMPLE_TENANT_ID).isEqualTo(returnedTenantId); + + } + @Test + public void testTaskQueryWithAttachmentAndComment() { + String queryName = "name"; + + Response response = given().queryParam("name", queryName) + .queryParam("withCommentAttachmentInfo","true") + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).taskName(queryName); + inOrder.verify(mockQuery).list(); + + String content = response.asString(); + List> instances = from(content).getList(""); + assertThat(instances).hasSize(1).as("There should be one task returned."); + assertThat(instances.get(0)).isNotNull().as("The returned task should not be null."); + + boolean returnedAttachmentsInfo = from(content).getBoolean("[0].attachment"); + boolean returnedCommentsInfo = from(content).getBoolean("[0].comment"); + + assertThat(MockProvider.EXAMPLE_TASK_ATTACHMENT_STATE).isEqualTo(returnedAttachmentsInfo); + assertThat(MockProvider.EXAMPLE_TASK_COMMENT_STATE).isEqualTo(returnedCommentsInfo); + + } + + @Test + public void testSimpleHalTaskQuery() { + String queryName = "name"; + + // setup user query mock + List mockUsers = MockProvider.createMockUsers(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(sampleUserQuery.listPage(0, 1)).thenReturn(mockUsers); + when(sampleUserQuery.userIdIn(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME)).thenReturn(sampleUserQuery); + when(sampleUserQuery.userIdIn(MockProvider.EXAMPLE_TASK_OWNER)).thenReturn(sampleUserQuery); + when(sampleUserQuery.count()).thenReturn(1l); + when(processEngine.getIdentityService().createUserQuery()).thenReturn(sampleUserQuery); + + // setup process definition query mock + List mockDefinitions = MockProvider.createMockDefinitions(); + ProcessDefinitionQuery sampleProcessDefinitionQuery = mock(ProcessDefinitionQuery.class); + when(sampleProcessDefinitionQuery.listPage(0, 1)).thenReturn(mockDefinitions); + when(sampleProcessDefinitionQuery.processDefinitionIdIn(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)).thenReturn(sampleProcessDefinitionQuery); + when(sampleProcessDefinitionQuery.count()).thenReturn(1l); + when(processEngine.getRepositoryService().createProcessDefinitionQuery()).thenReturn(sampleProcessDefinitionQuery); + + // setup case definition query mock + List mockCaseDefinitions = MockProvider.createMockCaseDefinitions(); + CaseDefinitionQuery sampleCaseDefinitionQuery = mock(CaseDefinitionQuery.class); + when(sampleCaseDefinitionQuery.listPage(0, 1)).thenReturn(mockCaseDefinitions); + when(sampleCaseDefinitionQuery.caseDefinitionIdIn(MockProvider.EXAMPLE_CASE_DEFINITION_ID)).thenReturn(sampleCaseDefinitionQuery); + when(sampleCaseDefinitionQuery.count()).thenReturn(1l); + when(processEngine.getRepositoryService().createCaseDefinitionQuery()).thenReturn(sampleCaseDefinitionQuery); + + // setup example process application context path + when(processEngine.getManagementService().getProcessApplicationForDeployment(MockProvider.EXAMPLE_DEPLOYMENT_ID)) + .thenReturn(MockProvider.EXAMPLE_PROCESS_APPLICATION_NAME); + + // replace the runtime container delegate & process application service with a mock + ProcessApplicationService processApplicationService = mock(ProcessApplicationService.class); + ProcessApplicationInfo appMock = MockProvider.createMockProcessApplicationInfo(); + when(processApplicationService.getProcessApplicationInfo(MockProvider.EXAMPLE_PROCESS_APPLICATION_NAME)).thenReturn(appMock); + + RuntimeContainerDelegate delegate = mock(RuntimeContainerDelegate.class); + when(delegate.getProcessApplicationService()).thenReturn(processApplicationService); + RuntimeContainerDelegate.INSTANCE.set(delegate); + + Response response = given().queryParam("name", queryName) + .header("accept", Hal.APPLICATION_HAL_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .contentType(Hal.APPLICATION_HAL_JSON) + .when().get(TASK_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).taskName(queryName); + inOrder.verify(mockQuery).list(); + + // validate embedded tasks + String content = response.asString(); + List> instances = from(content).getList("_embedded.task"); + Assert.assertEquals("There should be one task returned.", 1, instances.size()); + Assert.assertNotNull("The returned task should not be null.", instances.get(0)); + + Map taskObject = instances.get(0); + + String returnedTaskName = (String) taskObject.get("name"); + String returnedId = (String) taskObject.get("id"); + String returnedAssignee = (String) taskObject.get("assignee"); + String returnedCreateTime = (String) taskObject.get("created"); + String returnedDueDate = (String) taskObject.get("due"); + String returnedFollowUpDate = (String) taskObject.get("followUp"); + String returnedDelegationState = (String) taskObject.get("delegationState"); + String returnedDescription = (String) taskObject.get("description"); + String returnedExecutionId = (String) taskObject.get("executionId"); + String returnedOwner = (String) taskObject.get("owner"); + String returnedParentTaskId = (String) taskObject.get("parentTaskId"); + int returnedPriority = (Integer) taskObject.get("priority"); + String returnedProcessDefinitionId = (String) taskObject.get("processDefinitionId"); + String returnedProcessInstanceId = (String) taskObject.get("processInstanceId"); + String returnedTaskDefinitionKey = (String) taskObject.get("taskDefinitionKey"); + String returnedCaseDefinitionId = (String) taskObject.get("caseDefinitionId"); + String returnedCaseInstanceId = (String) taskObject.get("caseInstanceId"); + String returnedCaseExecutionId = (String) taskObject.get("caseExecutionId"); + boolean returnedSuspensionState = (Boolean) taskObject.get("suspended"); + String returnedFormKey = (String) taskObject.get("formKey"); + String returnedTenantId = (String) taskObject.get("tenantId"); + + Assert.assertEquals(MockProvider.EXAMPLE_TASK_NAME, returnedTaskName); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME, returnedAssignee); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_CREATE_TIME, returnedCreateTime); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_DUE_DATE, returnedDueDate); + Assert.assertEquals(MockProvider.EXAMPLE_FOLLOW_UP_DATE, returnedFollowUpDate); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_DELEGATION_STATE.toString(), returnedDelegationState); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_DESCRIPTION, returnedDescription); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_OWNER, returnedOwner); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_PARENT_TASK_ID, returnedParentTaskId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_PRIORITY, returnedPriority); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_DEFINITION_KEY, returnedTaskDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_EXECUTION_ID, returnedCaseExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_SUSPENSION_STATE, returnedSuspensionState); + Assert.assertEquals(MockProvider.EXAMPLE_FORM_KEY, returnedFormKey); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + + // validate the task count + Assert.assertEquals(1l, from(content).getLong("count")); + + // validate links + Map selfReference = from(content).getMap("_links.self"); + Assert.assertNotNull(selfReference); + Assert.assertEquals("/task", selfReference.get("href")); + + // validate embedded assignees: + List> embeddedAssignees = from(content).getList("_embedded.assignee"); + Assert.assertEquals("There should be one assignee returned.", 1, embeddedAssignees.size()); + Map embeddedAssignee = embeddedAssignees.get(0); + Assert.assertNotNull("The returned assignee should not be null.", embeddedAssignee); + Assert.assertEquals(MockProvider.EXAMPLE_USER_ID, embeddedAssignee.get("id")); + Assert.assertEquals(MockProvider.EXAMPLE_USER_FIRST_NAME, embeddedAssignee.get("firstName")); + Assert.assertEquals(MockProvider.EXAMPLE_USER_LAST_NAME, embeddedAssignee.get("lastName")); + Assert.assertEquals(MockProvider.EXAMPLE_USER_EMAIL, embeddedAssignee.get("email")); + + // validate embedded owners: + List> embeddedOwners = from(content).getList("_embedded.owner"); + Assert.assertEquals("There should be one owner returned.", 1, embeddedOwners.size()); + Map embeddedOwner = embeddedOwners.get(0); + Assert.assertNotNull("The returned owner should not be null.", embeddedOwner); + Assert.assertEquals(MockProvider.EXAMPLE_USER_ID, embeddedOwner.get("id")); + Assert.assertEquals(MockProvider.EXAMPLE_USER_FIRST_NAME, embeddedOwner.get("firstName")); + Assert.assertEquals(MockProvider.EXAMPLE_USER_LAST_NAME, embeddedOwner.get("lastName")); + Assert.assertEquals(MockProvider.EXAMPLE_USER_EMAIL, embeddedOwner.get("email")); + + // validate embedded processDefinitions: + List> embeddedDefinitions = from(content).getList("_embedded.processDefinition"); + Assert.assertEquals("There should be one processDefinition returned.", 1, embeddedDefinitions.size()); + Map embeddedProcessDefinition = embeddedDefinitions.get(0); + Assert.assertNotNull("The returned processDefinition should not be null.", embeddedProcessDefinition); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, embeddedProcessDefinition.get("id")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, embeddedProcessDefinition.get("key")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_CATEGORY, embeddedProcessDefinition.get("category")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME, embeddedProcessDefinition.get("name")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_DESCRIPTION, embeddedProcessDefinition.get("description")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION, embeddedProcessDefinition.get("version")); + Assert.assertEquals(MockProvider.EXAMPLE_VERSION_TAG, embeddedProcessDefinition.get("versionTag")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME, embeddedProcessDefinition.get("resource")); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, embeddedProcessDefinition.get("deploymentId")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME, embeddedProcessDefinition.get("diagram")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED, embeddedProcessDefinition.get("suspended")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH, embeddedProcessDefinition.get("contextPath")); + + // validate embedded caseDefinitions: + List> embeddedCaseDefinitions = from(content).getList("_embedded.caseDefinition"); + Assert.assertEquals("There should be one caseDefinition returned.", 1, embeddedCaseDefinitions.size()); + Map embeddedCaseDefinition = embeddedCaseDefinitions.get(0); + Assert.assertNotNull("The returned caseDefinition should not be null.", embeddedCaseDefinition); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, embeddedCaseDefinition.get("id")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_KEY, embeddedCaseDefinition.get("key")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_CATEGORY, embeddedCaseDefinition.get("category")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_NAME, embeddedCaseDefinition.get("name")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_VERSION, embeddedCaseDefinition.get("version")); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_RESOURCE_NAME, embeddedCaseDefinition.get("resource")); + Assert.assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, embeddedCaseDefinition.get("deploymentId")); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH, embeddedCaseDefinition.get("contextPath")); + } + + @Test + public void testNoParametersQuery() { + given() + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).initializeFormKeys(); + verify(mockQuery).list(); + verifyNoMoreInteractions(mockQuery); + } + + @Test + public void testAdditionalParametersExcludingVariables() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + Map intQueryParameters = getCompleteIntQueryParameters(); + Map booleanQueryParameters = getCompleteBooleanQueryParameters(); + + Map arrayQueryParameters = getCompleteStringArrayQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .queryParams(intQueryParameters) + .queryParams(booleanQueryParameters) + .queryParam("activityInstanceIdIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("activityInstanceIdIn"))) + .queryParam("taskDefinitionKeyIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("taskDefinitionKeyIn"))) + .queryParam("taskDefinitionKeyNotIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("taskDefinitionKeyNotIn"))) + .queryParam("taskIdIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("taskIdIn"))) + .queryParam("processDefinitionKeyIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("processDefinitionKeyIn"))) + .queryParam("processInstanceBusinessKeyIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("processInstanceBusinessKeyIn"))) + .queryParam("tenantIdIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("tenantIdIn"))) + .queryParam("assigneeIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("assigneeIn"))) + .queryParam("assigneeNotIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("assigneeNotIn"))) + .queryParam("processInstanceIdIn", arrayAsCommaSeperatedList(arrayQueryParameters.get("processInstanceIdIn"))) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verifyIntegerParameterQueryInvocations(); + verifyStringParameterQueryInvocations(); + verifyBooleanParameterQueryInvocation(); + verifyStringArrayParametersInvocations(); + + verify(mockQuery).list(); + } + + private void verifyIntegerParameterQueryInvocations() { + Map intQueryParameters = getCompleteIntQueryParameters(); + + verify(mockQuery).taskMaxPriority(intQueryParameters.get("maxPriority")); + verify(mockQuery).taskMinPriority(intQueryParameters.get("minPriority")); + verify(mockQuery).taskPriority(intQueryParameters.get("priority")); + } + + private Map getCompleteIntQueryParameters() { + Map parameters = new HashMap<>(); + + parameters.put("maxPriority", 10); + parameters.put("minPriority", 9); + parameters.put("priority", 8); + + return parameters; + } + + private Map getCompleteStringArrayQueryParameters() { + Map parameters = new HashMap<>(); + + String[] activityInstanceIds = { "anActivityInstanceId", "anotherActivityInstanceId" }; + String[] taskDefinitionKeys = { "aTaskDefinitionKey", "anotherTaskDefinitionKey" }; + String[] taskDefinitionKeyNotIn = { "anUnwantedTaskDefinitionKey", "anotherUnwantedTaskDefinitionKey" }; + String[] processDefinitionKeys = { "aProcessDefinitionKey", "anotherProcessDefinitionKey" }; + String[] processInstanceBusinessKeys = { "aBusinessKey", "anotherBusinessKey" }; + String[] tenantIds = { MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID }; + String[] assigneeIn = { MockProvider.EXAMPLE_USER_ID, "anAssignee" }; + String[] assigneeNotIn = { MockProvider.EXAMPLE_USER_ID, "anAssignee" }; + String[] taskId = { MockProvider.EXAMPLE_USER_ID, "anTaskId" }; + String[] processInstanceIds = { MockProvider.EXAMPLE_PROCESS_INSTANCE_ID , MockProvider.ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID }; + + + parameters.put("activityInstanceIdIn", activityInstanceIds); + parameters.put("taskDefinitionKeyIn", taskDefinitionKeys); + parameters.put("taskDefinitionKeyNotIn", taskDefinitionKeyNotIn); + parameters.put("taskIdIn", taskId); + parameters.put("processDefinitionKeyIn", processDefinitionKeys); + parameters.put("processInstanceBusinessKeyIn", processInstanceBusinessKeys); + parameters.put("tenantIdIn", tenantIds); + parameters.put("assigneeIn", assigneeIn); + parameters.put("assigneeNotIn", assigneeNotIn); + parameters.put("processInstanceIdIn", processInstanceIds); + + return parameters; + } + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap<>(); + + parameters.put("processInstanceBusinessKey", "aBusinessKey"); + parameters.put("processInstanceBusinessKeyLike", "aBusinessKeyLike"); + parameters.put("processDefinitionKey", "aProcDefKey"); + parameters.put("processDefinitionId", "aProcDefId"); + parameters.put("executionId", "anExecId"); + parameters.put("processDefinitionName", "aProcDefName"); + parameters.put("processDefinitionNameLike", "aProcDefNameLike"); + parameters.put("processInstanceId", "aProcInstId"); + parameters.put("assignee", "anAssignee"); + parameters.put("assigneeLike", "anAssigneeLike"); + parameters.put("candidateGroup", "aCandidateGroup"); + parameters.put("candidateGroupLike", "aCandidateGroupLike"); + parameters.put("candidateUser", "aCandidate"); + parameters.put("includeAssignedTasks", "false"); + parameters.put("taskId", "aTaskId"); + parameters.put("taskDefinitionKey", "aTaskDefKey"); + parameters.put("taskDefinitionKeyLike", "aTaskDefKeyLike"); + parameters.put("description", "aDesc"); + parameters.put("descriptionLike", "aDescLike"); + parameters.put("involvedUser", "anInvolvedPerson"); + parameters.put("name", "aName"); + parameters.put("nameNotEqual", "aNameNotEqual"); + parameters.put("nameLike", "aNameLike"); + parameters.put("nameNotLike", "aNameNotLike"); + parameters.put("owner", "anOwner"); + parameters.put("caseDefinitionKey", "aCaseDefKey"); + parameters.put("caseDefinitionId", "aCaseDefId"); + parameters.put("caseDefinitionName", "aCaseDefName"); + parameters.put("caseDefinitionNameLike", "aCaseDefNameLike"); + parameters.put("caseInstanceId", "anCaseInstanceId"); + parameters.put("caseInstanceBusinessKey", "aCaseInstanceBusinessKey"); + parameters.put("caseInstanceBusinessKeyLike", "aCaseInstanceBusinessKeyLike"); + parameters.put("caseExecutionId", "aCaseExecutionId"); + parameters.put("parentTaskId", "aParentTaskId"); + + return parameters; + } + + private Map getCompleteBooleanQueryParameters() { + Map parameters = new HashMap<>(); + + parameters.put("assigned", true); + parameters.put("unassigned", true); + parameters.put("active", true); + parameters.put("suspended", true); + parameters.put("withoutTenantId", true); + parameters.put("withCandidateGroups", true); + parameters.put("withoutCandidateGroups", true); + parameters.put("withCandidateUsers", true); + parameters.put("withoutCandidateUsers", true); + parameters.put("withoutDueDate", true); + parameters.put("withCommentAttachmentInfo", true); + + return parameters; + } + + private void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockQuery).processInstanceBusinessKey(stringQueryParameters.get("processInstanceBusinessKey")); + verify(mockQuery).processInstanceBusinessKeyLike(stringQueryParameters.get("processInstanceBusinessKeyLike")); + verify(mockQuery).processDefinitionKey(stringQueryParameters.get("processDefinitionKey")); + verify(mockQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); + verify(mockQuery).executionId(stringQueryParameters.get("executionId")); + verify(mockQuery).processDefinitionName(stringQueryParameters.get("processDefinitionName")); + verify(mockQuery).processDefinitionNameLike(stringQueryParameters.get("processDefinitionNameLike")); + verify(mockQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); + verify(mockQuery).taskAssignee(stringQueryParameters.get("assignee")); + verify(mockQuery).taskAssigneeLike(stringQueryParameters.get("assigneeLike")); + verify(mockQuery).taskCandidateGroup(stringQueryParameters.get("candidateGroup")); + verify(mockQuery).taskCandidateGroupLike(stringQueryParameters.get("candidateGroupLike")); + verify(mockQuery).taskCandidateUser(stringQueryParameters.get("candidateUser")); + verify(mockQuery).taskDefinitionKey(stringQueryParameters.get("taskDefinitionKey")); + verify(mockQuery).taskDefinitionKeyLike(stringQueryParameters.get("taskDefinitionKeyLike")); + verify(mockQuery).taskDescription(stringQueryParameters.get("description")); + verify(mockQuery).taskDescriptionLike(stringQueryParameters.get("descriptionLike")); + verify(mockQuery).taskInvolvedUser(stringQueryParameters.get("involvedUser")); + verify(mockQuery).taskName(stringQueryParameters.get("name")); + verify(mockQuery).taskNameNotEqual(stringQueryParameters.get("nameNotEqual")); + verify(mockQuery).taskNameLike(stringQueryParameters.get("nameLike")); + verify(mockQuery).taskNameNotLike(stringQueryParameters.get("nameNotLike")); + verify(mockQuery).taskOwner(stringQueryParameters.get("owner")); + verify(mockQuery).caseDefinitionKey(stringQueryParameters.get("caseDefinitionKey")); + verify(mockQuery).caseDefinitionId(stringQueryParameters.get("caseDefinitionId")); + verify(mockQuery).caseDefinitionName(stringQueryParameters.get("caseDefinitionName")); + verify(mockQuery).caseDefinitionNameLike(stringQueryParameters.get("caseDefinitionNameLike")); + verify(mockQuery).caseInstanceId(stringQueryParameters.get("caseInstanceId")); + verify(mockQuery).caseInstanceBusinessKey(stringQueryParameters.get("caseInstanceBusinessKey")); + verify(mockQuery).caseInstanceBusinessKeyLike(stringQueryParameters.get("caseInstanceBusinessKeyLike")); + verify(mockQuery).caseExecutionId(stringQueryParameters.get("caseExecutionId")); + verify(mockQuery).taskParentTaskId(stringQueryParameters.get("parentTaskId")); + + } + + private void verifyStringArrayParametersInvocations() { + Map stringArrayParameters = getCompleteStringArrayQueryParameters(); + + verify(mockQuery).activityInstanceIdIn(stringArrayParameters.get("activityInstanceIdIn")); + verify(mockQuery).taskDefinitionKeyIn(stringArrayParameters.get("taskDefinitionKeyIn")); + verify(mockQuery).taskDefinitionKeyNotIn(stringArrayParameters.get("taskDefinitionKeyNotIn")); + verify(mockQuery).processDefinitionKeyIn(stringArrayParameters.get("processDefinitionKeyIn")); + verify(mockQuery).processInstanceBusinessKeyIn(stringArrayParameters.get("processInstanceBusinessKeyIn")); + verify(mockQuery).tenantIdIn(stringArrayParameters.get("tenantIdIn")); + verify(mockQuery).taskIdIn(stringArrayParameters.get("taskIdIn")); + verify(mockQuery).taskAssigneeIn(stringArrayParameters.get("assigneeIn")); + verify(mockQuery).taskAssigneeNotIn(stringArrayParameters.get("assigneeNotIn")); + verify(mockQuery).processInstanceIdIn(stringArrayParameters.get("processInstanceIdIn")); + } + + private void verifyBooleanParameterQueryInvocation() { + verify(mockQuery).taskUnassigned(); + verify(mockQuery).active(); + verify(mockQuery).suspended(); + verify(mockQuery).withoutTenantId(); + verify(mockQuery).withCandidateGroups(); + verify(mockQuery).withoutCandidateGroups(); + verify(mockQuery).withCandidateUsers(); + verify(mockQuery).withoutCandidateUsers(); + verify(mockQuery).withoutDueDate(); + verify(mockQuery).withCommentAttachmentInfo(); + } + + @Test + public void testDateParameters() { + Map queryParameters = getDateParameters(); + + given().queryParams(queryParameters) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).dueAfter(any(Date.class)); + verify(mockQuery).dueBefore(any(Date.class)); + verify(mockQuery).dueDate(any(Date.class)); + verify(mockQuery).followUpAfter(any(Date.class)); + verify(mockQuery).followUpBefore(any(Date.class)); + verify(mockQuery).followUpBeforeOrNotExistent(any(Date.class)); + verify(mockQuery).followUpDate(any(Date.class)); + verify(mockQuery).taskCreatedAfter(any(Date.class)); + verify(mockQuery).taskCreatedBefore(any(Date.class)); + verify(mockQuery).taskCreatedOn(any(Date.class)); + verify(mockQuery).taskUpdatedAfter(any(Date.class)); + } + + @Test + public void testDateParametersPost() { + Map json = getDateParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).dueAfter(any(Date.class)); + verify(mockQuery).dueBefore(any(Date.class)); + verify(mockQuery).dueDate(any(Date.class)); + verify(mockQuery).followUpAfter(any(Date.class)); + verify(mockQuery).followUpBefore(any(Date.class)); + verify(mockQuery).followUpBeforeOrNotExistent(any(Date.class)); + verify(mockQuery).followUpDate(any(Date.class)); + verify(mockQuery).taskCreatedAfter(any(Date.class)); + verify(mockQuery).taskCreatedBefore(any(Date.class)); + verify(mockQuery).taskCreatedOn(any(Date.class)); + verify(mockQuery).taskUpdatedAfter(any(Date.class)); + } + + @Test + public void testDeprecatedDateParameters() { + Map queryParameters = new HashMap<>(); + queryParameters.put("due", withTimezone("2013-01-23T14:42:44")); + queryParameters.put("created", withTimezone("2013-01-23T14:42:47")); + queryParameters.put("followUp", withTimezone("2013-01-23T14:42:50")); + + given() + .queryParams(queryParameters) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).dueDate(any(Date.class)); + verify(mockQuery).taskCreatedOn(any(Date.class)); + verify(mockQuery).followUpDate(any(Date.class)); + } + + private Map getDateParameters() { + Map parameters = new HashMap<>(); + parameters.put("dueAfter", withTimezone("2013-01-23T14:42:42")); + parameters.put("dueBefore", withTimezone("2013-01-23T14:42:43")); + parameters.put("dueDate", withTimezone("2013-01-23T14:42:44")); + parameters.put("createdAfter", withTimezone("2013-01-23T14:42:45")); + parameters.put("createdBefore", withTimezone("2013-01-23T14:42:46")); + parameters.put("createdOn", withTimezone("2013-01-23T14:42:47")); + parameters.put("followUpAfter", withTimezone("2013-01-23T14:42:48")); + parameters.put("followUpBefore", withTimezone("2013-01-23T14:42:49")); + parameters.put("followUpBeforeOrNotExistent", withTimezone("2013-01-23T14:42:49")); + parameters.put("followUpDate", withTimezone("2013-01-23T14:42:50")); + parameters.put("updatedAfter", withTimezone("2013-01-23T14:42:50")); + return parameters; + } + + @Test + public void testCandidateGroupInList() { + List candidateGroups = new ArrayList<>(); + candidateGroups.add("boss"); + candidateGroups.add("worker"); + String queryParam = candidateGroups.get(0) + "," + candidateGroups.get(1); + + given().queryParams("candidateGroups", queryParam) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).taskCandidateGroupIn(argThat(new EqualsList(candidateGroups))); + } + + @Test + public void testDelegationState() { + given().queryParams("delegationState", "PENDING") + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).taskDelegationState(DelegationState.PENDING); + + given().queryParams("delegationState", "RESOLVED") + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).taskDelegationState(DelegationState.RESOLVED); + } + + @Test + public void testLowerCaseDelegationStateParam() { + given().queryParams("delegationState", "resolved") + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).taskDelegationState(DelegationState.RESOLVED); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("dueDate", "desc", Status.OK); + inOrder.verify(mockQuery).orderByDueDate(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("followUpDate", "desc", Status.OK); + inOrder.verify(mockQuery).orderByFollowUpDate(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("instanceId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByProcessInstanceId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("created", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTaskCreateTime(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("id", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTaskId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("priority", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTaskPriority(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByExecutionId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("assignee", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTaskAssignee(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("description", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTaskDescription(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("name", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTaskName(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("nameCaseInsensitive", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTaskNameCaseInsensitive(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("caseInstanceId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByCaseInstanceId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("dueDate", "asc", Status.OK); + inOrder.verify(mockQuery).orderByDueDate(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("followUpDate", "asc", Status.OK); + inOrder.verify(mockQuery).orderByFollowUpDate(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("instanceId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByProcessInstanceId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("created", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTaskCreateTime(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("id", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTaskId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("priority", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTaskPriority(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("executionId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByExecutionId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("assignee", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTaskAssignee(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("description", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTaskDescription(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("name", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTaskName(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("nameCaseInsensitive", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTaskNameCaseInsensitive(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("caseInstanceId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByCaseInstanceId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockQuery).orderByTenantId(); + inOrder.verify(mockQuery).desc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockQuery).orderByTenantId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySorting("lastUpdated", "asc", Status.OK); + inOrder.verify(mockQuery).orderByLastUpdated(); + inOrder.verify(mockQuery).asc(); + + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(TASK_QUERY_URL); + } + + protected void executeAndVerifySortingAsPost(List> sortingJson, Status expectedStatus) { + Map json = new HashMap<>(); + json.put("sorting", sortingJson); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(TASK_QUERY_URL); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySortingAsPost( + OrderingBuilder.create() + .orderBy("dueDate").desc() + .orderBy("caseExecutionId").asc() + .getJson(), + Status.OK); + + inOrder.verify(mockQuery).orderByDueDate(); + inOrder.verify(mockQuery).desc(); + inOrder.verify(mockQuery).orderByCaseExecutionId(); + inOrder.verify(mockQuery).asc(); + + inOrder = Mockito.inOrder(mockQuery); + executeAndVerifySortingAsPost( + OrderingBuilder.create() + .orderBy("processVariable").desc() + .parameter("variable", "var") + .parameter("type", "String") + .orderBy("executionVariable").asc() + .parameter("variable", "var2") + .parameter("type", "Integer") + .orderBy("taskVariable").desc() + .parameter("variable", "var3") + .parameter("type", "Double") + .orderBy("caseInstanceVariable").asc() + .parameter("variable", "var4") + .parameter("type", "Long") + .orderBy("caseExecutionVariable").desc() + .parameter("variable", "var5") + .parameter("type", "Date") + .getJson(), + Status.OK); + + inOrder.verify(mockQuery).orderByProcessVariable("var", ValueType.STRING); + inOrder.verify(mockQuery).desc(); + inOrder.verify(mockQuery).orderByExecutionVariable("var2", ValueType.INTEGER); + inOrder.verify(mockQuery).asc(); + inOrder.verify(mockQuery).orderByTaskVariable("var3", ValueType.DOUBLE); + inOrder.verify(mockQuery).desc(); + inOrder.verify(mockQuery).orderByCaseInstanceVariable("var4", ValueType.LONG); + inOrder.verify(mockQuery).asc(); + inOrder.verify(mockQuery).orderByCaseExecutionVariable("var5", ValueType.DATE); + inOrder.verify(mockQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + @Test + public void testTaskVariableParameters() { + // equals + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).taskVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueEquals(variableName, variableValue); + // greater than + queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueGreaterThan(variableName, variableValue); + + // greater than equals + queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueGreaterThanOrEquals(variableName, variableValue); + + // lower than + queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueLessThan(variableName, variableValue); + + // lower than equals + queryValue = variableName + "_lteq_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueLessThanOrEquals(variableName, variableValue); + + // like + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueLike(variableName, variableValue); + reset(mockQuery); + + // like case-insensitive + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueLike(variableName, variableValue); + + // not equals + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueNotEquals(variableName, variableValue); + reset(mockQuery); + + // not equals case-insensitive + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testTaskVariableValueEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("taskVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testTaskVariableNameEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME.toLowerCase()); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("taskVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).taskVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + reset(mockQuery); + + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + } + + @Test + public void testTaskVariableValueNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "neq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("taskVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueNotEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testTaskVariableValueLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "like"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("taskVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).taskVariableValueLike(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testProcessVariableParameters() { + // equals + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + //equals case-insensitive + queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + + // greater than + queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueGreaterThan(variableName, variableValue); + + // greater than equals + queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueGreaterThanOrEquals(variableName, variableValue); + + // lower than + queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueLessThan(variableName, variableValue); + + // lower than equals + queryValue = variableName + "_lteq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueLessThanOrEquals(variableName, variableValue); + + // like + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueLike(variableName, variableValue); + reset(mockQuery); + + // like case-insensitive + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueLike(variableName, variableValue); + + // not equals + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueNotEquals(variableName, variableValue); + reset(mockQuery); + + // not equals case-insensitive + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testProcessVariableValueEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testProcessVariableNameEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME.toLowerCase()); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + reset(mockQuery); + + json.put("variableValuesIgnoreCase", true); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + + } + + @Test + public void testProcessVariableValueNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "neq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueNotEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testProcessVariableValueLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "like"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueLike(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testProcessVariableValueNotLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "notLike"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).processVariableValueNotLike(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testCaseVariableParameters() { + // equals + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + // equals case-insensitive + queryValue = variableName + "_eq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueEquals(variableName, variableValue); + reset(mockQuery); + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueEquals(variableName, variableValue); + + // greater than + queryValue = variableName + "_gt_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueGreaterThan(variableName, variableValue); + + // greater than equals + queryValue = variableName + "_gteq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueGreaterThanOrEquals(variableName, variableValue); + + // lower than + queryValue = variableName + "_lt_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueLessThan(variableName, variableValue); + + // lower than equals + queryValue = variableName + "_lteq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueLessThanOrEquals(variableName, variableValue); + + // like + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueLike(variableName, variableValue); + reset(mockQuery); + + // like case-insensitive + queryValue = variableName + "_like_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueLike(variableName, variableValue); + + // not equals + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueNotEquals(variableName, variableValue); + reset(mockQuery); + + // not equals case-insensitive + queryValue = variableName + "_neq_" + variableValue; + + given() + .queryParam("caseInstanceVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testCaseInstanceVariableValueEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("caseInstanceVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testCaseInstanceVariableNameEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME.toLowerCase()); + variableJson.put("operator", "eq"); + variableJson.put("value", SAMPLE_VAR_VALUE); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("caseInstanceVariables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + reset(mockQuery); + + json.put("variableValuesIgnoreCase", true); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableNamesIgnoreCase(); + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueEquals(SAMPLE_VAR_NAME.toLowerCase(), SAMPLE_VAR_VALUE); + } + + @Test + public void testCaseInstanceVariableValueNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "neq"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("caseInstanceVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueNotEquals(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testCaseInstanceVariableValueLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap<>(); + variableJson.put("name", SAMPLE_VAR_NAME); + variableJson.put("operator", "like"); + variableJson.put("value", SAMPLE_VAR_VALUE.toLowerCase()); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map json = new HashMap<>(); + json.put("caseInstanceVariables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).matchVariableValuesIgnoreCase(); + verify(mockQuery).caseInstanceVariableValueLike(SAMPLE_VAR_NAME, SAMPLE_VAR_VALUE.toLowerCase()); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam("taskVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueEquals(variableName1, variableValue1); + verify(mockQuery).taskVariableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap<>(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap<>(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap<>(); + json.put("taskVariables", variables); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(TASK_QUERY_URL); + + verify(mockQuery).taskVariableValueEquals(variableName, variableValue); + verify(mockQuery).taskVariableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + + } + + @Test + public void testMultipleProcessVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam("processVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueEquals(variableName1, variableValue1); + verify(mockQuery).processVariableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleProcessVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap<>(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap<>(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap<>(); + json.put("processVariables", variables); + + given() + .header("accept", MediaType.APPLICATION_JSON) + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).processVariableValueEquals(variableName, variableValue); + verify(mockQuery).processVariableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testMultipleCaseVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam("caseInstanceVariables", queryValue) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueEquals(variableName1, variableValue1); + verify(mockQuery).caseInstanceVariableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleCaseVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap<>(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap<>(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap<>(); + json.put("caseInstanceVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verify(mockQuery).caseInstanceVariableValueEquals(variableName, variableValue); + verify(mockQuery).caseInstanceVariableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testCompletePostParameters() { + + Map queryParameters = new HashMap<>(); + Map stringQueryParameters = getCompleteStringQueryParameters(); + Map intQueryParameters = getCompleteIntQueryParameters(); + Map booleanQueryParameters = getCompleteBooleanQueryParameters(); + Map stringArrayQueryParameters = getCompleteStringArrayQueryParameters(); + + queryParameters.putAll(stringQueryParameters); + queryParameters.putAll(intQueryParameters); + queryParameters.putAll(booleanQueryParameters); + queryParameters.putAll(stringArrayQueryParameters); + + List candidateGroups = new ArrayList<>(); + candidateGroups.add("boss"); + candidateGroups.add("worker"); + + queryParameters.put("candidateGroups", candidateGroups); + + queryParameters.put("includeAssignedTasks", true); + + given().contentType(POST_JSON_CONTENT_TYPE).body(queryParameters) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(TASK_QUERY_URL); + + verifyStringParameterQueryInvocations(); + verifyIntegerParameterQueryInvocations(); + verifyStringArrayParametersInvocations(); + verifyBooleanParameterQueryInvocation(); + + verify(mockQuery).includeAssignedTasks(); + verify(mockQuery).taskCandidateGroupIn(argThat(new EqualsList(candidateGroups))); + } + + @Test + public void testQueryCount() { + given() + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(TASK_COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(TASK_COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void testQueryWithExpressions() { + String testExpression = "${'test-%s'}"; + + ValueGenerator generator = new ValueGenerator(testExpression); + + Map params = new HashMap<>(); + params.put("assigneeExpression", generator.getValue("assigneeExpression")); + params.put("assigneeLikeExpression", generator.getValue("assigneeLikeExpression")); + params.put("ownerExpression", generator.getValue("ownerExpression")); + params.put("involvedUserExpression", generator.getValue("involvedUserExpression")); + params.put("candidateUserExpression", generator.getValue("candidateUserExpression")); + params.put("candidateGroupExpression", generator.getValue("candidateGroupExpression")); + params.put("candidateGroupsExpression", generator.getValue("candidateGroupsExpression")); + params.put("createdBeforeExpression", generator.getValue("createdBeforeExpression")); + params.put("createdOnExpression", generator.getValue("createdOnExpression")); + params.put("createdAfterExpression", generator.getValue("createdAfterExpression")); + params.put("dueBeforeExpression", generator.getValue("dueBeforeExpression")); + params.put("dueDateExpression", generator.getValue("dueDateExpression")); + params.put("dueAfterExpression", generator.getValue("dueAfterExpression")); + params.put("followUpBeforeExpression", generator.getValue("followUpBeforeExpression")); + params.put("followUpDateExpression", generator.getValue("followUpDateExpression")); + params.put("followUpAfterExpression", generator.getValue("followUpAfterExpression")); + params.put("processInstanceBusinessKeyExpression", generator.getValue("processInstanceBusinessKeyExpression")); + params.put("processInstanceBusinessKeyLikeExpression", generator.getValue("processInstanceBusinessKeyLikeExpression")); + params.put("lastUpdatedExpression", generator.getValue("lastUpdatedExpressionExpression")); + + // get + given() + .header(ACCEPT_JSON_HEADER) + .queryParams(params) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(TASK_QUERY_URL); + + verifyExpressionMocks(generator); + + // reset mock + reset(mockQuery); + + // post + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header(ACCEPT_JSON_HEADER) + .body(params) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + verifyExpressionMocks(generator); + + } + + protected void verifyExpressionMocks(ValueGenerator generator) { + verify(mockQuery).taskAssigneeExpression(generator.getValue("assigneeExpression")); + verify(mockQuery).taskAssigneeLikeExpression(generator.getValue("assigneeLikeExpression")); + verify(mockQuery).taskOwnerExpression(generator.getValue("ownerExpression")); + verify(mockQuery).taskInvolvedUserExpression(generator.getValue("involvedUserExpression")); + verify(mockQuery).taskCandidateUserExpression(generator.getValue("candidateUserExpression")); + verify(mockQuery).taskCandidateGroupExpression(generator.getValue("candidateGroupExpression")); + verify(mockQuery).taskCandidateGroupInExpression(generator.getValue("candidateGroupsExpression")); + verify(mockQuery).taskCreatedBeforeExpression(generator.getValue("createdBeforeExpression")); + verify(mockQuery).taskCreatedOnExpression(generator.getValue("createdOnExpression")); + verify(mockQuery).taskCreatedAfterExpression(generator.getValue("createdAfterExpression")); + verify(mockQuery).dueBeforeExpression(generator.getValue("dueBeforeExpression")); + verify(mockQuery).dueDateExpression(generator.getValue("dueDateExpression")); + verify(mockQuery).dueAfterExpression(generator.getValue("dueAfterExpression")); + verify(mockQuery).followUpBeforeExpression(generator.getValue("followUpBeforeExpression")); + verify(mockQuery).followUpDateExpression(generator.getValue("followUpDateExpression")); + verify(mockQuery).followUpAfterExpression(generator.getValue("followUpAfterExpression")); + verify(mockQuery).processInstanceBusinessKeyExpression(generator.getValue("processInstanceBusinessKeyExpression")); + verify(mockQuery).processInstanceBusinessKeyLikeExpression(generator.getValue("processInstanceBusinessKeyLikeExpression")); + + } + + @Test + public void testQueryWithCandidateUsers() { + given().queryParam("withCandidateUsers", true) + .accept(MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).withCandidateUsers(); + } + + @Test + public void testQueryWithoutCandidateUsers() { + given().queryParam("withoutCandidateUsers", true) + .accept(MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery).withoutCandidateUsers(); + } + + @Test + public void testNeverQueryWithCandidateUsers() { + given().queryParam("withCandidateUsers", false) + .accept(MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery, never()).withCandidateUsers(); + } + + @Test + public void testNeverQueryWithoutCandidateUsers() { + given().queryParam("withoutCandidateUsers", false) + .accept(MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery, never()).withoutCandidateUsers(); + } + + @Test + public void testNeverQueryWithCandidateGroups() { + given().queryParam("withCandidateGroups", false) + .accept(MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery, never()).withCandidateGroups(); + } + + @Test + public void testNeverQueryWithoutCandidateGroups() { + given().queryParam("withoutCandidateGroups", false) + .accept(MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(TASK_QUERY_URL); + + verify(mockQuery, never()).withoutCandidateGroups(); + } + + @Test + public void testOrQuery() { + TaskQueryDto queryDto = TaskQueryDto.fromQuery(new TaskQueryImpl() + .or() + .taskName(MockProvider.EXAMPLE_TASK_NAME) + .taskDescription(MockProvider.EXAMPLE_TASK_DESCRIPTION) + .endOr()); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header(ACCEPT_JSON_HEADER) + .body(queryDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(TASK_QUERY_URL); + + ArgumentCaptor argument = ArgumentCaptor.forClass(TaskQueryImpl.class); + verify(((TaskQueryImpl) mockQuery)).addOrQuery(argument.capture()); + assertEquals(MockProvider.EXAMPLE_TASK_NAME, argument.getValue().getName()); + assertEquals(MockProvider.EXAMPLE_TASK_DESCRIPTION, argument.getValue().getDescription()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskVariableLocalRestResourceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskVariableLocalRestResourceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..723e796dd47ac62d9be80125d49b5caba58f2a0d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskVariableLocalRestResourceInteractionTest.java @@ -0,0 +1,1242 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_ID; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.impl.TaskServiceImpl; +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.EqualsList; +import org.camunda.bpm.engine.rest.helper.EqualsMap; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.helper.variable.EqualsNullValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.BooleanValue; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Daniel Meyer + * + */ +public class TaskVariableLocalRestResourceInteractionTest extends + AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String TASK_SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/task"; + protected static final String SINGLE_TASK_URL = TASK_SERVICE_URL + "/{id}"; + + protected static final String SINGLE_TASK_VARIABLES_URL = SINGLE_TASK_URL + "/localVariables"; + protected static final String SINGLE_TASK_SINGLE_VARIABLE_URL = SINGLE_TASK_VARIABLES_URL + "/{varId}"; + protected static final String SINGLE_TASK_PUT_SINGLE_VARIABLE_URL = SINGLE_TASK_SINGLE_VARIABLE_URL; + protected static final String SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL = SINGLE_TASK_PUT_SINGLE_VARIABLE_URL + "/data"; + protected static final String SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL = SINGLE_TASK_SINGLE_VARIABLE_URL; + protected static final String SINGLE_TASK_MODIFY_VARIABLES_URL = SINGLE_TASK_VARIABLES_URL; + + protected TaskService taskServiceMock; + + @Before + public void setUpRuntimeData() { + taskServiceMock = mock(TaskService.class); + when(processEngine.getTaskService()).thenReturn(taskServiceMock); + } + + private TaskServiceImpl mockTaskServiceImpl() { + TaskServiceImpl taskServiceMock = mock(TaskServiceImpl.class); + when(processEngine.getTaskService()).thenReturn(taskServiceMock); + return taskServiceMock; + } + + @Test + public void testGetLocalVariables() { + + when(taskServiceMock.getVariablesLocalTyped(EXAMPLE_TASK_ID, true)).thenReturn(EXAMPLE_VARIABLES); + + Response response = given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) + .when().get(SINGLE_TASK_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + } + + @Test + public void testGetLocalObjectVariables() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(taskServiceMock.getVariablesLocalTyped(eq(EXAMPLE_TASK_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given().pathParam("id", EXAMPLE_TASK_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo(payload)) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_VARIABLES_URL); + + // then + verify(taskServiceMock).getVariablesLocalTyped(EXAMPLE_TASK_ID, true); + } + + @Test + public void testGetLocalObjectVariablesSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(taskServiceMock.getVariablesLocalTyped(eq(EXAMPLE_TASK_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given() + .pathParam("id", EXAMPLE_TASK_ID) + .queryParam("deserializeValues", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo("a serialized value")) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_VARIABLES_URL); + + // then + verify(taskServiceMock).getVariablesLocalTyped(EXAMPLE_TASK_ID, false); + } + + @Test + public void testGetLocalVariablesForNonExistingTaskId() { + when(taskServiceMock.getVariablesLocalTyped(NON_EXISTING_ID, true)).thenThrow(new ProcessEngineException("task " + NON_EXISTING_ID + " doesn't exist")); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("task " + NON_EXISTING_ID + " doesn't exist")) + .when().get(SINGLE_TASK_VARIABLES_URL); + } + + @Test + public void testGetLocalVariablesThrowsAuthorizationException() { + String message = "expected exception"; + when(taskServiceMock.getVariablesLocalTyped(anyString(), anyBoolean())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(SINGLE_TASK_VARIABLES_URL); + } + + @Test + public void testLocalVariableModification() { + TaskServiceImpl taskServiceMock = mockTaskServiceImpl(); + + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + List deletions = new ArrayList(); + deletions.add("deleteKey"); + messageBodyJson.put("deletions", deletions); + + given().pathParam("id", EXAMPLE_TASK_ID).contentType(ContentType.JSON).body(messageBodyJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SINGLE_TASK_MODIFY_VARIABLES_URL); + + Map expectedModifications = new HashMap(); + expectedModifications.put(variableKey, variableValue); + verify(taskServiceMock).updateVariablesLocal(eq(EXAMPLE_TASK_ID), argThat(new EqualsMap(expectedModifications)), + argThat(new EqualsList(deletions))); + } + + @Test + public void testLocalVariableModificationForNonExistingTaskId() { + TaskServiceImpl taskServiceMock = mockTaskServiceImpl(); + doThrow(new ProcessEngineException("Cannot find task with id " + NON_EXISTING_ID)).when(taskServiceMock).updateVariablesLocal(any(), any(), any()); + + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", NON_EXISTING_ID).contentType(ContentType.JSON).body(messageBodyJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for task " + NON_EXISTING_ID + ": Cannot find task with id " + NON_EXISTING_ID)) + .when().post(SINGLE_TASK_MODIFY_VARIABLES_URL); + } + + @Test + public void testEmptyLocalVariableModification() { + mockTaskServiceImpl(); + + given().pathParam("id", EXAMPLE_TASK_ID).contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SINGLE_TASK_MODIFY_VARIABLES_URL); + } + + @Test + public void testVariableModificationThrowsAuthorizationException() { + String variableKey = "aKey"; + int variableValue = 123; + Map messageBodyJson = new HashMap(); + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + TaskServiceImpl taskServiceMock = mockTaskServiceImpl(); + String message = "excpected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).updateVariablesLocal(any(), any(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .post(SINGLE_TASK_MODIFY_VARIABLES_URL); + } + + @Test + public void testGetSingleLocalVariable() { + String variableKey = "aVariableKey"; + int variableValue = 123; + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())) + .thenReturn(Variables.integerValue(variableValue)); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", is(123)) + .body("type", is("Integer")) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + + @Test + public void testGetSingleLocalVariableData() { + + when(taskServiceMock.getVariableLocalTyped(anyString(), eq(EXAMPLE_BYTES_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE_BYTES); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", EXAMPLE_BYTES_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .when() + .get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_TASK_ID, EXAMPLE_BYTES_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalVariableDataNonExisting() { + + when(taskServiceMock.getVariableLocalTyped(anyString(), eq("nonExisting"), eq(false))).thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", "nonExisting") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("task variable with name " + "nonExisting" + " does not exist")) + .when() + .get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_TASK_ID, "nonExisting", false); + } + + @Test + public void testGetSingleLocalVariabledataNotBinary() { + + when(taskServiceMock.getVariableLocalTyped(anyString(), eq(EXAMPLE_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).getVariableLocalTyped(MockProvider.EXAMPLE_TASK_ID, EXAMPLE_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleLocalObjectVariable() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo(payload)) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + + // then + verify(taskServiceMock).getVariableLocalTyped(EXAMPLE_TASK_ID, variableKey, true); + } + + @Test + public void testGetSingleLocalObjectVariableSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo("a serialized value")) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + + // then + verify(taskServiceMock).getVariableLocalTyped(EXAMPLE_TASK_ID, variableKey, false); + } + + @Test + public void testNonExistingLocalVariable() { + String variableKey = "aVariableKey"; + + when(taskServiceMock.getVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey))).thenReturn(null); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("task variable with name " + variableKey + " does not exist")) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetLocalVariableForNonExistingTaskId() { + String variableKey = "aVariableKey"; + + when(taskServiceMock.getVariableLocalTyped(eq(NON_EXISTING_ID), eq(variableKey), anyBoolean())) + .thenThrow(new ProcessEngineException("task " + NON_EXISTING_ID + " doesn't exist")); + + given().pathParam("id", NON_EXISTING_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot get task variable " + variableKey + ": task " + NON_EXISTING_ID + " doesn't exist")) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetSingleLocalVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "excpected exception"; + when(taskServiceMock.getVariableLocalTyped(anyString(), anyString(), anyBoolean())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetFileVariable() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(mimeType).create(); + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON.toString()) + .and() + .body("valueInfo.mimeType", equalTo(mimeType)) + .body("valueInfo.filename", equalTo(filename)) + .body("value", nullValue()) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetNullFileVariable() { + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).mimeType(mimeType).create(); + + when(taskServiceMock.getVariableLocalTyped(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(""))) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithTypeAndEncoding() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + String contentType = response.contentType().replaceAll(" ", ""); + assertThat(contentType, is(ContentType.TEXT + ";charset=" + encoding)); + } + + @Test + public void testGetFileVariableDownloadWithoutType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).create(); + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .and() + .body(is(equalTo(new String(byteContent)))) + .header("Content-Disposition", containsString(filename)) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testCannotDownloadVariableOtherThanFile() { + String variableKey = "aVariableKey"; + BooleanValue variableValue = Variables.booleanValue(true); + + when(taskServiceMock.getVariableLocalTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariable() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsUntypedValue.matcher().value(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeInteger() { + String variableKey = "aVariableKey"; + Integer variableValue = 123; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.integerValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableInteger() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeShort() { + String variableKey = "aVariableKey"; + Short variableValue = 123; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.shortValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableShort() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeLong() { + String variableKey = "aVariableKey"; + Long variableValue = 123L; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.longValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableLong() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeDouble() { + String variableKey = "aVariableKey"; + Double variableValue = 123.456; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.doubleValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDouble() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeBoolean() { + String variableKey = "aVariableKey"; + Boolean variableValue = true; + String type = "Boolean"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.booleanValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeDate() throws Exception { + Date now = new Date(); + String variableKey = "aVariableKey"; + String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now); + String type = "Date"; + + Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.dateValue(expectedValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDate() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Date"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "X"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": Unsupported value type 'X'")) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableWithNoValue() { + String variableKey = "aVariableKey"; + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsNullValue.matcher())); + } + + @Test + public void testPutLocalVariableForNonExistingTaskId() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new ProcessEngineException("Cannot find task with id " + NON_EXISTING_ID)) + .when(taskServiceMock).setVariableLocal(eq(NON_EXISTING_ID), eq(variableKey), any()); + + given().pathParam("id", NON_EXISTING_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot put task variable " + variableKey + ": Cannot find task with id " + NON_EXISTING_ID)) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "String"; + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).setVariableLocal(anyString(), anyString(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPostSingleLocalBinaryVariable() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPostSingleLocalBinaryVariableWithValueType() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "Bytes", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPostSingleLocalBinaryVariableWithNoValue() throws Exception { + byte[] bytes = new byte[0]; + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleBinaryVariableThrowsAuthorizationException() { + byte[] bytes = "someContent".getBytes(); + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).setVariableLocal(anyString(), anyString(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .multiPart("data", "unspecified", bytes) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleLocalSerializableVariable() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable))); + } + + @Test + public void testPostSingleLocalSerializableVariableUnsupportedMediaType() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, "unsupported") + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Unrecognized content type for serialized java type: unsupported")) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock, never()).setVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey), + eq(serializable)); + } + + @Test + public void testPostSingleLocalFileVariableWithEncodingAndMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype + "; encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(taskServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(encoding)); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleLocalFileVariableWithMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String base64 = Base64.encodeBase64String(value); + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(taskServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleLocalFileVariableWithEncoding() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, "encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + //when the user passes an encoding, he has to provide the type, too + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleLocalFileVariableOnlyFilename() throws Exception { + + String variableKey = "aVariableKey"; + String filename = "test.txt"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, new byte[0]) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(taskServiceMock).setVariableLocal(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(MediaType.APPLICATION_OCTET_STREAM)); + assertThat(captured.getValue().available(), is(0)); + } + + @Test + public void testPutSingleLocalVariableFromSerialized() throws Exception { + String serializedValue = "{\"prop\" : \"value\"}"; + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, ValueType.OBJECT.getName(), "aDataFormat", "aRootType"); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal( + eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher() + .serializedValue(serializedValue) + .serializationFormat("aDataFormat") + .objectTypeName("aRootType"))); + } + + @Test + public void testPutSingleLocalVariableFromInvalidSerialized() throws Exception { + String serializedValue = "{\"prop\" : \"value\"}"; + + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, "aNonExistingType", null, null); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable aVariableKey: Unsupported value type 'aNonExistingType'")) + .when() + .put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleLocalVariableFromSerializedWithNoValue() { + String variableKey = "aVariableKey"; + + Map requestJson = VariablesBuilder + .getObjectValueMap(null, ValueType.OBJECT.getName(), null, null); + + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(requestJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariableLocal( + eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher())); + } + + @Test + public void testDeleteSingleLocalVariable() { + String variableKey = "aVariableKey"; + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).removeVariableLocal(eq(EXAMPLE_TASK_ID), eq(variableKey)); + } + + @Test + public void testDeleteLocalVariableForNonExistingTaskId() { + String variableKey = "aVariableKey"; + + doThrow(new ProcessEngineException("Cannot find task with id " + NON_EXISTING_ID)) + .when(taskServiceMock).removeVariableLocal(eq(NON_EXISTING_ID), eq(variableKey)); + + given().pathParam("id", NON_EXISTING_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot delete task variable " + variableKey + ": Cannot find task with id " + NON_EXISTING_ID)) + .when().delete(SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL); + } + + @Test + public void testDeleteVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).removeVariableLocal(anyString(), anyString()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .delete(SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskVariableRestResourceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskVariableRestResourceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1540cdf92044b99291c58dbaecd0f35d44263659 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TaskVariableRestResourceInteractionTest.java @@ -0,0 +1,1267 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TASK_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_ID; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.anyString; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.TaskService; +import org.camunda.bpm.engine.impl.TaskServiceImpl; +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.impl.util.IoUtil; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.EqualsList; +import org.camunda.bpm.engine.rest.helper.EqualsMap; +import org.camunda.bpm.engine.rest.helper.ErrorMessageHelper; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.helper.variable.EqualsNullValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsObjectValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.helper.variable.EqualsUntypedValue; +import org.camunda.bpm.engine.rest.util.VariablesBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.BooleanValue; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Daniel Meyer + * + */ +public class TaskVariableRestResourceInteractionTest extends + AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String TASK_SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/task"; + protected static final String SINGLE_TASK_URL = TASK_SERVICE_URL + "/{id}"; + + protected static final String SINGLE_TASK_VARIABLES_URL = SINGLE_TASK_URL + "/variables"; + protected static final String SINGLE_TASK_SINGLE_VARIABLE_URL = SINGLE_TASK_VARIABLES_URL + "/{varId}"; + protected static final String SINGLE_TASK_PUT_SINGLE_VARIABLE_URL = SINGLE_TASK_SINGLE_VARIABLE_URL; + protected static final String SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL = SINGLE_TASK_PUT_SINGLE_VARIABLE_URL + "/data"; + protected static final String SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL = SINGLE_TASK_SINGLE_VARIABLE_URL; + protected static final String SINGLE_TASK_MODIFY_VARIABLES_URL = SINGLE_TASK_VARIABLES_URL; + + protected TaskService taskServiceMock; + + @Before + public void setUpRuntimeData() { + taskServiceMock = mock(TaskService.class); + when(processEngine.getTaskService()).thenReturn(taskServiceMock); + } + + private TaskServiceImpl mockTaskServiceImpl() { + TaskServiceImpl taskServiceMock = mock(TaskServiceImpl.class); + when(processEngine.getTaskService()).thenReturn(taskServiceMock); + return taskServiceMock; + } + + @Test + public void testGetVariables() { + + when(taskServiceMock.getVariablesTyped(EXAMPLE_TASK_ID, true)).thenReturn(EXAMPLE_VARIABLES); + + Response response = given().pathParam("id", EXAMPLE_TASK_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(EXAMPLE_VARIABLE_KEY, notNullValue()) + .body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) + .body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) + .when().get(SINGLE_TASK_VARIABLES_URL); + + Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); + } + + @Test + public void testGetObjectVariables() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(taskServiceMock.getVariablesTyped(eq(EXAMPLE_TASK_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given().pathParam("id", EXAMPLE_TASK_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo(payload)) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_VARIABLES_URL); + + // then + verify(taskServiceMock).getVariablesTyped(EXAMPLE_TASK_ID, true); + } + + @Test + public void testGetObjectVariablesSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(taskServiceMock.getVariablesTyped(eq(EXAMPLE_TASK_ID), anyBoolean())) + .thenReturn(Variables.createVariables().putValueTyped(variableKey, variableValue)); + + // when + given() + .pathParam("id", EXAMPLE_TASK_ID) + .queryParam("deserializeValues", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body(variableKey + ".value", equalTo("a serialized value")) + .body(variableKey + ".type", equalTo("Object")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body(variableKey + ".valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_VARIABLES_URL); + + // then + verify(taskServiceMock).getVariablesTyped(EXAMPLE_TASK_ID, false); + } + + @Test + public void testGetVariablesForNonExistingTaskId() { + when(taskServiceMock.getVariablesTyped(NON_EXISTING_ID, true)).thenThrow(new ProcessEngineException("task " + NON_EXISTING_ID + " doesn't exist")); + + given().pathParam("id", NON_EXISTING_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("task " + NON_EXISTING_ID + " doesn't exist")) + .when().get(SINGLE_TASK_VARIABLES_URL); + } + + @Test + public void testGetVariablesThrowsAuthorizationException() { + String message = "expected exception"; + when(taskServiceMock.getVariablesTyped(anyString(), anyBoolean())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(SINGLE_TASK_VARIABLES_URL); + } + + @Test + public void testVariableModification() { + TaskServiceImpl taskServiceMock = mockTaskServiceImpl(); + + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + List deletions = new ArrayList(); + deletions.add("deleteKey"); + messageBodyJson.put("deletions", deletions); + + given().pathParam("id", EXAMPLE_TASK_ID).contentType(ContentType.JSON).body(messageBodyJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SINGLE_TASK_MODIFY_VARIABLES_URL); + + Map expectedModifications = new HashMap(); + expectedModifications.put(variableKey, variableValue); + verify(taskServiceMock).updateVariables(eq(EXAMPLE_TASK_ID), argThat(new EqualsMap(expectedModifications)), + argThat(new EqualsList(deletions))); + } + + @Test + public void testVariableModificationForNonExistingTaskId() { + TaskServiceImpl taskServiceMock = mockTaskServiceImpl(); + doThrow(new ProcessEngineException("Cannot find task with id " + NON_EXISTING_ID)).when(taskServiceMock).updateVariables(any(), any(), any()); + + Map messageBodyJson = new HashMap(); + + String variableKey = "aKey"; + int variableValue = 123; + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + given().pathParam("id", NON_EXISTING_ID).contentType(ContentType.JSON).body(messageBodyJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(RestException.class.getSimpleName())) + .body("message", equalTo("Cannot modify variables for task " + NON_EXISTING_ID + ": Cannot find task with id " + NON_EXISTING_ID)) + .when().post(SINGLE_TASK_MODIFY_VARIABLES_URL); + } + + @Test + public void testEmptyVariableModification() { + mockTaskServiceImpl(); + + given().pathParam("id", EXAMPLE_TASK_ID).contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().post(SINGLE_TASK_MODIFY_VARIABLES_URL); + } + + @Test + public void testVariableModificationThrowsAuthorizationException() { + String variableKey = "aKey"; + int variableValue = 123; + Map messageBodyJson = new HashMap(); + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + TaskServiceImpl taskServiceMock = mockTaskServiceImpl(); + String message = "excpected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).updateVariables(any(), any(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .post(SINGLE_TASK_MODIFY_VARIABLES_URL); + } + + @Test + public void shouldReturnErrorOnModification() { + String variableKey = "aKey"; + int variableValue = 123; + Map messageBodyJson = new HashMap<>(); + Map modifications = VariablesBuilder.create().variable(variableKey, variableValue).getVariables(); + messageBodyJson.put("modifications", modifications); + + TaskServiceImpl taskServiceMock = mockTaskServiceImpl(); + doThrow(new ProcessEngineException("foo", 123)) + .when(taskServiceMock).updateVariables(any(), any(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .contentType(ContentType.JSON) + .body(messageBodyJson) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot modify variables for task anId: foo")) + .body("code", is(123)) + .when() + .post(SINGLE_TASK_MODIFY_VARIABLES_URL); + } + + @Test + public void testGetSingleVariable() { + String variableKey = "aVariableKey"; + int variableValue = 123; + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())) + .thenReturn(Variables.integerValue(variableValue)); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", is(123)) + .body("type", is("Integer")) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetSingleVariableData() { + + when(taskServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_BYTES_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE_BYTES); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", EXAMPLE_BYTES_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .when() + .get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).getVariableTyped(MockProvider.EXAMPLE_TASK_ID, EXAMPLE_BYTES_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleVariableDataNonExisting() { + + when(taskServiceMock.getVariableTyped(anyString(), eq("nonExisting"), eq(false))).thenReturn(null); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", "nonExisting") + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("task variable with name " + "nonExisting" + " does not exist")) + .when() + .get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).getVariableTyped(MockProvider.EXAMPLE_TASK_ID, "nonExisting", false); + } + + @Test + public void testGetSingleVariabledataNotBinary() { + + when(taskServiceMock.getVariableTyped(anyString(), eq(EXAMPLE_VARIABLE_KEY), eq(false))).thenReturn(EXAMPLE_VARIABLE_VALUE); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).getVariableTyped(MockProvider.EXAMPLE_TASK_ID, EXAMPLE_VARIABLE_KEY, false); + } + + @Test + public void testGetSingleObjectVariable() { + // given + String variableKey = "aVariableId"; + + List payload = Arrays.asList("a", "b"); + ObjectValue variableValue = + MockObjectValue + .fromObjectValue(Variables + .objectValue(payload) + .serializationDataFormat("application/json") + .create()) + .objectTypeName(ArrayList.class.getName()) + .serializedValue("a serialized value"); // this should differ from the serialized json + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo(payload)) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + + // then + verify(taskServiceMock).getVariableTyped(EXAMPLE_TASK_ID, variableKey, true); + } + + @Test + public void testGetSingleObjectVariableSerialized() { + // given + String variableKey = "aVariableId"; + + ObjectValue variableValue = + Variables + .serializedObjectValue("a serialized value") + .serializationDataFormat("application/json") + .objectTypeName(ArrayList.class.getName()) + .create(); + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + // when + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("value", equalTo("a serialized value")) + .body("type", equalTo("Object")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo("application/json")) + .body("valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(ArrayList.class.getName())) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + + // then + verify(taskServiceMock).getVariableTyped(EXAMPLE_TASK_ID, variableKey, false); + } + + @Test + public void testNonExistingVariable() { + String variableKey = "aVariableKey"; + + when(taskServiceMock.getVariable(eq(EXAMPLE_TASK_ID), eq(variableKey))).thenReturn(null); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", is(InvalidRequestException.class.getSimpleName())) + .body("message", is("task variable with name " + variableKey + " does not exist")) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetVariableForNonExistingTaskId() { + String variableKey = "aVariableKey"; + + when(taskServiceMock.getVariableTyped(eq(NON_EXISTING_ID), eq(variableKey), anyBoolean())) + .thenThrow(new ProcessEngineException("task " + NON_EXISTING_ID + " doesn't exist")); + + given().pathParam("id", NON_EXISTING_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot get task variable " + variableKey + ": task " + NON_EXISTING_ID + " doesn't exist")) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetSingleVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "excpected exception"; + when(taskServiceMock.getVariableTyped(anyString(), anyString(), anyBoolean())).thenThrow(new AuthorizationException(message)); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetFileVariable() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(mimeType).create(); + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON.toString()) + .and() + .body("valueInfo.mimeType", equalTo(mimeType)) + .body("valueInfo.filename", equalTo(filename)) + .body("value", nullValue()) + .when().get(SINGLE_TASK_SINGLE_VARIABLE_URL); + } + + @Test + public void testGetNullFileVariable() { + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimeType = "text/plain"; + FileValue variableValue = Variables.fileValue(filename).mimeType(mimeType).create(); + + when(taskServiceMock.getVariableTyped(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())) + .thenReturn(variableValue); + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(""))) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT.toString()) + .and() + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testGetFileVariableDownloadWithTypeAndEncoding() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + Response response = given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body(is(equalTo(new String(byteContent)))) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + String contentType = response.contentType().replaceAll(" ", ""); + assertThat(contentType, is(ContentType.TEXT + ";charset=" + encoding)); + } + + @Test + public void testGetFileVariableDownloadWithoutType() { + String variableKey = "aVariableKey"; + final byte[] byteContent = "some bytes".getBytes(); + String filename = "test.txt"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).create(); + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(MediaType.APPLICATION_OCTET_STREAM) + .and() + .body(is(equalTo(new String(byteContent)))) + .header("Content-Disposition", containsString(filename)) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testCannotDownloadVariableOtherThanFile() { + String variableKey = "aVariableKey"; + BooleanValue variableValue = Variables.booleanValue(true); + + when(taskServiceMock.getVariableTyped(eq(EXAMPLE_TASK_ID), eq(variableKey), anyBoolean())).thenReturn(variableValue); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testPutSingleVariable() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsUntypedValue.matcher().value(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeInteger() { + String variableKey = "aVariableKey"; + Integer variableValue = 123; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.integerValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableInteger() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Integer"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Integer.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeShort() { + String variableKey = "aVariableKey"; + Short variableValue = 123; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.shortValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableShort() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Short"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Short.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeLong() { + String variableKey = "aVariableKey"; + Long variableValue = 123L; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.longValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableLong() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Long"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", MockProvider.EXAMPLE_EXECUTION_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Long.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeDouble() { + String variableKey = "aVariableKey"; + Double variableValue = 123.456; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.doubleValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDouble() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Double"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Double.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithTypeBoolean() { + String variableKey = "aVariableKey"; + Boolean variableValue = true; + String type = "Boolean"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.booleanValue(variableValue))); + } + + @Test + public void testPutSingleVariableWithTypeDate() throws Exception { + Date now = new Date(); + + String variableKey = "aVariableKey"; + String variableValue = DATE_FORMAT_WITH_TIMEZONE.format(now); + String type = "Date"; + + Date expectedValue = DATE_FORMAT_WITH_TIMEZONE.parse(variableValue); + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.dateValue(expectedValue))); + } + + @Test + public void testPutSingleVariableWithUnparseableDate() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "Date"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": " + + ErrorMessageHelper.getExpectedFailingConversionMessage(variableValue, type, Date.class))) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNotSupportedType() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "X"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable " + variableKey + ": Unsupported value type 'X'")) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableWithNoValue() { + String variableKey = "aVariableKey"; + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsNullValue.matcher())); + } + + @Test + public void testPutVariableForNonExistingTaskId() { + String variableKey = "aVariableKey"; + String variableValue = "aVariableValue"; + + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue); + + doThrow(new ProcessEngineException("Cannot find task with id " + NON_EXISTING_ID)) + .when(taskServiceMock).setVariable(eq(NON_EXISTING_ID), eq(variableKey), any()); + + given().pathParam("id", NON_EXISTING_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(variableJson) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot put task variable " + variableKey + ": Cannot find task with id " + NON_EXISTING_ID)) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + String variableValue = "1abc"; + String type = "String"; + Map variableJson = VariablesBuilder.getVariableValueMap(variableValue, type); + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).setVariable(anyString(), anyString(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(variableJson) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPostSingleBinaryVariable() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPostSingleBinaryVariableWithValueType() throws Exception { + byte[] bytes = "someContent".getBytes(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .multiPart("valueType", "Bytes", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPostSingleBinaryVariableWithNoValue() throws Exception { + byte[] bytes = new byte[0]; + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", null, bytes) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsPrimitiveValue.bytesValue(bytes))); + } + + @Test + public void testPutSingleBinaryVariableThrowsAuthorizationException() { + byte[] bytes = "someContent".getBytes(); + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).setVariable(anyString(), anyString(), any()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .multiPart("data", "unspecified", bytes) + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleSerializableVariable() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, MediaType.APPLICATION_JSON) + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher().isDeserialized().value(serializable))); + } + + @Test + public void testPostSingleSerializableVariableUnsupportedMediaType() throws Exception { + + ArrayList serializable = new ArrayList(); + serializable.add("foo"); + + ObjectMapper mapper = new ObjectMapper(); + String jsonBytes = mapper.writeValueAsString(serializable); + String typeName = TypeFactory.defaultInstance().constructType(serializable.getClass()).toCanonical(); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", jsonBytes, "unsupported") + .multiPart("type", typeName, MediaType.TEXT_PLAIN) + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Unrecognized content type for serialized java type: unsupported")) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + verify(taskServiceMock, never()).setVariable(eq(EXAMPLE_TASK_ID), eq(variableKey), + eq(serializable)); + } + + @Test + public void testPostSingleFileVariableWithEncodingAndMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype + "; encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(taskServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(encoding)); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleFileVariableWithMimeType() throws Exception { + + byte[] value = "some text".getBytes(); + String base64 = Base64.encodeBase64String(value); + String variableKey = "aVariableKey"; + String filename = "test.txt"; + String mimetype = MediaType.TEXT_PLAIN; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, mimetype) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(taskServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(mimetype)); + assertThat(IoUtil.readInputStream(captured.getValue(), null), is(value)); + } + + @Test + public void testPostSingleFileVariableWithEncoding() throws Exception { + + byte[] value = "some text".getBytes(); + String variableKey = "aVariableKey"; + String encoding = "utf-8"; + String filename = "test.txt"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, value, "encoding="+encoding) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + //when the user passes an encoding, he has to provide the type, too + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + } + + @Test + public void testPostSingleFileVariableOnlyFilename() throws Exception { + + String variableKey = "aVariableKey"; + String filename = "test.txt"; + + given() + .pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .multiPart("data", filename, new byte[0]) + .multiPart("valueType", "File", "text/plain") + .header("accept", MediaType.APPLICATION_JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(SINGLE_TASK_SINGLE_BINARY_VARIABLE_URL); + + ArgumentCaptor captor = ArgumentCaptor.forClass(FileValue.class); + verify(taskServiceMock).setVariable(eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + captor.capture()); + FileValue captured = captor.getValue(); + assertThat(captured.getEncoding(), is(nullValue())); + assertThat(captured.getFilename(), is(filename)); + assertThat(captured.getMimeType(), is(MediaType.APPLICATION_OCTET_STREAM)); + assertThat(captured.getValue().available(), is(0)); + } + + @Test + public void testPutSingleVariableFromSerialized() throws Exception { + String serializedValue = "{\"prop\" : \"value\"}"; + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, ValueType.OBJECT.getName(), "aDataFormat", "aRootType"); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable( + eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher() + .serializedValue(serializedValue) + .serializationFormat("aDataFormat") + .objectTypeName("aRootType"))); + } + + @Test + public void testPutSingleVariableFromInvalidSerialized() throws Exception { + String serializedValue = "{\"prop\" : \"value\"}"; + + Map requestJson = VariablesBuilder + .getObjectValueMap(serializedValue, "aNonExistingType", null, null); + + String variableKey = "aVariableKey"; + + given() + .pathParam("id", MockProvider.EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON) + .body(requestJson) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot put task variable aVariableKey: Unsupported value type 'aNonExistingType'")) + .when() + .put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + } + + @Test + public void testPutSingleVariableFromSerializedWithNoValue() { + String variableKey = "aVariableKey"; + + Map requestJson = VariablesBuilder + .getObjectValueMap(null, ValueType.OBJECT.getName(), null, null); + + given().pathParam("id", MockProvider.EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .contentType(ContentType.JSON).body(requestJson) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().put(SINGLE_TASK_PUT_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).setVariable( + eq(MockProvider.EXAMPLE_TASK_ID), eq(variableKey), + argThat(EqualsObjectValue.objectValueMatcher())); + } + + @Test + public void testDeleteSingleVariable() { + String variableKey = "aVariableKey"; + + given().pathParam("id", EXAMPLE_TASK_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL); + + verify(taskServiceMock).removeVariable(eq(EXAMPLE_TASK_ID), eq(variableKey)); + } + + @Test + public void testDeleteVariableForNonExistingTaskId() { + String variableKey = "aVariableKey"; + + doThrow(new ProcessEngineException("Cannot find task with id " + NON_EXISTING_ID)) + .when(taskServiceMock).removeVariable(eq(NON_EXISTING_ID), eq(variableKey)); + + given().pathParam("id", NON_EXISTING_ID).pathParam("varId", variableKey) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(RestException.class.getSimpleName())) + .body("message", is("Cannot delete task variable " + variableKey + ": Cannot find task with id " + NON_EXISTING_ID)) + .when().delete(SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL); + } + + @Test + public void testDeleteVariableThrowsAuthorizationException() { + String variableKey = "aVariableKey"; + + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(taskServiceMock).removeVariable(anyString(), anyString()); + + given() + .pathParam("id", EXAMPLE_TASK_ID) + .pathParam("varId", variableKey) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", is(AuthorizationException.class.getSimpleName())) + .body("message", is(message)) + .when() + .delete(SINGLE_TASK_DELETE_SINGLE_VARIABLE_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TelemetryRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TelemetryRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e61906e6376965e04c6f09b38f7fdcffd0fb4878 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TelemetryRestServiceTest.java @@ -0,0 +1,180 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.telemetry.ApplicationServer; +import org.camunda.bpm.engine.telemetry.Database; +import org.camunda.bpm.engine.telemetry.Internals; +import org.camunda.bpm.engine.telemetry.Jdk; +import org.camunda.bpm.engine.telemetry.Product; +import org.camunda.bpm.engine.telemetry.TelemetryData; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; + +import io.restassured.http.ContentType; + +public class TelemetryRestServiceTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String TELEMETRY_URL = TEST_RESOURCE_ROOT_PATH + TelemetryRestService.PATH; + protected static final String TELEMETRY_CONFIG_URL = TELEMETRY_URL + "/configuration"; + protected static final String TELEMETRY_DATA_URL = TELEMETRY_URL + "/data"; + + protected ManagementService managementServiceMock; + + + @Before + public void setupMocks() { + managementServiceMock = mock(ManagementService.class); + when(processEngine.getManagementService()).thenReturn(managementServiceMock); + } + + @Test + public void shouldDisableTelemetry() { + Map requestBody = new HashMap<>(); + requestBody.put("enableTelemetry", false); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(requestBody) + .then() + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(TELEMETRY_CONFIG_URL); + + verify(managementServiceMock).toggleTelemetry(false); + } + + @Test + public void shouldFetchDisabledTelemetryConfiguration() { + when(managementServiceMock.isTelemetryEnabled()).thenReturn(false); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("enableTelemetry", equalTo(false)) + .when() + .get(TELEMETRY_CONFIG_URL); + + verify(managementServiceMock).isTelemetryEnabled(); + } + + @Test + public void shouldGetTelemetryData() throws JsonProcessingException { + when(managementServiceMock.getTelemetryData()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_DATA); + + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("installation", equalTo(MockProvider.EXAMPLE_TELEMETRY_INSTALLATION_ID)) + .body("product.name", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_NAME)) + .body("product.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_VERSION)) + .body("product.edition", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_EDITION)) + .body("product.internals.database.vendor", equalTo(MockProvider.EXAMPLE_TELEMETRY_DB_VENDOR)) + .body("product.internals.database.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_DB_VERSION)) + .body("product.internals.commands.FetchExternalTasksCmd.count", equalTo(100)) + .body("product.internals.commands.StartProcessInstanceCmd.count", equalTo(40)) + .body("product.internals.metrics.process-instances.count", equalTo(936)) + .body("product.internals.metrics.flow-node-instances.count", equalTo(6125)) + .body("product.internals.metrics.executed-decision-elements.count", equalTo(732)) + .body("product.internals.metrics.decision-instances.count", equalTo(140)) + .body("product.internals.webapps[0]", equalTo("cockpit")) + .body("product.internals.jdk.vendor", equalTo(MockProvider.EXAMPLE_TELEMETRY_JDK_VENDOR)) + .body("product.internals.jdk.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_JDK_VERSION)) + .body("product.internals.application-server.vendor", equalTo(MockProvider.EXAMPLE_TELEMETRY_APP_SERVER_VENDOR)) + .body("product.internals.application-server.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_APP_SERVER_VERSION)) + .body("product.internals.license-key.customer", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_CUSTOMER_NAME)) + .body("product.internals.license-key.type", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_TYPE)) + .body("product.internals.license-key.features.camundaBPM", equalTo("true")) + .body("product.internals.license-key.raw", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_RAW)) + .body("product.internals.license-key.unlimited", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_UNLIMITED)) + .body("product.internals.license-key.valid-until", equalTo(MockProvider.EXAMPLE_TELEMETRY_LICENSE_VALID_UNTIL)) + .body("product.internals.camunda-integration[0]", equalTo("spring-boot")) + .body("product.internals.data-collection-start-date", equalTo(MockProvider.EXAMPLE_TELEMETRY_DATA_COLLECTION_START_DATE)) + .when() + .get(TELEMETRY_DATA_URL); + + verify(managementServiceMock).getTelemetryData(); + } + + @Test + public void shouldGetMinimalTelemetryData() { + + TelemetryData telemetryData = mock(TelemetryData.class); + when(telemetryData.getInstallation()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_INSTALLATION_ID); + + Product product = mock(Product.class); + when(product.getName()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_NAME); + when(product.getVersion()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_VERSION); + when(product.getEdition()).thenReturn(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_EDITION); + when(telemetryData.getProduct()).thenReturn(product); + + Internals internals = mock(Internals.class); + when(product.getInternals()).thenReturn(internals); + + when(internals.getApplicationServer()).thenReturn(mock(ApplicationServer.class)); + when(internals.getCamundaIntegration()).thenReturn(new HashSet<>()); + when(internals.getCommands()).thenReturn(new HashMap<>()); + when(internals.getDatabase()).thenReturn(mock(Database.class)); + when(internals.getJdk()).thenReturn(mock(Jdk.class)); + when(internals.getMetrics()).thenReturn(new HashMap<>()); + when(internals.getWebapps()).thenReturn(new HashSet<>()); + // license key may be null and is therefore not mocked + + when(managementServiceMock.getTelemetryData()).thenReturn(telemetryData); + + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("installation", equalTo(MockProvider.EXAMPLE_TELEMETRY_INSTALLATION_ID)) + .body("product.name", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_NAME)) + .body("product.version", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_VERSION)) + .body("product.edition", equalTo(MockProvider.EXAMPLE_TELEMETRY_PRODUCT_EDITION)) + .when() + .get(TELEMETRY_DATA_URL); + + verify(managementServiceMock).getTelemetryData(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TenantRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TenantRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3c8fb52002e89ee72a8e5da0fd097af4456b4306 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TenantRestServiceInteractionTest.java @@ -0,0 +1,932 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.authorization.Authorization.ANY; +import static org.camunda.bpm.engine.authorization.Permissions.CREATE; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.TENANT; +import static org.camunda.bpm.engine.authorization.Resources.TENANT_MEMBERSHIP; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.identity.TenantQuery; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.dto.identity.TenantDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; + +public class TenantRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/tenant"; + protected static final String TENANT_URL = SERVICE_URL + "/{id}"; + protected static final String TENANT_CREATE_URL = SERVICE_URL + "/create"; + protected static final String TENANT_USER_MEMBERS_URL = TENANT_URL + "/user-members"; + protected static final String TENANT_USER_MEMBER_URL = TENANT_USER_MEMBERS_URL + "/{userId}"; + protected static final String TENANT_GROUP_MEMBERS_URL = TENANT_URL + "/group-members"; + protected static final String TENANT_GROUP_MEMBER_URL = TENANT_GROUP_MEMBERS_URL + "/{groupId}"; + + protected IdentityService identityServiceMock; + protected AuthorizationService authorizationServiceMock; + protected ProcessEngineConfiguration processEngineConfigurationMock; + + protected Tenant mockTenant; + protected TenantQuery mockQuery; + + @Before + public void setupData() { + + identityServiceMock = mock(IdentityService.class); + authorizationServiceMock = mock(AuthorizationService.class); + processEngineConfigurationMock = mock(ProcessEngineConfiguration.class); + + // mock identity service + when(processEngine.getIdentityService()).thenReturn(identityServiceMock); + // authorization service + when(processEngine.getAuthorizationService()).thenReturn(authorizationServiceMock); + // process engine configuration + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationMock); + + mockTenant = MockProvider.createMockTenant(); + mockQuery = setUpMockQuery(mockTenant); + } + + protected TenantQuery setUpMockQuery(Tenant tenant) { + TenantQuery query = mock(TenantQuery.class); + when(query.tenantId(anyString())).thenReturn(query); + when(query.singleResult()).thenReturn(tenant); + + when(identityServiceMock.createTenantQuery()).thenReturn(query); + + return query; + } + + @Test + public void getTenant() { + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("name", equalTo(MockProvider.EXAMPLE_TENANT_NAME)) + .when() + .get(TENANT_URL); + } + + @Test + public void getNonExistingTenant() { + when(mockQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", "aNonExistingTenant") + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Tenant with id aNonExistingTenant does not exist")) + .when() + .get(TENANT_URL); + } + + @Test + public void deleteTenant() { + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(TENANT_URL); + } + + @Test + public void deleteNonExistingTenant() { + given().pathParam("id", "aNonExistingTenant") + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(TENANT_URL); + } + + @Test + public void deleteTenantThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).deleteTenant(MockProvider.EXAMPLE_TENANT_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(TENANT_URL); + } + + @Test + public void updateTenant() { + Tenant updatedTenant = MockProvider.createMockTenant(); + when(updatedTenant.getName()).thenReturn("updatedName"); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .body(TenantDto.fromTenant(updatedTenant)) + .contentType(ContentType.JSON) + .then() + .expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(TENANT_URL); + + // tenant was updated + verify(mockTenant).setName(updatedTenant.getName()); + + // and then saved + verify(identityServiceMock).saveTenant(mockTenant); + } + + @Test + public void updateNonExistingTenant() { + Tenant updatedTenant = MockProvider.createMockTenant(); + when(updatedTenant.getName()).thenReturn("updatedName"); + + when(mockQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", "aNonExistingTenant") + .body(TenantDto.fromTenant(updatedTenant)) + .contentType(ContentType.JSON) + .then() + .expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Tenant with id aNonExistingTenant does not exist")) + .when() + .put(TENANT_URL); + + verify(identityServiceMock, never()).saveTenant(any(Tenant.class)); + } + + @Test + public void updateTenantThrowsAuthorizationException() { + Tenant updatedTenant = MockProvider.createMockTenant(); + when(updatedTenant.getName()).thenReturn("updatedName"); + + String message = "exception expected"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).saveTenant(any(Tenant.class)); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .body(TenantDto.fromTenant(updatedTenant)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(TENANT_URL); + } + + @Test + public void createTenant() { + Tenant newTenant = MockProvider.createMockTenant(); + when(identityServiceMock.newTenant(MockProvider.EXAMPLE_TENANT_ID)).thenReturn(newTenant); + + given() + .body(TenantDto.fromTenant(mockTenant)).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(TENANT_CREATE_URL); + + verify(identityServiceMock).newTenant(MockProvider.EXAMPLE_TENANT_ID); + verify(newTenant).setName(MockProvider.EXAMPLE_TENANT_NAME); + verify(identityServiceMock).saveTenant(newTenant); + } + + @Test + public void createExistingTenant() { + Tenant newTenant = MockProvider.createMockTenant(); + when(identityServiceMock.newTenant(MockProvider.EXAMPLE_TENANT_ID)).thenReturn(newTenant); + + String message = "exception expected"; + doThrow(new ProcessEngineException(message)).when(identityServiceMock).saveTenant(newTenant); + + given() + .body(TenantDto.fromTenant(newTenant)).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(TENANT_CREATE_URL); + } + + @Test + public void createTenantThrowsAuthorizationException() { + Tenant newTenant = MockProvider.createMockTenant(); + + String message = "exception expected"; + when(identityServiceMock.newTenant(MockProvider.EXAMPLE_TENANT_ID)).thenThrow(new AuthorizationException(message)); + + given() + .body(TenantDto.fromTenant(newTenant)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(TENANT_CREATE_URL); + } + + @Test + public void saveTenantThrowsAuthorizationException() { + Tenant newTenant = MockProvider.createMockTenant(); + when(identityServiceMock.newTenant(MockProvider.EXAMPLE_TENANT_ID)).thenReturn(newTenant); + + String message = "exception expected"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).saveTenant(newTenant); + + given() + .body(TenantDto.fromTenant(newTenant)) + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(TENANT_CREATE_URL); + } + + @Test + public void userRestServiceOptionUnauthenticated() { + String fullAuthorizationUrl = getFullAuthorizationUrl(); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl+"/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl+"/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_URL); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void userRestServiceOptionUnauthorized() { + String fullAuthorizationUrl = getFullAuthorizationUrl(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT, ANY)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl+"/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2]", nullValue()) + + .when() + .options(SERVICE_URL); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void userRestServiceOptionAuthorized() { + String fullAuthorizationUrl = getFullAuthorizationUrl(); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT, ANY)).thenReturn(true); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl+"/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl+"/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_URL); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + } + + @Test + public void userRestServiceOptionsWithAuthorizationDisabled() { + String fullAuthorizationUrl = getFullAuthorizationUrl(); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl + "/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl + "/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void tenantResourceOptionsUnauthenticated() { + String fullTenantUrl = getFullAuthorizationTenantUrl(); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullTenantUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullTenantUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullTenantUrl)) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when().options(TENANT_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + } + + @Test + public void tenantResourceOptionsUnauthorized() { + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, TENANT, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(false); + + String fullTenantUrl = getFullAuthorizationTenantUrl(); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullTenantUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1]", nullValue()) + .body("links[2]", nullValue()) + + .when().options(TENANT_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT, MockProvider.EXAMPLE_TENANT_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, TENANT, MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void tenantResourceOptionsAuthorized() { + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, TENANT, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(false); + + String fullTenantUrl = getFullAuthorizationTenantUrl(); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullTenantUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullTenantUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2]", nullValue()) + + .when().options(TENANT_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT, MockProvider.EXAMPLE_TENANT_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, TENANT, MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void tenantResourceOptionsWithAuthorizationDisabled() { + String fullTenantUrl = getFullAuthorizationTenantUrl(); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullTenantUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullTenantUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullTenantUrl)) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when() + .options(TENANT_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void createTenantUserMembership() { + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(TENANT_USER_MEMBER_URL); + + verify(identityServiceMock).createTenantUserMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_USER_ID); + } + + @Test + public void createTenantGroupMembership() { + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("groupId", MockProvider.EXAMPLE_GROUP_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(TENANT_GROUP_MEMBER_URL); + + verify(identityServiceMock).createTenantGroupMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void createTenantUserMembershipThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).createTenantUserMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_USER_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(TENANT_USER_MEMBER_URL); + } + + @Test + public void deleteTenantUserMembership() { + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(TENANT_USER_MEMBER_URL); + + verify(identityServiceMock).deleteTenantUserMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_USER_ID); + } + + @Test + public void deleteTenantGroupMembership() { + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("groupId", MockProvider.EXAMPLE_GROUP_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(TENANT_GROUP_MEMBER_URL); + + verify(identityServiceMock).deleteTenantGroupMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void deleteTenantGroupMembershipThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).deleteTenantGroupMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_GROUP_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("groupId", MockProvider.EXAMPLE_GROUP_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(TENANT_GROUP_MEMBER_URL); + } + + @Test + public void tenantUserMembershipResourceOptionsUnauthenticated() { + String fullMembersUrl = getFullAuthorizationTenantUrl() + "/user-members"; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullMembersUrl)) + .body("links[0].method", equalTo(HttpMethod.DELETE)) + .body("links[0].rel", equalTo("delete")) + + .body("links[1].href", equalTo(fullMembersUrl)) + .body("links[1].method", equalTo(HttpMethod.PUT)) + .body("links[1].rel", equalTo("create")) + + .when() + .options(TENANT_USER_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + } + + @Test + public void tenantUserMembershipResourceOptionsAuthorized() { + String fullMembersUrl = getFullAuthorizationTenantUrl() + "/user-members"; + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(true); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullMembersUrl)) + .body("links[0].method", equalTo(HttpMethod.DELETE)) + .body("links[0].rel", equalTo("delete")) + + .body("links[1].href", equalTo(fullMembersUrl)) + .body("links[1].method", equalTo(HttpMethod.PUT)) + .body("links[1].rel", equalTo("create")) + + .when() + .options(TENANT_USER_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void tenantGroupMembershipResourceOptionsAuthorized() { + String fullMembersUrl = getFullAuthorizationTenantUrl() + "/group-members"; + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(true); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullMembersUrl)) + .body("links[0].method", equalTo(HttpMethod.DELETE)) + .body("links[0].rel", equalTo("delete")) + + .body("links[1].href", equalTo(fullMembersUrl)) + .body("links[1].method", equalTo(HttpMethod.PUT)) + .body("links[1].rel", equalTo("create")) + + .when() + .options(TENANT_GROUP_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void tenantUserMembershipResourceOptionsUnauthorized() { + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0]", nullValue()) + + .body("links[1]", nullValue()) + + .when() + .options(TENANT_USER_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void tenantGroupMembershipResourceOptionsUnauthorized() { + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0]", nullValue()) + + .body("links[1]", nullValue()) + + .when() + .options(TENANT_GROUP_MEMBERS_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, CREATE, TENANT_MEMBERSHIP, MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void tenantUserMembershipResourceOptionsWithAuthorizationDisabled() { + String fullMembersUrl = getFullAuthorizationTenantUrl() + "/user-members"; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullMembersUrl)) + .body("links[0].method", equalTo(HttpMethod.DELETE)) + .body("links[0].rel", equalTo("delete")) + + .body("links[1].href", equalTo(fullMembersUrl)) + .body("links[1].method", equalTo(HttpMethod.PUT)) + .body("links[1].rel", equalTo("create")) + + .when() + .options(TENANT_USER_MEMBERS_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void failToCreateTenantForReadOnlyService() { + Tenant newTenant = MockProvider.createMockTenant(); + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .body(TenantDto.fromTenant(newTenant)).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .post(TENANT_CREATE_URL); + + verify(identityServiceMock, never()).newTenant(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void failToUpdateTenantForReadOnlyService() { + Tenant updatedTenant = MockProvider.createMockTenant(); + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .body(TenantDto.fromTenant(updatedTenant)).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .put(TENANT_URL); + + verify(identityServiceMock, never()).saveTenant(mockTenant); + } + + @Test + public void failToDeleteTenantForReadOnlyService() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .delete(TENANT_URL); + + verify(identityServiceMock, never()).deleteTenant(MockProvider.EXAMPLE_TENANT_ID); + } + + @Test + public void failToCreateTenantUserMembershipForReadOnlyService() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .put(TENANT_USER_MEMBER_URL); + + verify(identityServiceMock, never()).createTenantUserMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_USER_ID); + } + + @Test + public void failToCreateTenantGroupMembershipForReadOnlyService() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("groupId", MockProvider.EXAMPLE_GROUP_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .put(TENANT_GROUP_MEMBER_URL); + + verify(identityServiceMock, never()).createTenantGroupMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + @Test + public void failToDeleteTenantUserMembershipForReadOnlyService() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("userId", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .delete(TENANT_USER_MEMBER_URL); + + verify(identityServiceMock, never()).deleteTenantUserMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_USER_ID); + } + + @Test + public void failToDeleteTenantGroupMembershipForReadOnlyService() { + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_TENANT_ID) + .pathParam("groupId", MockProvider.EXAMPLE_GROUP_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Identity service implementation is read-only.")) + .when() + .delete(TENANT_GROUP_MEMBER_URL); + + verify(identityServiceMock, never()).deleteTenantGroupMembership(MockProvider.EXAMPLE_TENANT_ID, MockProvider.EXAMPLE_GROUP_ID); + } + + protected void verifyNoAuthorizationCheckPerformed() { + verify(identityServiceMock, times(0)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(0)).isUserAuthorized(anyString(), anyList(), any(Permission.class), any(Resource.class)); + } + + protected String getFullAuthorizationUrl() { + return "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + TenantRestService.PATH; + } + + protected String getFullAuthorizationTenantUrl() { + return getFullAuthorizationUrl() + "/" + MockProvider.EXAMPLE_TENANT_ID; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TenantRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TenantRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1597941fac0cc565887b61b7fe1db20c3ca84a49 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/TenantRestServiceQueryTest.java @@ -0,0 +1,244 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.identity.TenantQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +public class TenantRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/tenant"; + protected static final String COUNT_QUERY_URL = QUERY_URL + "/count"; + + private TenantQuery mockQuery; + + @Before + public void setUpRuntimeData() { + List tenants = Collections.singletonList(MockProvider.createMockTenant()); + mockQuery = setUpMockQuery(tenants); + } + + private TenantQuery setUpMockQuery(List tenants) { + TenantQuery query = mock(TenantQuery.class); + when(query.list()).thenReturn(tenants); + when(query.count()).thenReturn((long) tenants.size()); + + when(processEngine.getIdentityService().createTenantQuery()).thenReturn(query); + + return query; + } + + @Test + public void emptyQuery() { + String queryKey = ""; + + given().queryParam("name", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(QUERY_URL); + } + + @Test + public void noParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(QUERY_URL); + + verify(mockQuery).list(); + verifyNoMoreInteractions(mockQuery); + } + + @Test + public void tenantRetrieval() { + String name = MockProvider.EXAMPLE_TENANT_NAME; + + Response response = given().queryParam("name", name) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).tenantName(name); + inOrder.verify(mockQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertThat(instances.size(), is(1)); + + String returnedId = from(content).getString("[0].id"); + String returnedName = from(content).getString("[0].name"); + + assertThat(returnedId, is(MockProvider.EXAMPLE_TENANT_ID)); + assertThat(returnedName, is(MockProvider.EXAMPLE_TENANT_NAME)); + } + + @Test + public void completeGetParameters() { + Map queryParameters = getCompleteStringQueryParameters(); + + RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE); + for (Entry paramEntry : queryParameters.entrySet()) { + requestSpecification.param(paramEntry.getKey(), paramEntry.getValue()); + } + + requestSpecification + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(QUERY_URL); + + verify(mockQuery).tenantId(MockProvider.EXAMPLE_TENANT_ID); + verify(mockQuery).tenantName(MockProvider.EXAMPLE_TENANT_NAME); + verify(mockQuery).tenantNameLike("%" + MockProvider.EXAMPLE_TENANT_NAME + "%"); + verify(mockQuery).userMember(MockProvider.EXAMPLE_USER_ID); + verify(mockQuery).groupMember(MockProvider.EXAMPLE_GROUP_ID); + + verify(mockQuery).list(); + } + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("id", MockProvider.EXAMPLE_TENANT_ID); + parameters.put("name", MockProvider.EXAMPLE_TENANT_NAME); + parameters.put("nameLike", "%" + MockProvider.EXAMPLE_TENANT_NAME + "%"); + parameters.put("userMember", MockProvider.EXAMPLE_USER_ID); + parameters.put("groupMember", MockProvider.EXAMPLE_GROUP_ID); + + return parameters; + } + + @Test + public void queryByUserIncludingGroups() { + + given() + .queryParam("userMember", MockProvider.EXAMPLE_USER_ID) + .queryParam("includingGroupsOfUser", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(QUERY_URL); + + verify(mockQuery).userMember(MockProvider.EXAMPLE_USER_ID); + verify(mockQuery).includingGroupsOfUser(true); + + verify(mockQuery).list(); + } + + @Test + public void queryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void queryPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .get(QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + @Test + public void sortByParameterOnly() { + given().queryParam("sortBy", "name") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(QUERY_URL); + } + + @Test + public void sortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(QUERY_URL); + } + + @Test + public void sortById() { + given() + .queryParam("sortBy", "id") + .queryParam("sortOrder", "asc") + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .get(QUERY_URL); + + InOrder inOrder = Mockito.inOrder(mockQuery); + inOrder.verify(mockQuery).orderByTenantId(); + inOrder.verify(mockQuery).asc(); + } + + @Test + public void sortByName() { + given() + .queryParam("sortBy", "name") + .queryParam("sortOrder", "desc") + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .get(QUERY_URL); + + InOrder inOrder = Mockito.inOrder(mockQuery); + inOrder.verify(mockQuery).orderByTenantName(); + inOrder.verify(mockQuery).desc(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/UserRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/UserRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..db61c009dcc96b60c9fcb619c9676f892bb5bfe5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/UserRestServiceInteractionTest.java @@ -0,0 +1,854 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.authorization.Permissions.DELETE; +import static org.camunda.bpm.engine.authorization.Permissions.UPDATE; +import static org.camunda.bpm.engine.authorization.Resources.USER; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.assertj.core.api.Assertions.assertThat; + +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.Response.Status; + +import java.util.List; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.AuthorizationService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineConfiguration; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Resource; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.dto.identity.UserCredentialsDto; +import org.camunda.bpm.engine.rest.dto.identity.UserDto; +import org.camunda.bpm.engine.rest.dto.identity.UserProfileDto; +import org.camunda.bpm.engine.rest.exception.ExceptionLogger; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.commons.testing.ProcessEngineLoggingRule; +import org.camunda.commons.testing.WatchLogger; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; + +import io.restassured.http.ContentType; + +/** + * @author Daniel Meyer + * + */ +public class UserRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + @Rule + public ProcessEngineLoggingRule loggingRule = new ProcessEngineLoggingRule() + .watch(ExceptionLogger.REST_API); + + protected static final String SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/user"; + protected static final String USER_URL = SERVICE_URL + "/{id}"; + protected static final String USER_CREATE_URL = SERVICE_URL + "/create"; + protected static final String USER_PROFILE_URL = USER_URL + "/profile"; + protected static final String USER_CREDENTIALS_URL = USER_URL + "/credentials"; + protected static final String USER_UNLOCK = USER_URL + "/unlock"; + + protected IdentityService identityServiceMock; + protected AuthorizationService authorizationServiceMock; + protected ProcessEngineConfiguration processEngineConfigurationMock; + + @Before + public void setupUserData() { + + identityServiceMock = mock(IdentityService.class); + authorizationServiceMock = mock(AuthorizationService.class); + processEngineConfigurationMock = mock(ProcessEngineConfiguration.class); + + // mock identity service + when(processEngine.getIdentityService()).thenReturn(identityServiceMock); + // authorization service + when(processEngine.getAuthorizationService()).thenReturn(authorizationServiceMock); + // process engine configuration + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationMock); + + } + + @Test + public void testGetSingleUserProfile() { + User sampleUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(sampleUser); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_USER_ID)) + .body("firstName", equalTo(MockProvider.EXAMPLE_USER_FIRST_NAME)) + .body("lastName", equalTo(MockProvider.EXAMPLE_USER_LAST_NAME)) + .body("email", equalTo(MockProvider.EXAMPLE_USER_EMAIL)) + .when() + .get(USER_PROFILE_URL); + } + + @Test + public void testUserRestServiceOptions() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + UserRestService.PATH; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl+"/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl+"/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_URL); + + verify(identityServiceMock, times(1)).getCurrentAuthentication(); + + } + + @Test + public void testUserRestServiceOptionsWithAuthorizationDisabled() { + String fullAuthorizationUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + UserRestService.PATH; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullAuthorizationUrl)) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("list")) + + .body("links[1].href", equalTo(fullAuthorizationUrl + "/count")) + .body("links[1].method", equalTo(HttpMethod.GET)) + .body("links[1].rel", equalTo("count")) + + .body("links[2].href", equalTo(fullAuthorizationUrl + "/create")) + .body("links[2].method", equalTo(HttpMethod.POST)) + .body("links[2].rel", equalTo("create")) + + .when() + .options(SERVICE_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testUserResourceOptionsUnauthenticated() { + String fullUserUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/user/" + MockProvider.EXAMPLE_USER_ID; + + User sampleUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(sampleUser); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(null); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullUserUrl+"/profile")) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullUserUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullUserUrl+"/profile")) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when() + .options(USER_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + + } + + @Test + public void testUserResourceOptionsUnauthorized() { + String fullUserUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/user/" + MockProvider.EXAMPLE_USER_ID; + + User sampleUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(sampleUser); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(false); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullUserUrl+"/profile")) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1]", nullValue()) + .body("links[2]", nullValue()) + + .when() + .options(USER_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID); + } + + @Test + public void testUserResourceOptionsDeleteAuthorized() { + String fullUserUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/user/" + MockProvider.EXAMPLE_USER_ID; + + User sampleUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(sampleUser); + + Authentication authentication = new Authentication(MockProvider.EXAMPLE_USER_ID, null); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(true); + when(authorizationServiceMock.isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID)).thenReturn(false); + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullUserUrl+"/profile")) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullUserUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2]", nullValue()) + + .when() + .options(USER_URL); + + verify(identityServiceMock, times(2)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, DELETE, USER, MockProvider.EXAMPLE_USER_ID); + verify(authorizationServiceMock, times(1)).isUserAuthorized(MockProvider.EXAMPLE_USER_ID, null, UPDATE, USER, MockProvider.EXAMPLE_USER_ID); + } + + @Test + public void testUserResourceOptionsWithAuthorizationDisabled() { + String fullUserUrl = "http://localhost:" + PORT + TEST_RESOURCE_ROOT_PATH + "/user/" + MockProvider.EXAMPLE_USER_ID; + + when(processEngineConfigurationMock.isAuthorizationEnabled()).thenReturn(false); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.OK.getStatusCode()) + + .body("links[0].href", equalTo(fullUserUrl + "/profile")) + .body("links[0].method", equalTo(HttpMethod.GET)) + .body("links[0].rel", equalTo("self")) + + .body("links[1].href", equalTo(fullUserUrl)) + .body("links[1].method", equalTo(HttpMethod.DELETE)) + .body("links[1].rel", equalTo("delete")) + + .body("links[2].href", equalTo(fullUserUrl + "/profile")) + .body("links[2].method", equalTo(HttpMethod.PUT)) + .body("links[2].rel", equalTo("update")) + + .when() + .options(USER_URL); + + verifyNoAuthorizationCheckPerformed(); + } + + @Test + public void testGetNonExistingUserProfile() { + String exceptionMessage = "User with id aNonExistingUser does not exist"; + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(anyString())).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(null); + + given() + .pathParam("id", "aNonExistingUser") + .then() + .statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when() + .get(USER_PROFILE_URL); + + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testDeleteUser() { + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(USER_URL); + } + + @Test + public void testDeleteNonExistingUser() { + given() + .pathParam("id", "non-existing") + .then() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(USER_URL); + } + + @Test + public void testDeleteUserThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).deleteUser(MockProvider.EXAMPLE_USER_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(USER_URL); + + verifyLogs(Level.DEBUG, message); + } + + @Test + public void testCreateNewUserWithCredentials() { + User newUser = MockProvider.createMockUser(); + when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser); + + UserDto userDto = UserDto.fromUser(newUser, true); + + given() + .body(userDto).contentType(ContentType.JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(USER_CREATE_URL); + + verify(identityServiceMock).newUser(MockProvider.EXAMPLE_USER_ID); + verify(newUser).setFirstName(MockProvider.EXAMPLE_USER_FIRST_NAME); + verify(newUser).setLastName(MockProvider.EXAMPLE_USER_LAST_NAME); + verify(newUser).setEmail(MockProvider.EXAMPLE_USER_EMAIL); + verify(newUser).setPassword(MockProvider.EXAMPLE_USER_PASSWORD); + verify(identityServiceMock).saveUser(newUser); + } + + @Test + public void testCreateNewUserWithoutCredentials() { + User newUser = MockProvider.createMockUser(); + when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser); + + UserDto userDto = UserDto.fromUser(newUser, false); + + given() + .body(userDto).contentType(ContentType.JSON) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(USER_CREATE_URL); + + verify(identityServiceMock).newUser(MockProvider.EXAMPLE_USER_ID); + verify(newUser).setFirstName(MockProvider.EXAMPLE_USER_FIRST_NAME); + verify(newUser).setLastName(MockProvider.EXAMPLE_USER_LAST_NAME); + verify(newUser).setEmail(MockProvider.EXAMPLE_USER_EMAIL); + // no password was set + verify(newUser, never()).setPassword(any(String.class)); + + verify(identityServiceMock).saveUser(newUser); + } + + @Test + public void testUserCreateExistingFails() { + User newUser = MockProvider.createMockUser(); + when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser); + doThrow(new ProcessEngineException("")).when(identityServiceMock).saveUser(newUser); + + UserDto userDto = UserDto.fromUser(newUser, true); + + given() + .body(userDto).contentType(ContentType.JSON) + .then() + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .when() + .post(USER_CREATE_URL); + + verify(identityServiceMock).newUser(MockProvider.EXAMPLE_USER_ID); + verify(identityServiceMock).saveUser(newUser); + + verifyLogs(Level.WARN, "org.camunda.bpm.engine.ProcessEngineException"); + } + + @Test + public void testUserCreateThrowsAuthorizationException() { + User newUser = MockProvider.createMockUser(); + String message = "exception expected"; + when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenThrow(new AuthorizationException(message)); + + UserDto userDto = UserDto.fromUser(newUser, true); + + given() + .body(userDto) + .contentType(ContentType.JSON) + .then() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(USER_CREATE_URL); + + verifyLogs(Level.DEBUG, message); + } + + @Test + public void testSaveNewUserThrowsAuthorizationException() { + User newUser = MockProvider.createMockUser(); + when(identityServiceMock.newUser(MockProvider.EXAMPLE_USER_ID)).thenReturn(newUser); + String message = "exception expected"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).saveUser(newUser); + + UserDto userDto = UserDto.fromUser(newUser, true); + + given() + .body(userDto) + .contentType(ContentType.JSON) + .then() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(USER_CREATE_URL); + + verifyLogs(Level.DEBUG, message); + } + + @Test + public void testPutCredentials() { + User initialUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(initialUser); + + UserCredentialsDto dto = new UserCredentialsDto(); + dto.setPassword("new-password"); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .body(dto).contentType(ContentType.JSON) + .then() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(USER_CREDENTIALS_URL); + + // password was updated + verify(initialUser).setPassword(dto.getPassword()); + + // and then saved + verify(identityServiceMock).saveUser(initialUser); + } + + @Test + public void testPutCredentialsThrowsAuthorizationException() { + User initialUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(initialUser); + + String message = "exception expected"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).saveUser(any(User.class)); + + UserCredentialsDto dto = new UserCredentialsDto(); + dto.setPassword("new-password"); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .body(dto).contentType(ContentType.JSON) + .then() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(USER_CREDENTIALS_URL); + + verifyLogs(Level.DEBUG, message); + } + + @Test + public void testChangeCredentials() { + User initialUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(initialUser); + + Authentication authentication = MockProvider.createMockAuthentication(); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + + when(identityServiceMock.checkPassword(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD)).thenReturn(true); + + UserCredentialsDto dto = new UserCredentialsDto(); + dto.setPassword("new-password"); + dto.setAuthenticatedUserPassword(MockProvider.EXAMPLE_USER_PASSWORD); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(USER_CREDENTIALS_URL); + + verify(identityServiceMock).getCurrentAuthentication(); + verify(identityServiceMock).checkPassword(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD); + + // password was updated + verify(initialUser).setPassword(dto.getPassword()); + + // and then saved + verify(identityServiceMock).saveUser(initialUser); + } + + @Test + public void testChangeCredentialsWithWrongAuthenticatedUserPassword() { + String exceptionMessage = "The given authenticated user password is not valid."; + User initialUser = MockProvider.createMockUser(); + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(initialUser); + + Authentication authentication = MockProvider.createMockAuthentication(); + when(identityServiceMock.getCurrentAuthentication()).thenReturn(authentication); + + when(identityServiceMock.checkPassword(MockProvider.EXAMPLE_USER_ID, MockProvider.EXAMPLE_USER_PASSWORD)).thenReturn(false); + + UserCredentialsDto dto = new UserCredentialsDto(); + dto.setPassword("new-password"); + dto.setAuthenticatedUserPassword(MockProvider.EXAMPLE_USER_PASSWORD); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .contentType(ContentType.JSON) + .body(dto) + .then() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo("InvalidRequestException")) + .body("message", equalTo(exceptionMessage)) + .when() + .put(USER_CREDENTIALS_URL); + + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testPutCredentialsNonExistingUserFails() { + String exceptionMessage = "User with id aNonExistingUser does not exist"; + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId("aNonExistingUser")).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(null); + + UserCredentialsDto dto = new UserCredentialsDto(); + dto.setPassword("new-password"); + + given() + .pathParam("id", "aNonExistingUser") + .body(dto).contentType(ContentType.JSON) + .then() + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when() + .put(USER_CREDENTIALS_URL); + + // user was not updated + verify(identityServiceMock, never()).saveUser(any(User.class)); + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testPutProfile() { + User initialUser = MockProvider.createMockUser(); + User userUpdate = MockProvider.createMockUserUpdate(); + + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(initialUser); + + UserProfileDto updateDto = UserProfileDto.fromUser(userUpdate); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .body(updateDto).contentType(ContentType.JSON) + .then() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(USER_PROFILE_URL); + + // password was updated + verify(initialUser).setEmail(updateDto.getEmail()); + verify(initialUser).setFirstName(updateDto.getFirstName()); + verify(initialUser).setLastName(updateDto.getLastName()); + + // and then saved + verify(identityServiceMock).saveUser(initialUser); + } + + @Test + public void testPutProfileNonexistingFails() { + String exceptionMessage = "User with id aNonExistingUser does not exist"; + User userUpdate = MockProvider.createMockUserUpdate(); + + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId("aNonExistingUser")).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(null); + + UserProfileDto updateDto = UserProfileDto.fromUser(userUpdate); + + given() + .pathParam("id", "aNonExistingUser") + .body(updateDto).contentType(ContentType.JSON) + .then() + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when() + .put(USER_PROFILE_URL); + + // nothing was saved + verify(identityServiceMock, never()).saveUser(any(User.class)); + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testPutProfileThrowsAuthorizationException() { + User initialUser = MockProvider.createMockUser(); + User userUpdate = MockProvider.createMockUserUpdate(); + + UserQuery sampleUserQuery = mock(UserQuery.class); + when(identityServiceMock.createUserQuery()).thenReturn(sampleUserQuery); + when(sampleUserQuery.userId(MockProvider.EXAMPLE_USER_ID)).thenReturn(sampleUserQuery); + when(sampleUserQuery.singleResult()).thenReturn(initialUser); + + String message = "exception expected"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).saveUser(any(User.class)); + + UserProfileDto updateDto = UserProfileDto.fromUser(userUpdate); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .body(updateDto).contentType(ContentType.JSON) + .then() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .put(USER_PROFILE_URL); + + verifyLogs(Level.DEBUG, message); + } + + @Test + public void testReadOnlyUserCreateFails() { + String exceptionMessage = "Identity service implementation is read-only."; + User newUser = MockProvider.createMockUser(); + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given().body(UserDto.fromUser(newUser, true)).contentType(ContentType.JSON) + .then().expect().statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when().post(USER_CREATE_URL); + + verify(identityServiceMock, never()).newUser(MockProvider.EXAMPLE_USER_ID); + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testReadOnlyPutUserProfileFails() { + String exceptionMessage = "Identity service implementation is read-only."; + User userUdpdate = MockProvider.createMockUser(); + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .body(UserProfileDto.fromUser(userUdpdate)).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when().put(USER_PROFILE_URL); + + verify(identityServiceMock, never()).saveUser(userUdpdate); + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testReadOnlyPutUserCredentialsFails() { + String exceptionMessage = "Identity service implementation is read-only."; + User userUdpdate = MockProvider.createMockUser(); + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .body(UserCredentialsDto.fromUser(userUdpdate)).contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when().put(USER_CREDENTIALS_URL); + + verify(identityServiceMock, never()).saveUser(userUdpdate); + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testReadOnlyUserDeleteFails() { + String exceptionMessage = "Identity service implementation is read-only."; + when(identityServiceMock.isReadOnly()).thenReturn(true); + + given().pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then().expect().statusCode(Status.FORBIDDEN.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when().delete(USER_URL); + + verify(identityServiceMock, never()).deleteUser(MockProvider.EXAMPLE_USER_ID); + verifyLogs(Level.DEBUG, exceptionMessage); + } + + @Test + public void testUnlockUser() { + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(USER_UNLOCK); + + verify(identityServiceMock).unlockUser(MockProvider.EXAMPLE_USER_ID); + } + + @Test + public void testUnlockUserNonExistingUser() { + given() + .pathParam("id", "non-existing") + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .post(USER_UNLOCK); + } + + @Test + public void testUnlockUserThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(identityServiceMock).unlockUser(MockProvider.EXAMPLE_USER_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_USER_ID) + .then() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(USER_UNLOCK); + + verifyLogs(Level.DEBUG, message); + } + + protected void verifyNoAuthorizationCheckPerformed() { + verify(identityServiceMock, times(0)).getCurrentAuthentication(); + verify(authorizationServiceMock, times(0)).isUserAuthorized(anyString(), anyList(), any(Permission.class), any(Resource.class)); + } + + protected void verifyLogs(Level logLevel, String message) { + List logs = loggingRule.getLog(); + assertThat(logs).hasSize(1); + assertThat(logs.get(0).getLevel()).isEqualTo(logLevel); + assertThat(logs.get(0).getMessage()).containsIgnoringCase(message); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/UserRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/UserRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8d41a1f345f38b832b336438daaae02c29d9f33e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/UserRestServiceQueryTest.java @@ -0,0 +1,258 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.identity.UserQuery; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import io.restassured.specification.RequestSpecification; + +public class UserRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String USER_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/user"; + protected static final String USER_COUNT_QUERY_URL = USER_QUERY_URL + "/count"; + + private UserQuery mockQuery; + + @Before + public void setUpRuntimeData() { + mockQuery = setUpMockUserQuery(MockProvider.createMockUsers()); + } + + private UserQuery setUpMockUserQuery(List list) { + UserQuery sampleUserQuery = mock(UserQuery.class); + when(sampleUserQuery.list()).thenReturn(list); + when(sampleUserQuery.count()).thenReturn((long) list.size()); + + when(processEngine.getIdentityService().createUserQuery()).thenReturn(sampleUserQuery); + + return sampleUserQuery; + } + + @Test + public void testEmptyQuery() { + + String queryKey = ""; + given().queryParam("name", queryKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_QUERY_URL); + + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "firstName") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(USER_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(USER_QUERY_URL); + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(USER_QUERY_URL); + + verify(mockQuery).list(); + verifyNoMoreInteractions(mockQuery); + } + + @Test + public void testSimpleUserQuery() { + String queryFirstName = MockProvider.EXAMPLE_USER_FIRST_NAME; + + Response response = given().queryParam("firstName", queryFirstName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).userFirstName(queryFirstName); + inOrder.verify(mockQuery).list(); + + verifyExampleUserResponse(response); + } + + @Test + public void testCompleteGetParameters() { + + Map queryParameters = getCompleteStringQueryParameters(); + + RequestSpecification requestSpecification = given().contentType(POST_JSON_CONTENT_TYPE); + for (Entry paramEntry : queryParameters.entrySet()) { + requestSpecification.param(paramEntry.getKey(), paramEntry.getValue()); + } + + requestSpecification.expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_QUERY_URL); + + verify(mockQuery).userEmail(MockProvider.EXAMPLE_USER_EMAIL); + verify(mockQuery).userFirstName(MockProvider.EXAMPLE_USER_FIRST_NAME); + verify(mockQuery).userLastName(MockProvider.EXAMPLE_USER_LAST_NAME); + verify(mockQuery).memberOfGroup(MockProvider.EXAMPLE_GROUP_ID); + verify(mockQuery).memberOfTenant(MockProvider.EXAMPLE_TENANT_ID); + + verify(mockQuery).list(); + + } + + @Test + public void testFirstNameLikeQuery() { + String[] testQueries = new String[] {"first%", "%Name", "%stNa%"}; + + for (String testQuery : testQueries) { + Response response = given() + .queryParam("firstNameLike", testQuery) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(USER_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).userFirstNameLike(testQuery); + inOrder.verify(mockQuery).list(); + + verifyExampleUserResponse(response); + } + } + + @Test + public void testLastNameLikeQuery() { + String[] testQueries = new String[] {"last%", "%Name", "%stNa%"}; + + for (String testQuery : testQueries) { + Response response = given() + .queryParam("lastNameLike", testQuery) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(USER_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).userLastNameLike(testQuery); + inOrder.verify(mockQuery).list(); + + verifyExampleUserResponse(response); + } + } + + @Test + public void testEmailLikeQuery() { + String[] testQueries = new String[] {"test@%", "%example.org", "%@%"}; + + for (String testQuery : testQueries) { + Response response = given() + .queryParam("emailLike", testQuery) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(USER_QUERY_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).userEmailLike(testQuery); + inOrder.verify(mockQuery).list(); + + verifyExampleUserResponse(response); + } + } + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("firstName", MockProvider.EXAMPLE_USER_FIRST_NAME); + parameters.put("lastName", MockProvider.EXAMPLE_USER_LAST_NAME); + parameters.put("email", MockProvider.EXAMPLE_USER_EMAIL); + parameters.put("memberOfGroup", MockProvider.EXAMPLE_GROUP_ID); + parameters.put("memberOfTenant", MockProvider.EXAMPLE_TENANT_ID); + + return parameters; + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(USER_COUNT_QUERY_URL); + + verify(mockQuery).count(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_QUERY_URL); + + verify(mockQuery).listPage(firstResult, maxResults); + } + + protected void verifyExampleUserResponse(Response response) { + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one user returned.", 1, instances.size()); + Assert.assertNotNull("The returned user should not be null.", instances.get(0)); + + String returendLastName = from(content).getString("[0].lastName"); + String returnedFirstName = from(content).getString("[0].firstName"); + String returnedEmail = from(content).getString("[0].email"); + + Assert.assertEquals(MockProvider.EXAMPLE_USER_FIRST_NAME, returnedFirstName); + Assert.assertEquals(MockProvider.EXAMPLE_USER_LAST_NAME, returendLastName); + Assert.assertEquals(MockProvider.EXAMPLE_USER_EMAIL, returnedEmail); + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/VariableInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/VariableInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8fdedd534b21f86d9c17ed849d9d1e32ce9766a2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/VariableInstanceRestServiceInteractionTest.java @@ -0,0 +1,357 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.either; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.MockVariableInstanceBuilder; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.runtime.VariableInstanceQuery; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Daniel Meyer + * + */ +public class VariableInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String SERVICE_URL = TEST_RESOURCE_ROOT_PATH + "/variable-instance"; + protected static final String VARIABLE_INSTANCE_URL = SERVICE_URL + "/{id}"; + protected static final String VARIABLE_INSTANCE_BINARY_DATA_URL = VARIABLE_INSTANCE_URL + "/data"; + + protected RuntimeService runtimeServiceMock; + + protected VariableInstanceQuery variableInstanceQueryMock; + + @Before + public void setupTestData() { + runtimeServiceMock = mock(RuntimeService.class); + variableInstanceQueryMock = mock(VariableInstanceQuery.class); + + // mock runtime service. + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + when(runtimeServiceMock.createVariableInstanceQuery()).thenReturn(variableInstanceQueryMock); + } + + @Test + public void testGetSingleVariableInstance() { + + MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); + VariableInstance variableInstanceMock = builder.build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("name", equalTo(builder.getName())) + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo(builder.getTypedValue().getValue())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("taskId", equalTo(builder.getTaskId())) + .body("batchId", equalTo(builder.getBatchId())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("tenantId", equalTo(builder.getTenantId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + } + + @Test + public void testGetSingleVariableInstanceDeserialized() { + ObjectValue serializedValue = MockObjectValue.fromObjectValue( + Variables.objectValue("a value").serializationDataFormat("aDataFormat").create()) + .objectTypeName("aTypeName"); + + MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance().typedValue(serializedValue); + VariableInstance variableInstanceMock = builder.build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("name", equalTo(builder.getName())) + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo("a value")) + .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) + .body("valueInfo.objectTypeName", equalTo("aTypeName")) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("taskId", equalTo(builder.getTaskId())) + .body("batchId", equalTo(builder.getBatchId())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("tenantId", equalTo(builder.getTenantId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + verify(variableInstanceQueryMock, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testGetSingleVariableInstanceSerialized() { + ObjectValue serializedValue = Variables.serializedObjectValue("a serialized value") + .serializationDataFormat("aDataFormat").objectTypeName("aTypeName").create(); + + MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance().typedValue(serializedValue); + VariableInstance variableInstanceMock = builder.build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("name", equalTo(builder.getName())) + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo("a serialized value")) + .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) + .body("valueInfo.objectTypeName", equalTo("aTypeName")) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("taskId", equalTo(builder.getTaskId())) + .body("batchId", equalTo(builder.getBatchId())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("tenantId", equalTo(builder.getTenantId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + verify(variableInstanceQueryMock, times(1)).disableCustomObjectDeserialization(); + } + + @Test + public void testGetSingleVariableInstanceForBinaryVariable() { + MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); + VariableInstance variableInstanceMock = + builder + .typedValue(Variables.byteArrayValue(null)) + .build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.BYTES))) + .body("value", nullValue()) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + + } + + @Test + public void testGetNonExistingVariableInstance() { + + String nonExistingId = "nonExistingId"; + + when(variableInstanceQueryMock.variableId(nonExistingId)).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", nonExistingId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Variable instance with Id 'nonExistingId' does not exist.")) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + } + + @Test + public void testBinaryDataForBinaryVariable() { + final byte[] byteContent = "some bytes".getBytes(); + + VariableInstance variableInstanceMock = + MockProvider.mockVariableInstance() + .typedValue(Variables.byteArrayValue(byteContent)) + .build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.BINARY.toString()) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + byte[] responseBytes = response.getBody().asByteArray(); + Assert.assertEquals(new String(byteContent), new String(responseBytes)); + verify(variableInstanceQueryMock, never()).disableBinaryFetching(); + verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + + } + + @Test + public void testBinaryDataForNonBinaryVariable() { + VariableInstance variableInstanceMock = MockProvider.createMockVariableInstance(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Value of variable with id aVariableInstanceId is not a binary value")) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + verify(variableInstanceQueryMock, never()).disableBinaryFetching(); + verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + + } + + @Test + public void testGetBinaryDataForNonExistingVariableInstance() { + + String nonExistingId = "nonExistingId"; + + when(variableInstanceQueryMock.variableId(nonExistingId)).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", nonExistingId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Variable instance with Id 'nonExistingId' does not exist.")) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + verify(variableInstanceQueryMock, never()).disableBinaryFetching(); + verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + } + + @Test + public void testGetBinaryDataForFileVariable() { + String filename = "test.txt"; + byte[] byteContent = "test".getBytes(); + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); + VariableInstance variableInstanceMock = + builder + .typedValue(variableValue) + .build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .header("Content-Disposition", "attachment; " + + "filename=\"" + filename + "\"; " + + "filename*=UTF-8''" + filename) + .and() + .body(is(equalTo(new String(byteContent)))) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + //due to some problems with wildfly we gotta check this separately + String contentType = response.getContentType(); + assertThat(contentType, is(either(CoreMatchers.equalTo(ContentType.TEXT.toString() + "; charset=UTF-8")).or(CoreMatchers.equalTo(ContentType.TEXT.toString() + ";charset=UTF-8")))); + } + + @Test + public void testGetBinaryDataForNullFileVariable() { + String filename = "test.txt"; + byte[] byteContent = null; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + MockVariableInstanceBuilder builder = MockProvider.mockVariableInstance(); + VariableInstance variableInstanceMock = + builder + .typedValue(variableValue) + .build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .contentType(ContentType.TEXT) + .and() + .body(is(equalTo(new String()))) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/VariableInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/VariableInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..53f2bf3f6a4aa83d987d646c0b2b87b73bbbb095 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/VariableInstanceRestServiceQueryTest.java @@ -0,0 +1,1253 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.MockVariableInstanceBuilder; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.runtime.VariableInstanceQuery; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class VariableInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String VARIABLE_INSTANCE_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/variable-instance"; + protected static final String VARIABLE_INSTANCE_COUNT_QUERY_URL = VARIABLE_INSTANCE_QUERY_URL + "/count"; + + protected VariableInstanceQuery mockedQuery; + protected VariableInstance mockInstance; + protected MockVariableInstanceBuilder mockInstanceBuilder; + + @Before + public void setUpRuntimeData() { + mockInstanceBuilder = MockProvider.mockVariableInstance(); + mockInstance = mockInstanceBuilder.build(); + + mockedQuery = setUpMockVariableInstanceQuery(createMockVariableInstanceList(mockInstance)); + } + + private VariableInstanceQuery setUpMockVariableInstanceQuery(List mockedInstances) { + VariableInstanceQuery sampleInstanceQuery = mock(VariableInstanceQuery.class); + + when(sampleInstanceQuery.list()).thenReturn(mockedInstances); + when(sampleInstanceQuery.count()).thenReturn((long) mockedInstances.size()); + when(processEngine.getRuntimeService().createVariableInstanceQuery()).thenReturn(sampleInstanceQuery); + + return sampleInstanceQuery; + } + + protected List createMockVariableInstanceList(VariableInstance mockInstance) { + List mocks = new ArrayList(); + + mocks.add(mockInstance); + return mocks; + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryDisableObjectDeserialization() { + given() + .queryParam("deserializeValues", false) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPostDisableObjectDeserialization() { + given() + .queryParam("deserializeValues", false) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidVariableRequests() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_" + invalidComparator + "_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid variable comparator specified: " + invalidComparator)) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + // invalid format + queryValue = "invalidFormattedVariableQuery"; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("variable query parameter has to have format KEY_OPERATOR_VALUE")) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("variableName", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then().expect().statusCode(expectedStatus.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + } + + @Test + public void testSortByParameterOnly() { + given().queryParam("sortBy", "variableName") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableName", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableType(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("variableName").desc() + .orderBy("activityInstanceId").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(VARIABLE_INSTANCE_QUERY_URL); + + inOrder.verify(mockedQuery).orderByVariableName(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByActivityInstanceId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = 0; + int maxResults = 10; + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + /** + * If parameter "firstResult" is missing, we expect 0 as default. + */ + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given().queryParam("maxResults", maxResults) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + /** + * If parameter "maxResults" is missing, we expect Integer.MAX_VALUE as default. + */ + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given().queryParam("firstResult", firstResult) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableInstanceRetrieval() { + String queryVariableName = "aVariableInstanceName"; + Response response = given().queryParam("variableName", queryVariableName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("size()", is(1)) + .body("[0].id", equalTo(mockInstanceBuilder.getId())) + .body("[0].name", equalTo(mockInstanceBuilder.getName())) + .body("[0].type", equalTo(VariableTypeHelper.toExpectedValueTypeName(mockInstanceBuilder.getTypedValue().getType()))) + .body("[0].value", equalTo(mockInstanceBuilder.getValue())) + .body("[0].processDefinitionId", equalTo(mockInstanceBuilder.getProcessDefinitionId())) + .body("[0].processInstanceId", equalTo(mockInstanceBuilder.getProcessInstanceId())) + .body("[0].executionId", equalTo(mockInstanceBuilder.getExecutionId())) + .body("[0].caseInstanceId", equalTo(mockInstanceBuilder.getCaseInstanceId())) + .body("[0].caseExecutionId", equalTo(mockInstanceBuilder.getCaseExecutionId())) + .body("[0].taskId", equalTo(mockInstanceBuilder.getTaskId())) + .body("[0].batchId", equalTo(mockInstanceBuilder.getBatchId())) + .body("[0].activityInstanceId", equalTo(mockInstanceBuilder.getActivityInstanceId())) + .body("[0].tenantId", equalTo(mockInstanceBuilder.getTenantId())) + .body("[0].errorMessage", equalTo(mockInstanceBuilder.getErrorMessage())) + .body("[0].serializedValue", nullValue()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).variableName(queryVariableName); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List variables = from(content).getList(""); + Assert.assertEquals("There should be one variable instance returned.", 1, variables.size()); + Assert.assertNotNull("There should be one variable instance returned", variables.get(0)); + + verify(mockedQuery).disableBinaryFetching(); + // requirement to not break existing API; should be: + // verify(mockedQuery).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + + @Test + public void testVariableInstanceRetrievalAsPost() { + String queryVariableName = "aVariableInstanceName"; + Map queryParameter = new HashMap(); + queryParameter.put("variableName", queryVariableName); + + Response response = given().contentType(POST_JSON_CONTENT_TYPE).body(queryParameter) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("size()", is(1)) + .body("[0].id", equalTo(mockInstanceBuilder.getId())) + .body("[0].name", equalTo(mockInstanceBuilder.getName())) + .body("[0].type", equalTo(VariableTypeHelper.toExpectedValueTypeName(mockInstanceBuilder.getTypedValue().getType()))) + .body("[0].value", equalTo(mockInstanceBuilder.getTypedValue().getValue())) + .body("[0].processInstanceId", equalTo(mockInstanceBuilder.getProcessInstanceId())) + .body("[0].executionId", equalTo(mockInstanceBuilder.getExecutionId())) + .body("[0].caseInstanceId", equalTo(mockInstanceBuilder.getCaseInstanceId())) + .body("[0].caseExecutionId", equalTo(mockInstanceBuilder.getCaseExecutionId())) + .body("[0].taskId", equalTo(mockInstanceBuilder.getTaskId())) + .body("[0].batchId", equalTo(mockInstanceBuilder.getBatchId())) + .body("[0].activityInstanceId", equalTo(mockInstanceBuilder.getActivityInstanceId())) + .body("[0].tenantId", equalTo(mockInstanceBuilder.getTenantId())) + .body("[0].errorMessage", equalTo(mockInstanceBuilder.getErrorMessage())) + .body("[0].serializedValue", nullValue()) + .when().post(VARIABLE_INSTANCE_QUERY_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(mockedQuery); + inOrder.verify(mockedQuery).variableName(queryVariableName); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List variables = from(content).getList(""); + Assert.assertEquals("There should be one process definition returned.", 1, variables.size()); + Assert.assertNotNull("There should be one process definition returned", variables.get(0)); + + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(mockedQuery).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testAdditionalParametersExcludingVariableValues() { + Map queryParameters = new HashMap(); + + queryParameters.put("variableName", "aVariableName"); + queryParameters.put("variableNameLike", "aVariableNameLike"); + queryParameters.put("executionIdIn", "anExecutionId"); + queryParameters.put("processInstanceIdIn", "aProcessInstanceId"); + queryParameters.put("caseExecutionIdIn", "aCaseExecutionId"); + queryParameters.put("caseInstanceIdIn", "aCaseInstanceId"); + queryParameters.put("taskIdIn", "aTaskId"); + queryParameters.put("batchIdIn", "aBatchId"); + queryParameters.put("variableScopeIdIn", "aVariableScopeId"); + queryParameters.put("activityInstanceIdIn", "anActivityInstanceId"); + queryParameters.put("tenantIdIn", "anTenantId"); + + given().queryParams(queryParameters) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableName(queryParameters.get("variableName")); + verify(mockedQuery).variableNameLike(queryParameters.get("variableNameLike")); + verify(mockedQuery).processInstanceIdIn(queryParameters.get("processInstanceIdIn")); + verify(mockedQuery).executionIdIn(queryParameters.get("executionIdIn")); + verify(mockedQuery).caseInstanceIdIn(queryParameters.get("caseInstanceIdIn")); + verify(mockedQuery).caseExecutionIdIn(queryParameters.get("caseExecutionIdIn")); + verify(mockedQuery).taskIdIn(queryParameters.get("taskIdIn")); + verify(mockedQuery).batchIdIn(queryParameters.get("batchIdIn")); + verify(mockedQuery).variableScopeIdIn(queryParameters.get("variableScopeIdIn")); + verify(mockedQuery).activityInstanceIdIn(queryParameters.get("activityInstanceIdIn")); + verify(mockedQuery).tenantIdIn(queryParameters.get("tenantIdIn")); + verify(mockedQuery).list(); + + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(mockedQuery).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testAdditionalParametersExcludingVariableValuesAsPost() { + String aVariableName = "aVariableName"; + String aVariableNameLike = "aVariableNameLike"; + String aProcessInstanceId = "aProcessInstanceId"; + String anExecutionId = "anExecutionId"; + String aTaskId = "aTaskId"; + String aBatchId = "aBatchId"; + String aVariableScopeId = "aVariableScopeId"; + String anActivityInstanceId = "anActivityInstanceId"; + String aCaseInstanceId = "aCaseInstanceId"; + String aCaseExecutionId = "aCaseExecutionId"; + String aTenantId = "aTenantId"; + + Map queryParameters = new HashMap(); + + queryParameters.put("variableName", aVariableName); + queryParameters.put("variableNameLike", aVariableNameLike); + + List executionIdIn = new ArrayList(); + executionIdIn.add(anExecutionId); + queryParameters.put("executionIdIn", executionIdIn); + + List processInstanceIdIn = new ArrayList(); + processInstanceIdIn.add(aProcessInstanceId); + queryParameters.put("processInstanceIdIn", processInstanceIdIn); + + List caseExecutionIdIn = new ArrayList(); + caseExecutionIdIn.add(aCaseExecutionId); + queryParameters.put("caseExecutionIdIn", caseExecutionIdIn); + + List caseInstanceIdIn = new ArrayList(); + caseInstanceIdIn.add(aCaseInstanceId); + queryParameters.put("caseInstanceIdIn", caseInstanceIdIn); + + List taskIdIn = new ArrayList(); + taskIdIn.add(aTaskId); + queryParameters.put("taskIdIn", taskIdIn); + + List batchIdIn = new ArrayList<>(); + batchIdIn.add(aBatchId); + queryParameters.put("batchIdIn", batchIdIn); + + List variableScopeIdIn = new ArrayList(); + variableScopeIdIn.add(aVariableScopeId); + queryParameters.put("variableScopeIdIn", variableScopeIdIn); + + List activityInstanceIdIn = new ArrayList(); + activityInstanceIdIn.add(anActivityInstanceId); + queryParameters.put("activityInstanceIdIn", activityInstanceIdIn); + + List tenantIdIn = new ArrayList(); + tenantIdIn.add(aTenantId); + queryParameters.put("tenantIdIn", tenantIdIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(queryParameters) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableName(aVariableName); + verify(mockedQuery).variableNameLike(aVariableNameLike); + verify(mockedQuery).processInstanceIdIn(aProcessInstanceId); + verify(mockedQuery).executionIdIn(anExecutionId); + verify(mockedQuery).taskIdIn(aTaskId); + verify(mockedQuery).batchIdIn(aBatchId); + verify(mockedQuery).variableScopeIdIn(aVariableScopeId); + verify(mockedQuery).activityInstanceIdIn(anActivityInstanceId); + verify(mockedQuery).tenantIdIn(aTenantId); + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(mockedQuery).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gt_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueGreaterThan(variableName, variableValue); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gteq_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueGreaterThanOrEqual(variableName, variableValue); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lt_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueLessThan(variableName, variableValue); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lteq_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueLessThanOrEqual(variableName, variableValue); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variableValues", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variableValues", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variableValues", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + + @Test + public void testVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variableValues", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variableValues", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueGreaterThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThan("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueGreaterThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueLessThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThan("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueLessThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLessThanOrEqual("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueLikeAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValueNotEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + + @Test + public void testVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given().queryParam("variableValues", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName1, variableValue1); + verify(mockedQuery).variableValueNotEquals(variableName2, variableValue2); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("variableValues", variables); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).variableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testMultipleParameters() { + String aProcessInstanceId = "aProcessInstanceId"; + String anotherProcessInstanceId = "anotherProcessInstanceId"; + + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + String aTaskId = "aTaskId"; + String anotherTaskId = "anotherTaskId"; + + String aVariableScopeId = "aVariableScopeId"; + String anotherVariableScopeId = "anotherVariableScopeId"; + + String anActivityInstanceId = "anActivityInstanceId"; + String anotherActivityInstanceId = "anotherActivityInstanceId"; + + given() + .queryParam("processInstanceIdIn", aProcessInstanceId + "," + anotherProcessInstanceId) + .queryParam("executionIdIn", anExecutionId + "," + anotherExecutionId) + .queryParam("taskIdIn", aTaskId + "," + anotherTaskId) + .queryParam("variableScopeIdIn", aVariableScopeId + "," + anotherVariableScopeId) + .queryParam("activityInstanceIdIn", anActivityInstanceId + "," + anotherActivityInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).processInstanceIdIn(aProcessInstanceId, anotherProcessInstanceId); + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).taskIdIn(aTaskId, anotherTaskId); + verify(mockedQuery).variableScopeIdIn(aVariableScopeId, anotherVariableScopeId); + verify(mockedQuery).activityInstanceIdIn(anActivityInstanceId, anotherActivityInstanceId); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testMultipleParametersAsPost() { + String aProcessInstanceId = "aProcessInstanceId"; + String anotherProcessInstanceId = "anotherProcessInstanceId"; + + List processDefinitionIdIn= new ArrayList(); + processDefinitionIdIn.add(aProcessInstanceId); + processDefinitionIdIn.add(anotherProcessInstanceId); + + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + List executionIdIn= new ArrayList(); + executionIdIn.add(anExecutionId); + executionIdIn.add(anotherExecutionId); + + String aTaskId = "aTaskId"; + String anotherTaskId = "anotherTaskId"; + + List taskIdIn= new ArrayList(); + taskIdIn.add(aTaskId); + taskIdIn.add(anotherTaskId); + + String aVariableScopeId = "aVariableScopeId"; + String anotherVariableScopeId = "anotherVariableScopeId"; + + List variableScopeIdIn= new ArrayList(); + variableScopeIdIn.add(aVariableScopeId); + variableScopeIdIn.add(anotherVariableScopeId); + + String anActivityInstanceId = "anActivityInstanceId"; + String anotherActivityInstanceId = "anotherActivityInstanceId"; + + List activityInstanceIdIn= new ArrayList(); + activityInstanceIdIn.add(anActivityInstanceId); + activityInstanceIdIn.add(anotherActivityInstanceId); + + Map json = new HashMap(); + json.put("processInstanceIdIn", processDefinitionIdIn); + json.put("executionIdIn", executionIdIn); + json.put("taskIdIn", taskIdIn); + json.put("variableScopeIdIn", variableScopeIdIn); + json.put("activityInstanceIdIn", activityInstanceIdIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(VARIABLE_INSTANCE_QUERY_URL); + + verify(mockedQuery).processInstanceIdIn(aProcessInstanceId, anotherProcessInstanceId); + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).taskIdIn(aTaskId, anotherTaskId); + verify(mockedQuery).variableScopeIdIn(aVariableScopeId, anotherVariableScopeId); + verify(mockedQuery).activityInstanceIdIn(anActivityInstanceId, anotherActivityInstanceId); + verify(mockedQuery).disableBinaryFetching(); + + // requirement to not break existing API; should be: + // verify(variableInstanceQueryMock).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(VARIABLE_INSTANCE_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given().contentType(POST_JSON_CONTENT_TYPE).body(EMPTY_JSON_OBJECT) + .expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().post(VARIABLE_INSTANCE_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/ConflictingProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/ConflictingProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..e1adbef5614160a8587bc32f32a80c10ba8b98c1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/ConflictingProvider.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.application; + +import java.io.IOException; +import java.io.OutputStream; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; + +/** + * a provider that is in conflict with the jackson provider. + * + * The produced content type has to be lexicographically sortable before 'application/json' to ensure it is picked instead of jackson + * by the JAX-RS runtime in case there is no content type defined in the response by the resource method. + * @author Thorben Lindhauer + * + */ +@Provider +@Produces("aaa/aaa") +public class ConflictingProvider implements MessageBodyWriter { + + @Override + public boolean isWriteable(Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return true; + } + + @Override + public long getSize(Object t, Class type, Type genericType, + Annotation[] annotations, MediaType mediaType) { + return -1; + } + + @Override + public void writeTo(Object t, Class type, Type genericType, + Annotation[] annotations, MediaType mediaType, + MultivaluedMap httpHeaders, OutputStream entityStream) + throws IOException, WebApplicationException { + entityStream.write("Conflicting provider used".getBytes()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/TestCustomResourceApplication.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/TestCustomResourceApplication.java new file mode 100644 index 0000000000000000000000000000000000000000..bb04b5e38f55b3d8950cfeea2438b0e1091e01a2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/TestCustomResourceApplication.java @@ -0,0 +1,72 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.application; + +import com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper; +import com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; +import org.camunda.bpm.engine.rest.exception.ExceptionHandler; +import org.camunda.bpm.engine.rest.exception.ProcessEngineExceptionHandler; +import org.camunda.bpm.engine.rest.exception.RestExceptionHandler; +import org.camunda.bpm.engine.rest.mapper.JacksonConfigurator; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; +import java.util.HashSet; +import java.util.Set; + +@ApplicationPath("/") +public class TestCustomResourceApplication extends Application { + + private static final Set> RESOURCES = new HashSet>(); + private static final Set> PROVIDERS = new HashSet>(); + + static { + // RESOURCES + RESOURCES.add(UnannotatedResource.class); + + // PROVIDERS + PROVIDERS.add(ConflictingProvider.class); + + PROVIDERS.add(JacksonConfigurator.class); + + PROVIDERS.add(JacksonJsonProvider.class); + PROVIDERS.add(JsonMappingExceptionMapper.class); + PROVIDERS.add(JsonParseExceptionMapper.class); + + PROVIDERS.add(ProcessEngineExceptionHandler.class); + PROVIDERS.add(RestExceptionHandler.class); + PROVIDERS.add(ExceptionHandler.class); + } + + @Override + public Set> getClasses() { + Set> classes = new HashSet>(); + classes.addAll(RESOURCES); + classes.addAll(PROVIDERS); + + return classes; + } + + public static Set> getResourceClasses() { + return RESOURCES; + } + + public static Set> getProviderClasses() { + return PROVIDERS; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/UnannotatedResource.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/UnannotatedResource.java new file mode 100644 index 0000000000000000000000000000000000000000..3bf1b2cf021bf92af129537fd4ebe59a9b7a24ca --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/application/UnannotatedResource.java @@ -0,0 +1,79 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.application; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.authorization.MissingAuthorization; +import org.camunda.bpm.engine.rest.exception.RestException; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response.Status; +import java.util.ArrayList; +import java.util.List; + +/** + * Does not declare produced media types. + * @author Thorben Lindhauer + * + */ +@Path("/unannotated") +public class UnannotatedResource { + + @GET + @Path("/exception") + public String throwAnException() throws Exception { + throw new Exception("expected exception"); + } + + @GET + @Path("/processEngineException") + public String throwProcessEngineException() throws Exception { + throw new ProcessEngineException("expected exception"); + } + + @GET + @Path("/restException") + public String throwRestException() throws Exception { + throw new RestException(Status.BAD_REQUEST, "expected exception"); + } + + @GET + @Path("/authorizationException") + public String throwAuthorizationException() throws Exception { + throw new AuthorizationException("someUser", "somePermission", "someResourceName", "someResourceId"); + } + + @GET + @Path("/stackOverflowError") + public String throwStackOverflowError() throws Throwable { + throw new StackOverflowError("Stack overflow"); + } + + @GET + @Path("/authorizationExceptionMultiple") + public String throwAuthorizationExceptionMultiple() throws Exception { + List missingAuthorizations = new ArrayList<>(); + + missingAuthorizations.add( + new MissingAuthorization("somePermission1", "someResourceName1", "someResourceId1")); + missingAuthorizations.add( + new MissingAuthorization("somePermission2", "someResourceName2", "someResourceId2")); + throw new AuthorizationException("someUser", missingAuthorizations); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/converter/DateConverterTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/converter/DateConverterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0551936c82dd0cb7fc58820233ad96d7ffe8bd0f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/converter/DateConverterTest.java @@ -0,0 +1,69 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.converter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.dto.converter.DateConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.junit.Before; +import org.junit.Test; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import static org.junit.Assert.assertEquals; + +import java.util.Date; + +public class DateConverterTest { + private DateConverter converter; + + @Before + public void setUp() throws Exception { + converter = new DateConverter(); + } + + @Test(expected = InvalidRequestException.class) + public void shouldFailForDoubleQuotedValue() { + //when + converter.convertQueryParameterToType("\"pizza\""); + } + + @Test(expected = InvalidRequestException.class) + public void shouldFailForSingleDoubleQuotedValue() { + //when + converter.convertQueryParameterToType("2014-01-01T00:00:00+0200\""); + } + + @Test + public void shouldConvertDate() throws JsonProcessingException { + //given + String value = "2014-01-01T00:00:00+0200"; + ObjectMapper mock = mock(ObjectMapper.class); + converter.setObjectMapper(mock); + when(mock.readValue(anyString(), eq(Date.class))).thenReturn(DateTimeUtil.parseDate(value)); + + //when + Date date = converter.convertQueryParameterToType(value); + + //then + assertEquals(date, DateTimeUtil.parseDate(value)); + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsList.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsList.java new file mode 100644 index 0000000000000000000000000000000000000000..a67c322165b28dc31c9a5ffbaacceea20ea436c3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsList.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; + +public class EqualsList extends BaseMatcher> { + + private List listToCompare; + + public EqualsList(List listToCompare) { + this.listToCompare = listToCompare; + } + + @Override + public boolean matches(Object list) { + if ((list == null && listToCompare != null) || + (list != null && listToCompare == null)) { + return false; + } + + if (list == null && listToCompare == null) { + return true; + } + + List argumentList = (List) list; + + Set setToCompare = new HashSet(listToCompare); + Set argumentSet = new HashSet(argumentList); + + return setToCompare.equals(argumentSet); + } + + @Override + public void describeTo(final Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append(": "); + sb.append("listToCompare="); + sb.append(listToCompare); + + description.appendText(sb.toString()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsMap.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsMap.java new file mode 100644 index 0000000000000000000000000000000000000000..a56f1d8b432cb7bb80bf7393c93dfc4a0f3ddd56 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsMap.java @@ -0,0 +1,131 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import org.camunda.bpm.engine.variable.VariableMap; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; + +public class EqualsMap extends BaseMatcher> { + + protected Map mapToCompare; + protected Map> matchers; + + public EqualsMap() { + } + + public EqualsMap(Map mapToCompare) { + this.mapToCompare = mapToCompare; + } + + @Override + public boolean matches(Object argument) { + if (mapToCompare != null) { + return matchesExactly(argument); + } else if (matchers != null) { + return matchesMatchers(argument); + } else { + return argument == null; + } + } + + protected boolean matchesExactly(Object argument) { + if (argument == null) { + return false; + } + + Map argumentMap = (Map) argument; + + Set> setToCompare = mapToCompare.entrySet(); + Set> argumentSet = argumentMap.entrySet(); + + return setToCompare.equals(argumentSet); + } + + protected boolean matchesMatchers(Object argument) { + if (argument == null) { + return false; + } + + Map argumentMap = (Map) argument; + + boolean containSameKeys = matchers.keySet().containsAll(argumentMap.keySet()) && + argumentMap.keySet().containsAll(matchers.keySet()); + if (!containSameKeys) { + return false; + } + + for (String key : argumentMap.keySet()) { + Matcher matcher = matchers.get(key); + Object value = null; + if (argumentMap instanceof VariableMap) { + VariableMap varMap = (VariableMap) argumentMap; + value = varMap.getValueTyped(key); + } + else { + value = argumentMap.get(key); + } + if (!matcher.matches(value)) { + return false; + } + } + + + return true; + } + + public static EqualsMap containsExactly(Map map) { + EqualsMap matcher = new EqualsMap(); + matcher.mapToCompare = map; + return matcher; + } + + public static EqualsMap matchesExactly(Map> matchers) { + EqualsMap matcher = new EqualsMap(); + matcher.matchers = matchers; + return matcher; + } + + public EqualsMap matcher(String key, Matcher matcher) { + if (matchers == null) { + this.matchers = new HashMap>(); + } + + matchers.put(key, matcher); + return this; + } + + public void describeTo(Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append(": "); + sb.append("mapToCompare="); + sb.append(mapToCompare); + sb.append(" "); + sb.append("matchers="); + sb.append(matchers); + + description.appendText(sb.toString()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsVariableMap.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsVariableMap.java new file mode 100644 index 0000000000000000000000000000000000000000..f2b148b90df2c07439ddd6bcd642782d620cf56c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/EqualsVariableMap.java @@ -0,0 +1,91 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.engine.variable.VariableMap; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.hamcrest.Matcher; + +public class EqualsVariableMap extends BaseMatcher> { + + protected Map> matchers; + + public EqualsVariableMap() { + } + + @Override + public boolean matches(Object argument) { + return matchesMatchers(argument); + } + + protected boolean matchesMatchers(Object argument) { + if (argument == null) { + return false; + } + + VariableMap argumentMap = (VariableMap) argument; + + boolean containSameKeys = matchers.keySet().containsAll(argumentMap.keySet()) && + argumentMap.keySet().containsAll(matchers.keySet()); + if (!containSameKeys) { + return false; + } + + for (String key : argumentMap.keySet()) { + Matcher matcher = matchers.get(key); + if (!matcher.matches(argumentMap.getValueTyped(key))) { + return false; + } + } + + return true; + } + + public static EqualsVariableMap matchesExactly(Map> matchers) { + EqualsVariableMap matcher = new EqualsVariableMap(); + matcher.matchers = matchers; + return matcher; + } + + public static EqualsVariableMap matches() { + return new EqualsVariableMap(); + } + + public EqualsVariableMap matcher(String key, Matcher matcher) { + if (matchers == null) { + this.matchers = new HashMap>(); + } + + matchers.put(key, matcher); + return this; + } + + public void describeTo(Description description) { + description.appendText("EqualsVariableMap: {"); + for (Map.Entry> matcher : matchers.entrySet()) { + description.appendText(matcher.getKey() + " => "); + description.appendDescriptionOf(matcher.getValue()); + } + description.appendText("}"); + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ErrorMessageHelper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ErrorMessageHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..0fe0bd866995e9afe3b15773b25f6428b792978f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ErrorMessageHelper.java @@ -0,0 +1,30 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +/** + * @author Thorben Lindhauer + * + */ +public class ErrorMessageHelper { + + protected static final String EXPECTED_CONVERSION_FAILURE_MESSAGE = "Cannot convert value '%s' of type '%s' to java type %s"; + + public static String getExpectedFailingConversionMessage(Object value, String submittedValueType, Class conversionClass) { + return String.format(EXPECTED_CONVERSION_FAILURE_MESSAGE, value, submittedValueType, conversionClass.getName()); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ExampleVariableObject.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ExampleVariableObject.java new file mode 100644 index 0000000000000000000000000000000000000000..76f99d5db1dfde22aa224be21a08af1db7dc077a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ExampleVariableObject.java @@ -0,0 +1,36 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +public class ExampleVariableObject { + + private String property1; + private boolean property2; + + public String getProperty1() { + return property1; + } + public void setProperty1(String property1) { + this.property1 = property1; + } + public boolean isProperty2() { + return property2; + } + public void setProperty2(boolean property2) { + this.property2 = property2; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/FluentAnswer.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/FluentAnswer.java new file mode 100644 index 0000000000000000000000000000000000000000..1e3b485da71b9ea901721eef6a634296601d5da9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/FluentAnswer.java @@ -0,0 +1,42 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +/** + * Default answer for Mockito mocks to always return themselves if the method return type matches. + * Can be used to mock fluent APIs more easily. + * + * @author Thorben Lindhauer + */ +public class FluentAnswer implements Answer { + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + Class returnType = invocation.getMethod().getReturnType(); + + Object mock = invocation.getMock(); + if (returnType.isAssignableFrom(mock.getClass())) { + return mock; + } + else { + return null; + } + } +} \ No newline at end of file diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockBatchBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockBatchBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..210200b8663c52a4815fcea14f0e9091c25e6f46 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockBatchBuilder.java @@ -0,0 +1,132 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.batch.Batch; + +import java.util.Date; + +public class MockBatchBuilder { + + protected String id; + protected String type; + protected int totalJobs; + protected int jobsCreated; + protected int batchJobsPerSeed; + protected int invocationsPerBatchJob; + protected String seedJobDefinitionId; + protected String monitorJobDefinitionId; + protected String batchJobDefinitionId; + protected boolean suspended; + protected String tenantId; + protected String createUserId; + protected Date startTime; + protected Date executionStartTime; + + public MockBatchBuilder id(String id) { + this.id = id; + return this; + } + + public MockBatchBuilder type(String type) { + this.type = type; + return this; + } + + public MockBatchBuilder totalJobs(int totalJobs) { + this.totalJobs = totalJobs; + return this; + } + + public MockBatchBuilder jobsCreated(int jobsCreated) { + this.jobsCreated = jobsCreated; + return this; + } + + public MockBatchBuilder batchJobsPerSeed(int batchJobsPerSeed) { + this.batchJobsPerSeed = batchJobsPerSeed; + return this; + } + + public MockBatchBuilder invocationsPerBatchJob(int invocationsPerBatchJob) { + this.invocationsPerBatchJob = invocationsPerBatchJob; + return this; + } + + public MockBatchBuilder seedJobDefinitionId(String seedJobDefinitionId) { + this.seedJobDefinitionId = seedJobDefinitionId; + return this; + } + + public MockBatchBuilder monitorJobDefinitionId(String monitorJobDefinitionId) { + this.monitorJobDefinitionId = monitorJobDefinitionId; + return this; + } + + public MockBatchBuilder batchJobDefinitionId(String batchJobDefinitionId) { + this.batchJobDefinitionId = batchJobDefinitionId; + return this; + } + + public MockBatchBuilder suspended() { + this.suspended = true; + return this; + } + + public MockBatchBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockBatchBuilder createUserId(String createUserId) { + this.createUserId = createUserId; + return this; + } + + public MockBatchBuilder startTime(Date startTime) { + this.startTime = startTime; + return this; + } + + public MockBatchBuilder executionStartTime(Date executionStartTime) { + this.executionStartTime = executionStartTime; + return this; + } + + public Batch build() { + Batch batch = mock(Batch.class); + when(batch.getId()).thenReturn(id); + when(batch.getType()).thenReturn(type); + when(batch.getTotalJobs()).thenReturn(totalJobs); + when(batch.getJobsCreated()).thenReturn(jobsCreated); + when(batch.getBatchJobsPerSeed()).thenReturn(batchJobsPerSeed); + when(batch.getInvocationsPerBatchJob()).thenReturn(invocationsPerBatchJob); + when(batch.getSeedJobDefinitionId()).thenReturn(seedJobDefinitionId); + when(batch.getMonitorJobDefinitionId()).thenReturn(monitorJobDefinitionId); + when(batch.getBatchJobDefinitionId()).thenReturn(batchJobDefinitionId); + when(batch.isSuspended()).thenReturn(suspended); + when(batch.getTenantId()).thenReturn(tenantId); + when(batch.getCreateUserId()).thenReturn(createUserId); + when(batch.getStartTime()).thenReturn(startTime); + when(batch.getExecutionStartTime()).thenReturn(executionStartTime); + return batch; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockBatchStatisticsBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockBatchStatisticsBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..c32703f4b802890015325adb55aa480749aab8d5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockBatchStatisticsBuilder.java @@ -0,0 +1,145 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.batch.BatchStatistics; + +import java.util.Date; + +public class MockBatchStatisticsBuilder { + + protected String id; + protected String type; + protected int size; + protected int jobsCreated; + protected int batchJobsPerSeed; + protected int invocationsPerBatchJob; + protected String seedJobDefinitionId; + protected String monitorJobDefinitionId; + protected String batchJobDefinitionId; + protected String tenantId; + protected String createUserId; + protected int remainingJobs; + protected int completedJobs; + protected int failedJobs; + protected boolean suspended; + protected Date startTime; + + public MockBatchStatisticsBuilder id(String id) { + this.id = id; + return this; + } + + public MockBatchStatisticsBuilder type(String type) { + this.type = type; + return this; + } + + public MockBatchStatisticsBuilder size(int size) { + this.size = size; + return this; + } + + public MockBatchStatisticsBuilder jobsCreated(int jobsCreated) { + this.jobsCreated = jobsCreated; + return this; + } + + public MockBatchStatisticsBuilder batchJobsPerSeed(int batchJobsPerSeed) { + this.batchJobsPerSeed = batchJobsPerSeed; + return this; + } + + public MockBatchStatisticsBuilder invocationsPerBatchJob(int invocationsPerBatchJob) { + this.invocationsPerBatchJob = invocationsPerBatchJob; + return this; + } + + public MockBatchStatisticsBuilder seedJobDefinitionId(String seedJobDefinitionId) { + this.seedJobDefinitionId = seedJobDefinitionId; + return this; + } + + public MockBatchStatisticsBuilder monitorJobDefinitionId(String monitorJobDefinitionId) { + this.monitorJobDefinitionId = monitorJobDefinitionId; + return this; + } + + public MockBatchStatisticsBuilder batchJobDefinitionId(String batchJobDefinitionId) { + this.batchJobDefinitionId = batchJobDefinitionId; + return this; + } + + public MockBatchStatisticsBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockBatchStatisticsBuilder createUserId(String createUserId) { + this.createUserId = createUserId; + return this; + } + + public MockBatchStatisticsBuilder remainingJobs(int remainingJobs) { + this.remainingJobs = remainingJobs; + return this; + } + + public MockBatchStatisticsBuilder completedJobs(int completedJobs) { + this.completedJobs = completedJobs; + return this; + } + + public MockBatchStatisticsBuilder failedJobs(int failedJobs) { + this.failedJobs = failedJobs; + return this; + } + + public MockBatchStatisticsBuilder suspended() { + this.suspended = true; + return this; + } + + public MockBatchStatisticsBuilder startTime(Date startTime) { + this.startTime = startTime; + return this; + } + + public BatchStatistics build() { + BatchStatistics batchStatistics = mock(BatchStatistics.class); + when(batchStatistics.getId()).thenReturn(id); + when(batchStatistics.getType()).thenReturn(type); + when(batchStatistics.getTotalJobs()).thenReturn(size); + when(batchStatistics.getJobsCreated()).thenReturn(jobsCreated); + when(batchStatistics.getBatchJobsPerSeed()).thenReturn(batchJobsPerSeed); + when(batchStatistics.getInvocationsPerBatchJob()).thenReturn(invocationsPerBatchJob); + when(batchStatistics.getSeedJobDefinitionId()).thenReturn(seedJobDefinitionId); + when(batchStatistics.getMonitorJobDefinitionId()).thenReturn(monitorJobDefinitionId); + when(batchStatistics.getBatchJobDefinitionId()).thenReturn(batchJobDefinitionId); + when(batchStatistics.getTenantId()).thenReturn(tenantId); + when(batchStatistics.getCreateUserId()).thenReturn(createUserId); + when(batchStatistics.getRemainingJobs()).thenReturn(remainingJobs); + when(batchStatistics.getCompletedJobs()).thenReturn(completedJobs); + when(batchStatistics.getFailedJobs()).thenReturn(failedJobs); + when(batchStatistics.isSuspended()).thenReturn(suspended); + when(batchStatistics.getStartTime()).thenReturn(startTime); + return batchStatistics; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockCaseDefinitionBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockCaseDefinitionBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..4fc624da2541ea3994a3f02d492a355f39cd7ce5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockCaseDefinitionBuilder.java @@ -0,0 +1,102 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.repository.CaseDefinition; + +/** + * + * @author Roman Smirnov + * + */ +public class MockCaseDefinitionBuilder { + + private String id = null; + private String key = null; + private String category = null; + private String name = null; + private int version = 0; + private String resource = null; + protected String diagramResource = null; + private String deploymentId = null; + private String tenantId = null; + + public MockCaseDefinitionBuilder id(String id) { + this.id = id; + return this; + } + + public MockCaseDefinitionBuilder key(String key) { + this.key = key; + return this; + } + + public MockCaseDefinitionBuilder category(String category) { + this.category = category; + return this; + } + + public MockCaseDefinitionBuilder name(String name) { + this.name = name; + return this; + } + + public MockCaseDefinitionBuilder version(int version) { + this.version = version; + return this; + } + + public MockCaseDefinitionBuilder resource(String resource) { + this.resource = resource; + return this; + } + + public MockCaseDefinitionBuilder diagram(String diagramResource) { + this.diagramResource = diagramResource; + return this; + } + + public MockCaseDefinitionBuilder deploymentId(String deploymentId) { + this.deploymentId = deploymentId; + return this; + } + + public MockCaseDefinitionBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public CaseDefinition build() { + CaseDefinition mockDefinition = mock(CaseDefinition.class); + + when(mockDefinition.getId()).thenReturn(id); + when(mockDefinition.getCategory()).thenReturn(category); + when(mockDefinition.getName()).thenReturn(name); + when(mockDefinition.getKey()).thenReturn(key); + when(mockDefinition.getVersion()).thenReturn(version); + when(mockDefinition.getResourceName()).thenReturn(resource); + when(mockDefinition.getDiagramResourceName()).thenReturn(diagramResource); + when(mockDefinition.getDeploymentId()).thenReturn(deploymentId); + when(mockDefinition.getTenantId()).thenReturn(tenantId); + + return mockDefinition; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionDefinitionBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionDefinitionBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..8127f33f79b27fef4e8a064772b08cd2af852657 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionDefinitionBuilder.java @@ -0,0 +1,118 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.repository.DecisionDefinition; + +public class MockDecisionDefinitionBuilder { + + private String id = null; + private String key = null; + private String category = null; + private String name = null; + private int version = 0; + private String resource = null; + private String diagramResource = null; + private String deploymentId = null; + private String tenantId = null; + private String decisionRequirementsDefinitionId = null; + private String decisionRequirementsDefinitionKey = null; + private String versionTag = null; + + public MockDecisionDefinitionBuilder id(String id) { + this.id = id; + return this; + } + + public MockDecisionDefinitionBuilder key(String key) { + this.key = key; + return this; + } + + public MockDecisionDefinitionBuilder category(String category) { + this.category = category; + return this; + } + + public MockDecisionDefinitionBuilder name(String name) { + this.name = name; + return this; + } + + public MockDecisionDefinitionBuilder version(int version) { + this.version = version; + return this; + } + + public MockDecisionDefinitionBuilder resource(String resource) { + this.resource = resource; + return this; + } + + public MockDecisionDefinitionBuilder diagram(String diagramResource) { + this.diagramResource = diagramResource; + return this; + } + + public MockDecisionDefinitionBuilder deploymentId(String deploymentId) { + this.deploymentId = deploymentId; + return this; + } + + public MockDecisionDefinitionBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockDecisionDefinitionBuilder decisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) { + this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId; + return this; + } + + public MockDecisionDefinitionBuilder decisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) { + this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey; + return this; + } + + public MockDecisionDefinitionBuilder versionTag(String versionTag) { + this.versionTag = versionTag; + return this; + } + + public DecisionDefinition build() { + DecisionDefinition mockDefinition = mock(DecisionDefinition.class); + + when(mockDefinition.getId()).thenReturn(id); + when(mockDefinition.getCategory()).thenReturn(category); + when(mockDefinition.getName()).thenReturn(name); + when(mockDefinition.getKey()).thenReturn(key); + when(mockDefinition.getVersion()).thenReturn(version); + when(mockDefinition.getResourceName()).thenReturn(resource); + when(mockDefinition.getDiagramResourceName()).thenReturn(diagramResource); + when(mockDefinition.getDeploymentId()).thenReturn(deploymentId); + when(mockDefinition.getTenantId()).thenReturn(tenantId); + when(mockDefinition.getDecisionRequirementsDefinitionId()).thenReturn(decisionRequirementsDefinitionId); + when(mockDefinition.getDecisionRequirementsDefinitionKey()).thenReturn(decisionRequirementsDefinitionKey); + when(mockDefinition.getVersionTag()).thenReturn(versionTag); + + return mockDefinition; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionRequirementsDefinitionBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionRequirementsDefinitionBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..ae2cecbbd84a0d19b1470c2ce6a688d89f7e9e6e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionRequirementsDefinitionBuilder.java @@ -0,0 +1,97 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinition; + +public class MockDecisionRequirementsDefinitionBuilder { + + private String id = null; + private String key = null; + private String category = null; + private String name = null; + private int version = 0; + private String resource = null; + private String diagramResource = null; + private String deploymentId = null; + private String tenantId = null; + + public MockDecisionRequirementsDefinitionBuilder id(String id) { + this.id = id; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder key(String key) { + this.key = key; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder category(String category) { + this.category = category; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder name(String name) { + this.name = name; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder version(int version) { + this.version = version; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder resource(String resource) { + this.resource = resource; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder diagram(String diagramResource) { + this.diagramResource = diagramResource; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder deploymentId(String deploymentId) { + this.deploymentId = deploymentId; + return this; + } + + public MockDecisionRequirementsDefinitionBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public DecisionRequirementsDefinition build() { + DecisionRequirementsDefinition mockDefinition = mock(DecisionRequirementsDefinition.class); + + when(mockDefinition.getId()).thenReturn(id); + when(mockDefinition.getCategory()).thenReturn(category); + when(mockDefinition.getName()).thenReturn(name); + when(mockDefinition.getKey()).thenReturn(key); + when(mockDefinition.getVersion()).thenReturn(version); + when(mockDefinition.getResourceName()).thenReturn(resource); + when(mockDefinition.getDiagramResourceName()).thenReturn(diagramResource); + when(mockDefinition.getDeploymentId()).thenReturn(deploymentId); + when(mockDefinition.getTenantId()).thenReturn(tenantId); + + return mockDefinition; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionResultBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionResultBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..f56b1599a7d14946968c53de9b59093025bc85e2 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionResultBuilder.java @@ -0,0 +1,83 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.dmn.engine.DmnDecisionResult; +import org.camunda.bpm.dmn.engine.DmnDecisionResultEntries; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Philipp Ossler + */ +public class MockDecisionResultBuilder { + + protected List entries = new ArrayList(); + + public MockDecisionResultEntriesBuilder resultEntries() { + return new MockDecisionResultEntriesBuilder(this); + } + + public void addResultEntries(DmnDecisionResultEntries resultEntries) { + entries.add(resultEntries); + } + + public DmnDecisionResult build() { + SimpleDecisionResult decisionTableResult = new SimpleDecisionResult(); + decisionTableResult.addAll(entries); + return decisionTableResult; + } + + protected class SimpleDecisionResult extends ArrayList implements DmnDecisionResult { + + private static final long serialVersionUID = 1L; + + @Override + public DmnDecisionResultEntries getFirstResult() { + throw new UnsupportedOperationException(); + } + + @Override + public DmnDecisionResultEntries getSingleResult() { + throw new UnsupportedOperationException(); + } + + @Override + public List collectEntries(String outputName) { + throw new UnsupportedOperationException(); + } + + @Override + public List> getResultList() { + throw new UnsupportedOperationException(); + } + + @Override + public T getSingleEntry() { + throw new UnsupportedOperationException(); + } + + @Override + public T getSingleEntryTyped() { + throw new UnsupportedOperationException(); + } + + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionResultEntriesBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionResultEntriesBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..3ca0ebc8945931942ea5109f00dff2306223930b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDecisionResultEntriesBuilder.java @@ -0,0 +1,126 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import java.util.HashMap; +import java.util.Map; + +import org.camunda.bpm.dmn.engine.DmnDecisionResult; +import org.camunda.bpm.dmn.engine.DmnDecisionResultEntries; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Philipp Ossler + */ +public class MockDecisionResultEntriesBuilder { + + protected final MockDecisionResultBuilder mockDecisionResultBuilder; + + protected Map entries = new HashMap(); + + public MockDecisionResultEntriesBuilder(MockDecisionResultBuilder mockDecisionResultBuilder) { + this.mockDecisionResultBuilder = mockDecisionResultBuilder; + } + + public MockDecisionResultEntriesBuilder entry(String key, TypedValue value) { + entries.put(key, value); + return this; + } + + public MockDecisionResultBuilder endResultEntries() { + SimpleDecisionResultEntries resultEntires = new SimpleDecisionResultEntries(entries); + + mockDecisionResultBuilder.addResultEntries(resultEntires); + + return mockDecisionResultBuilder; + } + + public MockDecisionResultEntriesBuilder resultEntries() { + return endResultEntries().resultEntries(); + } + + public DmnDecisionResult build() { + return endResultEntries().build(); + } + + protected static class SimpleDecisionResultEntries extends HashMap implements DmnDecisionResultEntries { + + private static final long serialVersionUID = 1L; + + protected final Map typedEntries; + + public SimpleDecisionResultEntries(Map entries) { + super(asEntryMap(entries)); + + this.typedEntries = entries; + } + + private static Map asEntryMap(Map typedValueMap) { + Map entryMap = new HashMap(); + + for(Map.Entry entry : typedValueMap.entrySet()) { + entryMap.put(entry.getKey(), entry.getValue().getValue()); + } + + return entryMap; + } + + @Override + public T getFirstEntry() { + throw new UnsupportedOperationException(); + } + + @Override + public T getSingleEntry() { + throw new UnsupportedOperationException(); + } + + @SuppressWarnings("unchecked") + @Override + public T getEntry(String name) { + return (T) typedEntries.get(name).getValue(); + } + + @SuppressWarnings("unchecked") + @Override + public T getEntryTyped(String name) { + return (T) typedEntries.get(name); + } + + @Override + public T getFirstEntryTyped() { + throw new UnsupportedOperationException(); + } + + @Override + public T getSingleEntryTyped() { + throw new UnsupportedOperationException(); + } + + @Override + public Map getEntryMap() { + throw new UnsupportedOperationException(); + } + + @Override + public Map getEntryMapTyped() { + throw new UnsupportedOperationException(); + } + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDefinitionBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDefinitionBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..7db96fa91cd84024e87c7be7ae12cf3a0afe788e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockDefinitionBuilder.java @@ -0,0 +1,129 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.repository.ProcessDefinition; + +public class MockDefinitionBuilder { + + private String id = null; + private String key = null; + private String category = null; + private String description = null; + private String name = null; + private int version = 0; + private String resource = null; + private String deploymentId = null; + private String diagram = null; + private boolean suspended = false; + private boolean startFormKey = false; + private String tenantId = null; + private String versionTag = null; + private boolean isStartableInTasklist = true; + + public MockDefinitionBuilder id(String id) { + this.id = id; + return this; + } + + public MockDefinitionBuilder key(String key) { + this.key = key; + return this; + } + + public MockDefinitionBuilder category(String category) { + this.category = category; + return this; + } + + public MockDefinitionBuilder description(String description) { + this.description = description; + return this; + } + + public MockDefinitionBuilder name(String name) { + this.name = name; + return this; + } + + public MockDefinitionBuilder version(int version) { + this.version = version; + return this; + } + + public MockDefinitionBuilder resource(String resource) { + this.resource = resource; + return this; + } + + public MockDefinitionBuilder deploymentId(String deploymentId) { + this.deploymentId = deploymentId; + return this; + } + + public MockDefinitionBuilder diagram(String diagram) { + this.diagram = diagram; + return this; + } + + public MockDefinitionBuilder suspended(boolean suspended) { + this.suspended = suspended; + return this; + } + + public MockDefinitionBuilder startFormKey(boolean startFormKey) { + this.startFormKey = startFormKey; + return this; + } + + public MockDefinitionBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockDefinitionBuilder versionTag(String versionTag) { + this.versionTag = versionTag; + return this; + } + + public MockDefinitionBuilder isStartableInTasklist(boolean isStartableInTasklist) { + this.isStartableInTasklist = isStartableInTasklist; + return this; + } + + public ProcessDefinition build() { + ProcessDefinition mockDefinition = mock(ProcessDefinition.class); + when(mockDefinition.getId()).thenReturn(id); + when(mockDefinition.getCategory()).thenReturn(category); + when(mockDefinition.getName()).thenReturn(name); + when(mockDefinition.getKey()).thenReturn(key); + when(mockDefinition.getDescription()).thenReturn(description); + when(mockDefinition.getVersion()).thenReturn(version); + when(mockDefinition.getResourceName()).thenReturn(resource); + when(mockDefinition.getDeploymentId()).thenReturn(deploymentId); + when(mockDefinition.getDiagramResourceName()).thenReturn(diagram); + when(mockDefinition.isSuspended()).thenReturn(suspended); + when(mockDefinition.hasStartFormKey()).thenReturn(startFormKey); + when(mockDefinition.getTenantId()).thenReturn(tenantId); + when(mockDefinition.getVersionTag()).thenReturn(versionTag); + when(mockDefinition.isStartableInTasklist()).thenReturn(isStartableInTasklist); + return mockDefinition; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockExternalTaskBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockExternalTaskBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..07a07d374f974a220b5f3da93507efd387d974b7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockExternalTaskBuilder.java @@ -0,0 +1,199 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Date; + +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Thorben Lindhauer + * + */ +public class MockExternalTaskBuilder { + + protected String activityId; + protected String activityInstanceId; + protected String errorMessage; + protected String executionId; + protected String id; + protected Date lockExpirationTime; + protected Date createTime; + protected String processDefinitionId; + protected String processDefinitionKey; + protected String processDefinitionVersionTag; + protected String processInstanceId; + protected Integer retries; + protected boolean suspended; + protected String topicName; + protected String workerId; + protected String tenantId; + protected VariableMap variables = Variables.createVariables(); + protected long priority; + protected String businessKey; + + public MockExternalTaskBuilder activityId(String activityId) { + this.activityId = activityId; + return this; + } + + public MockExternalTaskBuilder activityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + return this; + } + + public MockExternalTaskBuilder errorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + public MockExternalTaskBuilder executionId(String executionId) { + this.executionId = executionId; + return this; + } + + public MockExternalTaskBuilder id(String id) { + this.id = id; + return this; + } + + public MockExternalTaskBuilder lockExpirationTime(Date lockExpirationTime) { + this.lockExpirationTime = lockExpirationTime; + return this; + } + + public MockExternalTaskBuilder createTime(Date createTime) { + this.createTime = createTime; + return this; + } + + public MockExternalTaskBuilder processDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + return this; + } + + public MockExternalTaskBuilder processDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + return this; + } + + public MockExternalTaskBuilder processDefinitionVersionTag(String processDefinitionVersionTag) { + this.processDefinitionVersionTag = processDefinitionVersionTag; + return this; + } + + public MockExternalTaskBuilder processInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + return this; + } + + public MockExternalTaskBuilder retries(Integer retries) { + this.retries = retries; + return this; + } + + public MockExternalTaskBuilder suspended(boolean suspended) { + this.suspended = suspended; + return this; + } + + public MockExternalTaskBuilder topicName(String topicName) { + this.topicName = topicName; + return this; + } + + public MockExternalTaskBuilder workerId(String workerId) { + this.workerId = workerId; + return this; + } + + public MockExternalTaskBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockExternalTaskBuilder variable(String variableName, TypedValue value) { + this.variables.putValueTyped(variableName, value); + return this; + } + + public MockExternalTaskBuilder priority(long priority) { + this.priority = priority; + return this; + } + + public MockExternalTaskBuilder businessKey(String businessKey) { + this.businessKey = businessKey; + return this; + } + + public ExternalTask buildExternalTask() { + ExternalTask task = mock(ExternalTask.class); + when(task.getActivityId()).thenReturn(activityId); + when(task.getActivityInstanceId()).thenReturn(activityInstanceId); + when(task.getErrorMessage()).thenReturn(errorMessage); + when(task.getExecutionId()).thenReturn(executionId); + when(task.getId()).thenReturn(id); + when(task.getLockExpirationTime()).thenReturn(lockExpirationTime); + when(task.getCreateTime()).thenReturn(createTime); + when(task.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(task.getProcessDefinitionKey()).thenReturn(processDefinitionKey); + when(task.getProcessDefinitionVersionTag()).thenReturn(processDefinitionVersionTag); + when(task.getProcessInstanceId()).thenReturn(processInstanceId); + when(task.getRetries()).thenReturn(retries); + when(task.isSuspended()).thenReturn(suspended); + when(task.getTopicName()).thenReturn(topicName); + when(task.getWorkerId()).thenReturn(workerId); + when(task.getTenantId()).thenReturn(tenantId); + when(task.getPriority()).thenReturn(priority); + when(task.getBusinessKey()).thenReturn(businessKey); + + return task; + } + + public LockedExternalTask buildLockedExternalTask() { + LockedExternalTask task = mock(LockedExternalTask.class); + when(task.getActivityId()).thenReturn(activityId); + when(task.getActivityInstanceId()).thenReturn(activityInstanceId); + when(task.getErrorMessage()).thenReturn(errorMessage); + when(task.getExecutionId()).thenReturn(executionId); + when(task.getId()).thenReturn(id); + when(task.getLockExpirationTime()).thenReturn(lockExpirationTime); + when(task.getCreateTime()).thenReturn(createTime); + when(task.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(task.getProcessDefinitionKey()).thenReturn(processDefinitionKey); + when(task.getProcessDefinitionVersionTag()).thenReturn(processDefinitionVersionTag); + when(task.getProcessInstanceId()).thenReturn(processInstanceId); + when(task.getRetries()).thenReturn(retries); + when(task.getTopicName()).thenReturn(topicName); + when(task.getWorkerId()).thenReturn(workerId); + when(task.getTenantId()).thenReturn(tenantId); + when(task.getVariables()).thenReturn(variables); + when(task.getPriority()).thenReturn(priority); + + return task; + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockFilterBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockFilterBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..5dee8d19995b2d04832729d2d8b7a37619c602a6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockFilterBuilder.java @@ -0,0 +1,81 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Map; + +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.query.Query; + +/** + * @author Sebastian Menski + */ +public class MockFilterBuilder { + + protected String id; + protected String resourceType; + protected String name; + protected String owner; + protected Query query; + protected Map properties; + + public MockFilterBuilder id(String id) { + this.id = id; + return this; + } + + public MockFilterBuilder resourceType(String resourceType) { + this.resourceType = resourceType; + return this; + } + + public MockFilterBuilder name(String name) { + this.name = name; + return this; + } + + public MockFilterBuilder owner(String owner) { + this.owner = owner; + return this; + } + + public MockFilterBuilder query(Query query) { + this.query = query; + return this; + } + + public MockFilterBuilder properties(Map properties) { + this.properties = properties; + return this; + } + + @SuppressWarnings("unchecked") + public Filter build() { + Filter filter = mock(Filter.class); + when(filter.getId()).thenReturn(id); + when(filter.getResourceType()).thenReturn(resourceType); + when(filter.getName()).thenReturn(name); + when(filter.getOwner()).thenReturn(owner); + when(filter.getQuery()).thenReturn(query); + when(filter.getProperties()).thenReturn(properties); + return filter; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockGroupBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockGroupBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..5f1f89a3c7521f213948bfeb5507c51d96d7c632 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockGroupBuilder.java @@ -0,0 +1,54 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.identity.Group; + +public class MockGroupBuilder { + + protected String id; + protected String name; + protected String type; + + public MockGroupBuilder id(String id) { + this.id = id; + return this; + } + + public MockGroupBuilder name(String name) { + this.name = name; + return this; + } + + public MockGroupBuilder type(String type) { + this.type = type; + return this; + } + + @SuppressWarnings("unchecked") + public Group build() { + Group group = mock(Group.class); + when(group.getId()).thenReturn(id); + when(group.getName()).thenReturn(name); + when(group.getType()).thenReturn(type); + return group; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricBatchBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricBatchBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..ca1058079b0e02eb39ea28c60d5537489197fdbf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricBatchBuilder.java @@ -0,0 +1,132 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Date; + +import org.camunda.bpm.engine.batch.history.HistoricBatch; + +public class MockHistoricBatchBuilder { + + protected String id; + protected String type; + protected int totalJobs; + protected int batchJobsPerSeed; + protected int invocationsPerBatchJob; + protected String seedJobDefinitionId; + protected String monitorJobDefinitionId; + protected String batchJobDefinitionId; + protected String tenantId; + protected String createUserId; + protected Date startTime; + protected Date executionStartTime; + protected Date endTime; + protected Date removalTime; + + public MockHistoricBatchBuilder id(String id) { + this.id = id; + return this; + } + + public MockHistoricBatchBuilder type(String type) { + this.type = type; + return this; + } + + public MockHistoricBatchBuilder totalJobs(int totalJobs) { + this.totalJobs = totalJobs; + return this; + } + + public MockHistoricBatchBuilder batchJobsPerSeed(int batchJobsPerSeed) { + this.batchJobsPerSeed = batchJobsPerSeed; + return this; + } + + public MockHistoricBatchBuilder invocationsPerBatchJob(int invocationsPerBatchJob) { + this.invocationsPerBatchJob = invocationsPerBatchJob; + return this; + } + + public MockHistoricBatchBuilder seedJobDefinitionId(String seedJobDefinitionId) { + this.seedJobDefinitionId = seedJobDefinitionId; + return this; + } + + public MockHistoricBatchBuilder monitorJobDefinitionId(String monitorJobDefinitionId) { + this.monitorJobDefinitionId = monitorJobDefinitionId; + return this; + } + + public MockHistoricBatchBuilder batchJobDefinitionId(String batchJobDefinitionId) { + this.batchJobDefinitionId = batchJobDefinitionId; + return this; + } + + public MockHistoricBatchBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockHistoricBatchBuilder createUserId(String createUserId) { + this.createUserId = createUserId; + return this; + } + + public MockHistoricBatchBuilder startTime(Date startTime) { + this.startTime = startTime; + return this; + } + + public MockHistoricBatchBuilder executionStartTime(Date executionStartTime) { + this.executionStartTime = executionStartTime; + return this; + } + + public MockHistoricBatchBuilder endTime(Date endTime) { + this.endTime = endTime; + return this; + } + + public MockHistoricBatchBuilder removalTime(Date removalTime) { + this.removalTime = removalTime; + return this; + } + + public HistoricBatch build() { + HistoricBatch historicBatch = mock(HistoricBatch.class); + when(historicBatch.getId()).thenReturn(id); + when(historicBatch.getType()).thenReturn(type); + when(historicBatch.getTotalJobs()).thenReturn(totalJobs); + when(historicBatch.getBatchJobsPerSeed()).thenReturn(batchJobsPerSeed); + when(historicBatch.getInvocationsPerBatchJob()).thenReturn(invocationsPerBatchJob); + when(historicBatch.getSeedJobDefinitionId()).thenReturn(seedJobDefinitionId); + when(historicBatch.getMonitorJobDefinitionId()).thenReturn(monitorJobDefinitionId); + when(historicBatch.getBatchJobDefinitionId()).thenReturn(batchJobDefinitionId); + when(historicBatch.getTenantId()).thenReturn(tenantId); + when(historicBatch.getCreateUserId()).thenReturn(createUserId); + when(historicBatch.getStartTime()).thenReturn(startTime); + when(historicBatch.getExecutionStartTime()).thenReturn(executionStartTime); + when(historicBatch.getEndTime()).thenReturn(endTime); + when(historicBatch.getRemovalTime()).thenReturn(removalTime); + return historicBatch; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricVariableInstanceBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricVariableInstanceBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..25ccd9a273da3a489290b6807fb256c1565a45d6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricVariableInstanceBuilder.java @@ -0,0 +1,263 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Date; + +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * Creates variable mocks and simultaneously provides a ResponseSpecification + * to assert a result of this mock in json; expectations can be overriden using the + * methods {@link JsonSpec#setMatcher(String, org.hamcrest.Matcher)} and + * {@link JsonSpec#setEnclosedJsonSpec(String, JsonSpec)}. + * + * @author Thorben Lindhauer + */ +public class MockHistoricVariableInstanceBuilder { + + protected String id; + protected String name; + protected TypedValue value; + protected String processDefinitionKey; + protected String processDefinitionId; + protected String processInstanceId; + protected String executionId; + protected String errorMessage; + protected String activityInstanceId; + protected String caseDefinitionKey; + protected String caseDefinitionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String taskId; + protected String tenantId; + protected Date createTime; + protected Date removalTime; + protected String rootProcessInstanceId; + + public MockHistoricVariableInstanceBuilder id(String id) { + this.id = id; + return this; + } + + public MockHistoricVariableInstanceBuilder name(String name) { + this.name = name; + return this; + } + + public MockHistoricVariableInstanceBuilder typedValue(TypedValue value) { + this.value = value; + return this; + } + + public MockHistoricVariableInstanceBuilder processDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + return this; + } + + public MockHistoricVariableInstanceBuilder processDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + return this; + } + + public MockHistoricVariableInstanceBuilder processInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + return this; + } + + public MockHistoricVariableInstanceBuilder executionId(String executionId) { + this.executionId = executionId; + return this; + } + + public MockHistoricVariableInstanceBuilder errorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + public MockHistoricVariableInstanceBuilder activityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + return this; + } + + public MockHistoricVariableInstanceBuilder caseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + return this; + } + + public MockHistoricVariableInstanceBuilder caseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + return this; + } + + public MockHistoricVariableInstanceBuilder caseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + return this; + } + + public MockHistoricVariableInstanceBuilder caseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + return this; + } + + public MockHistoricVariableInstanceBuilder taskId(String taskId) { + this.taskId = taskId; + return this; + } + + public MockHistoricVariableInstanceBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockHistoricVariableInstanceBuilder createTime(Date createTime) { + this.createTime = createTime; + return this; + } + + public MockHistoricVariableInstanceBuilder removalTime(Date removalTime) { + this.removalTime = removalTime; + return this; + } + + public MockHistoricVariableInstanceBuilder rootProcessInstanceId(String rootProcessInstanceId) { + this.rootProcessInstanceId = rootProcessInstanceId; + return this; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public TypedValue getTypedValue() { + return value; + } + + public Object getValue() { + return value.getValue(); + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getErrorMessage() { + return errorMessage; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getTaskId() { + return taskId; + } + + public String getTenantId() { + return tenantId; + } + + public Date getCreateTime() { + return createTime; + } + + public Date getRemovalTime() { + return removalTime; + } + + public String getRootProcessInstanceId() { + return rootProcessInstanceId; + } + + public HistoricVariableInstance build() { + HistoricVariableInstance mockVariable = mock(HistoricVariableInstance.class); + when(mockVariable.getId()).thenReturn(id); + when(mockVariable.getName()).thenReturn(name); + when(mockVariable.getVariableName()).thenReturn(name); + when(mockVariable.getTypeName()).thenReturn(value.getType().getName()); + when(mockVariable.getVariableTypeName()).thenReturn(value.getType().getName()); + + if (ObjectValue.class.isAssignableFrom(value.getClass())) { + ObjectValue objectValue = (ObjectValue) value; + if (objectValue.isDeserialized()) { + when(mockVariable.getValue()).thenReturn(value.getValue()); + } else { + when(mockVariable.getValue()).thenReturn(null); + } + } else { + when(mockVariable.getValue()).thenReturn(value.getValue()); + } + + when(mockVariable.getTypedValue()).thenReturn(value); + when(mockVariable.getProcessDefinitionKey()).thenReturn(processDefinitionKey); + when(mockVariable.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(mockVariable.getProcessInstanceId()).thenReturn(processInstanceId); + when(mockVariable.getExecutionId()).thenReturn(executionId); + when(mockVariable.getErrorMessage()).thenReturn(errorMessage); + when(mockVariable.getActivtyInstanceId()).thenReturn(activityInstanceId); + when(mockVariable.getActivityInstanceId()).thenReturn(activityInstanceId); + when(mockVariable.getCaseDefinitionKey()).thenReturn(caseDefinitionKey); + when(mockVariable.getCaseDefinitionId()).thenReturn(caseDefinitionId); + when(mockVariable.getCaseInstanceId()).thenReturn(caseInstanceId); + when(mockVariable.getCaseExecutionId()).thenReturn(caseExecutionId); + when(mockVariable.getTaskId()).thenReturn(taskId); + when(mockVariable.getTenantId()).thenReturn(tenantId); + when(mockVariable.getCreateTime()).thenReturn(createTime); + when(mockVariable.getRemovalTime()).thenReturn(removalTime); + when(mockVariable.getRootProcessInstanceId()).thenReturn(rootProcessInstanceId); + + return mockVariable; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricVariableUpdateBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricVariableUpdateBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..abbb439f1092f3e1ea2a19e5e70a11010e1f235d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockHistoricVariableUpdateBuilder.java @@ -0,0 +1,277 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * @author Thorben Lindhauer + * + */ +public class MockHistoricVariableUpdateBuilder { + + protected String id; + protected String name; + protected String variableInstanceId; + protected TypedValue typedValue; + protected String processDefinitionKey; + protected String processDefinitionId; + protected String processInstanceId; + protected String errorMessage; + protected String activityInstanceId; + protected int revision; + protected String time; + protected String executionId; + protected String taskId; + protected String caseDefinitionKey; + protected String caseDefinitionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String tenantId; + protected String userOperationId; + protected boolean initial; + + public MockHistoricVariableUpdateBuilder id(String id) { + this.id = id; + return this; + } + + public MockHistoricVariableUpdateBuilder name(String name) { + this.name = name; + return this; + } + + public MockHistoricVariableUpdateBuilder variableInstanceId(String variableInstanceId) { + this.variableInstanceId = variableInstanceId; + return this; + } + + public MockHistoricVariableUpdateBuilder typedValue(TypedValue value) { + this.typedValue = value; + return this; + } + + public MockHistoricVariableUpdateBuilder processDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + return this; + } + + public MockHistoricVariableUpdateBuilder processDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + return this; + } + + public MockHistoricVariableUpdateBuilder processInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + return this; + } + + public MockHistoricVariableUpdateBuilder errorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + public MockHistoricVariableUpdateBuilder activityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + return this; + } + + public MockHistoricVariableUpdateBuilder executionId(String executionId) { + this.executionId = executionId; + return this; + } + + public MockHistoricVariableUpdateBuilder taskId(String taskId) { + this.taskId = taskId; + return this; + } + + public MockHistoricVariableUpdateBuilder time(String time) { + this.time = time; + return this; + } + + public MockHistoricVariableUpdateBuilder revision(int revision) { + this.revision = revision; + return this; + } + + public MockHistoricVariableUpdateBuilder caseDefinitionKey(String caseDefinitionKey) { + this.caseDefinitionKey = caseDefinitionKey; + return this; + } + + public MockHistoricVariableUpdateBuilder caseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + return this; + } + + public MockHistoricVariableUpdateBuilder caseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + return this; + } + + public MockHistoricVariableUpdateBuilder caseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + return this; + } + + public MockHistoricVariableUpdateBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockHistoricVariableUpdateBuilder userOperationId(String userOperationId) { + this.userOperationId = userOperationId; + return this; + } + + public MockHistoricVariableUpdateBuilder initial(boolean initial) { + this.initial = initial; + return this; + } + + public HistoricVariableUpdate build() { + HistoricVariableUpdate mockVariable = mock(HistoricVariableUpdate.class); + when(mockVariable.getId()).thenReturn(id); + when(mockVariable.getVariableName()).thenReturn(name); + when(mockVariable.getVariableInstanceId()).thenReturn(variableInstanceId); + when(mockVariable.getVariableTypeName()).thenReturn(typedValue.getType().getName()); + + if (ObjectValue.class.isAssignableFrom(typedValue.getClass())) { + ObjectValue objectValue = (ObjectValue) typedValue; + if (objectValue.isDeserialized()) { + when(mockVariable.getValue()).thenReturn(typedValue.getValue()); + } else { + when(mockVariable.getValue()).thenReturn(null); + } + } else { + when(mockVariable.getValue()).thenReturn(typedValue.getValue()); + } + + when(mockVariable.getTypedValue()).thenReturn(typedValue); + when(mockVariable.getProcessDefinitionKey()).thenReturn(processDefinitionKey); + when(mockVariable.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(mockVariable.getProcessInstanceId()).thenReturn(processInstanceId); + when(mockVariable.getErrorMessage()).thenReturn(errorMessage); + when(mockVariable.getRevision()).thenReturn(revision); + when(mockVariable.getTime()).thenReturn(DateTimeUtil.parseDate(time)); + when(mockVariable.getActivityInstanceId()).thenReturn(activityInstanceId); + when(mockVariable.getTaskId()).thenReturn(taskId); + when(mockVariable.getExecutionId()).thenReturn(executionId); + when(mockVariable.getTypeName()).thenReturn(typedValue.getType().getName()); + when(mockVariable.getCaseDefinitionKey()).thenReturn(caseDefinitionKey); + when(mockVariable.getCaseDefinitionId()).thenReturn(caseDefinitionId); + when(mockVariable.getCaseInstanceId()).thenReturn(caseInstanceId); + when(mockVariable.getCaseExecutionId()).thenReturn(caseExecutionId); + when(mockVariable.getTenantId()).thenReturn(tenantId); + when(mockVariable.getUserOperationId()).thenReturn(userOperationId); + when(mockVariable.isInitial()).thenReturn(initial); + + return mockVariable; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getVariableInstanceId() { + return variableInstanceId; + } + + public Object getValue() { + return typedValue.getValue(); + } + + public TypedValue getTypedValue() { + return typedValue; + } + + public String getProcessDefinitionKey() { + return processDefinitionKey; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getErrorMessage() { + return errorMessage; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public int getRevision() { + return revision; + } + + public String getTime() { + return time; + } + + public String getExecutionId() { + return executionId; + } + + public String getTaskId() { + return taskId; + } + + public String getCaseDefinitionKey() { + return caseDefinitionKey; + } + + public String getCaseDefinitionId() { + return caseDefinitionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getUserOperationId() { + return userOperationId; + } + + public String getTenantId() { + return tenantId; + } + + public boolean isInitial() { + return initial; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockJobBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockJobBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..cecb25da13a56cf72f1cde871638a8729c84f3e5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockJobBuilder.java @@ -0,0 +1,139 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Date; + +import org.camunda.bpm.engine.runtime.Job; + +public class MockJobBuilder { + + protected String id; + protected Date dueDate; + protected String exceptionMessage; + protected String executionId; + protected String processInstanceId; + protected String processDefinitionId; + protected String processDefinitionKey; + protected int retries; + protected boolean suspended; + protected long priority; + protected String jobDefinitionId; + protected String tenantId; + protected Date createTime; + protected String failedActivityId; + protected String batchId; + + public MockJobBuilder id(String id) { + this.id = id; + return this; + } + + public MockJobBuilder dueDate(Date dueDate) { + this.dueDate = dueDate; + return this; + } + + public MockJobBuilder exceptionMessage(String exceptionMessage) { + this.exceptionMessage = exceptionMessage; + return this; + } + + public MockJobBuilder executionId(String executionId) { + this.executionId = executionId; + return this; + } + + public MockJobBuilder processInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + return this; + } + + public MockJobBuilder processDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + return this; + } + + public MockJobBuilder processDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + return this; + } + + public MockJobBuilder suspended(boolean suspended) { + this.suspended = suspended; + return this; + } + + public MockJobBuilder priority(long priority) { + this.priority = priority; + return this; + } + + public MockJobBuilder retries(int retries) { + this.retries = retries; + return this; + } + + public MockJobBuilder jobDefinitionId(String jobDefinitionId) { + this.jobDefinitionId = jobDefinitionId; + return this; + } + + public MockJobBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockJobBuilder createTime(Date createTime) { + this.createTime = createTime; + return this; + } + + public MockJobBuilder failedActivityId(String failedActivityId) { + this.failedActivityId = failedActivityId; + return this; + } + + public MockJobBuilder batchId(String batchId) { + this.batchId = batchId; + return this; + } + + public Job build() { + Job mockJob = mock(Job.class); + when(mockJob.getId()).thenReturn(id); + when(mockJob.getDuedate()).thenReturn(dueDate); + when(mockJob.getExceptionMessage()).thenReturn(exceptionMessage); + when(mockJob.getExecutionId()).thenReturn(executionId); + when(mockJob.getProcessInstanceId()).thenReturn(processInstanceId); + when(mockJob.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(mockJob.getProcessDefinitionKey()).thenReturn(processDefinitionKey); + when(mockJob.getRetries()).thenReturn(retries); + when(mockJob.isSuspended()).thenReturn(suspended); + when(mockJob.getPriority()).thenReturn(priority); + when(mockJob.getJobDefinitionId()).thenReturn(jobDefinitionId); + when(mockJob.getTenantId()).thenReturn(tenantId); + when(mockJob.getCreateTime()).thenReturn(createTime); + when(mockJob.getFailedActivityId()).thenReturn(failedActivityId); + when(mockJob.getBatchId()).thenReturn(batchId); + return mockJob; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockJobDefinitionBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockJobDefinitionBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..cf6595da6e83081b762d430d8e1d810862f39c86 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockJobDefinitionBuilder.java @@ -0,0 +1,102 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.management.JobDefinition; + +public class MockJobDefinitionBuilder { + + protected String id; + protected String activityId; + protected String jobConfiguration; + protected String jobType; + protected Long jobPriority; + protected String processDefinitionKey; + protected String processDefinitionId; + protected boolean suspended; + protected String tenantId; + protected String deploymentId; + + public MockJobDefinitionBuilder id(String id) { + this.id = id; + return this; + } + + public MockJobDefinitionBuilder activityId(String activityId) { + this.activityId = activityId; + return this; + } + + public MockJobDefinitionBuilder jobConfiguration(String jobConfiguration) { + this.jobConfiguration = jobConfiguration; + return this; + } + + public MockJobDefinitionBuilder jobType(String jobType) { + this.jobType = jobType; + return this; + } + + public MockJobDefinitionBuilder jobPriority(Long priority) { + this.jobPriority = priority; + return this; + } + + public MockJobDefinitionBuilder processDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + return this; + } + + public MockJobDefinitionBuilder processDefinitionKey(String processDefinitionKey) { + this.processDefinitionKey = processDefinitionKey; + return this; + } + + public MockJobDefinitionBuilder suspended(boolean suspended) { + this.suspended = suspended; + return this; + } + + public MockJobDefinitionBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockJobDefinitionBuilder deploymentId(String deploymentId) { + this.deploymentId = deploymentId; + return this; + } + + public JobDefinition build() { + JobDefinition mockJobDefinition = mock(JobDefinition.class); + when(mockJobDefinition.getId()).thenReturn(id); + when(mockJobDefinition.getActivityId()).thenReturn(activityId); + when(mockJobDefinition.getJobConfiguration()).thenReturn(jobConfiguration); + when(mockJobDefinition.getOverridingJobPriority()).thenReturn(jobPriority); + when(mockJobDefinition.getJobType()).thenReturn(jobType); + when(mockJobDefinition.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(mockJobDefinition.getProcessDefinitionKey()).thenReturn(processDefinitionKey); + when(mockJobDefinition.isSuspended()).thenReturn(suspended); + when(mockJobDefinition.getTenantId()).thenReturn(tenantId); + when(mockJobDefinition.getDeploymentId()).thenReturn(deploymentId); + return mockJobDefinition; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockMigrationInstructionBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockMigrationInstructionBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..df60a6481bd300a466a9d8379d15598376c62ff1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockMigrationInstructionBuilder.java @@ -0,0 +1,66 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collections; +import java.util.List; + +import org.camunda.bpm.engine.migration.MigrationInstruction; + +public class MockMigrationInstructionBuilder { + + protected List sourceActivityIds; + protected List targetActivityIds; + protected boolean updateEventTrigger = false; + + public MockMigrationInstructionBuilder sourceActivityIds(List sourceActivityIds) { + this.sourceActivityIds = sourceActivityIds; + return this; + } + + public MockMigrationInstructionBuilder sourceActivityId(String sourceActivityId) { + this.sourceActivityIds = Collections.singletonList(sourceActivityId); + return this; + } + + public MockMigrationInstructionBuilder targetActivityIds(List targetActivityIds) { + this.targetActivityIds = targetActivityIds; + return this; + } + + public MockMigrationInstructionBuilder targetActivityId(String targetActivityId) { + this.targetActivityIds = Collections.singletonList(targetActivityId); + return this; + } + + public MockMigrationInstructionBuilder updateEventTrigger() { + this.updateEventTrigger = true; + return this; + } + + public MigrationInstruction build() { + MigrationInstruction migrationInstructionMock = mock(MigrationInstruction.class); + when(migrationInstructionMock.getSourceActivityId()).thenReturn(sourceActivityIds.get(0)); + when(migrationInstructionMock.getTargetActivityId()).thenReturn(targetActivityIds.get(0)); + when(migrationInstructionMock.isUpdateEventTrigger()).thenReturn(updateEventTrigger); + return migrationInstructionMock; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockMigrationPlanBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockMigrationPlanBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..ddb22272a718c46fd03528f66700aeddd9e039b3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockMigrationPlanBuilder.java @@ -0,0 +1,114 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.migration.MigrationInstruction; +import org.camunda.bpm.engine.migration.MigrationInstructionBuilder; +import org.camunda.bpm.engine.migration.MigrationInstructionsBuilder; +import org.camunda.bpm.engine.migration.MigrationPlan; +import org.camunda.bpm.engine.migration.MigrationPlanBuilder; +import org.camunda.bpm.engine.variable.VariableMap; + +public class MockMigrationPlanBuilder { + + protected String sourceProcessDefinitionId; + protected String targetProcessDefinitionId; + protected List instructions = new ArrayList(); + protected VariableMap variables; + + public MockMigrationPlanBuilder sourceProcessDefinitionId(String sourceProcessDefinitionId) { + this.sourceProcessDefinitionId = sourceProcessDefinitionId; + return this; + } + + public MockMigrationPlanBuilder targetProcessDefinitionId(String targetProcessDefinitionId) { + this.targetProcessDefinitionId = targetProcessDefinitionId; + return this; + } + + public MockMigrationPlanBuilder instructions(List instructions) { + this.instructions = instructions; + return this; + } + + public MockMigrationPlanBuilder instruction(MigrationInstruction instruction) { + instructions.add(instruction); + return this; + } + + public MockMigrationPlanBuilder instruction(String sourceActivityId, String targetActivityId) { + MigrationInstruction instructionMock = new MockMigrationInstructionBuilder() + .sourceActivityId(sourceActivityId) + .targetActivityId(targetActivityId) + .build(); + return instruction(instructionMock); + } + + public MockMigrationPlanBuilder instruction(String sourceActivityId, String targetActivityId, Boolean updateEventTrigger) { + MockMigrationInstructionBuilder instructionBuilder = new MockMigrationInstructionBuilder() + .sourceActivityId(sourceActivityId) + .targetActivityId(targetActivityId); + + if (Boolean.TRUE.equals(updateEventTrigger)) { + instructionBuilder = instructionBuilder.updateEventTrigger(); + } + + MigrationInstruction instructionMock = instructionBuilder + .build(); + return instruction(instructionMock); + } + + public MigrationPlan build() { + MigrationPlan migrationPlanMock = mock(MigrationPlan.class); + when(migrationPlanMock.getSourceProcessDefinitionId()).thenReturn(sourceProcessDefinitionId); + when(migrationPlanMock.getTargetProcessDefinitionId()).thenReturn(targetProcessDefinitionId); + when(migrationPlanMock.getInstructions()).thenReturn(instructions); + when(migrationPlanMock.getVariables()).thenReturn(variables); + return migrationPlanMock; + } + + public JoinedMigrationPlanBuilderMock builder() { + MigrationPlan migrationPlanMock = build(); + JoinedMigrationPlanBuilderMock migrationPlanBuilderMock = + mock(JoinedMigrationPlanBuilderMock.class, new FluentAnswer()); + + when(migrationPlanBuilderMock + .build()) + .thenReturn(migrationPlanMock); + + return migrationPlanBuilderMock; + } + + public MockMigrationPlanBuilder variables(VariableMap variables) { + this.variables = variables; + return this; + } + + public static interface JoinedMigrationPlanBuilderMock extends MigrationPlanBuilder, MigrationInstructionBuilder, MigrationInstructionsBuilder { + // Just an empty interface joining all migration plan builder interfaces together. + // Allows it to mock all three with one mock instance, which in turn makes invocation verification easier. + // Quite a hack that may break if the interfaces become incompatible in the future. + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockObjectValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockObjectValue.java new file mode 100644 index 0000000000000000000000000000000000000000..709bf32be4fde053c99cdd8d3f5fd35abdf0116e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockObjectValue.java @@ -0,0 +1,62 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import org.camunda.bpm.engine.variable.impl.value.ObjectValueImpl; +import org.camunda.bpm.engine.variable.value.ObjectValue; + +/** + * Subclass of {@link ObjectValueImpl} that allows to manipulate all of its properties + * from the outside such that it can be easily used when "mocking" (i.e. crafting them by hand) these values + * + * @author Thorben Lindhauer + * + */ +public class MockObjectValue extends ObjectValueImpl { + + private static final long serialVersionUID = 1L; + + public MockObjectValue(Object value) { + super(value); + } + + public MockObjectValue objectTypeName(String objectTypeName) { + this.objectTypeName = objectTypeName; + return this; + } + + public MockObjectValue serializedValue(String serializedValue) { + this.serializedValue = serializedValue; + return this; + } + + public static MockObjectValue fromObjectValue(ObjectValue objectValue) { + MockObjectValue result = new MockObjectValue(objectValue.getValue()); + + result.isDeserialized = objectValue.isDeserialized(); + result.objectTypeName = objectValue.getObjectTypeName(); + result.serializationDataFormat = objectValue.getSerializationDataFormat(); + result.serializedValue = objectValue.getValueSerialized(); + result.type = objectValue.getType(); + + return result; + } + + + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockProvider.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockProvider.java new file mode 100644 index 0000000000000000000000000000000000000000..d0d4e0c42b6449e41942aecfec80a5bd57ae6257 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockProvider.java @@ -0,0 +1,3397 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.withTimezone; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.camunda.bpm.application.ProcessApplicationInfo; +import org.camunda.bpm.dmn.engine.DmnDecisionResult; +import org.camunda.bpm.engine.EntityTypes; +import org.camunda.bpm.engine.ManagementService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.authorization.Authorization; +import org.camunda.bpm.engine.authorization.Permission; +import org.camunda.bpm.engine.authorization.Permissions; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.batch.BatchStatistics; +import org.camunda.bpm.engine.batch.history.HistoricBatch; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.filter.Filter; +import org.camunda.bpm.engine.filter.FilterQuery; +import org.camunda.bpm.engine.form.FormField; +import org.camunda.bpm.engine.form.FormProperty; +import org.camunda.bpm.engine.form.FormType; +import org.camunda.bpm.engine.form.StartFormData; +import org.camunda.bpm.engine.form.TaskFormData; +import org.camunda.bpm.engine.history.DurationReportResult; +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.history.HistoricActivityStatistics; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstance; +import org.camunda.bpm.engine.history.HistoricCaseActivityStatistics; +import org.camunda.bpm.engine.history.HistoricCaseInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInputInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceStatistics; +import org.camunda.bpm.engine.history.HistoricDecisionOutputInstance; +import org.camunda.bpm.engine.history.HistoricDetail; +import org.camunda.bpm.engine.history.HistoricExternalTaskLog; +import org.camunda.bpm.engine.history.HistoricFormField; +import org.camunda.bpm.engine.history.HistoricIdentityLinkLog; +import org.camunda.bpm.engine.history.HistoricIncident; +import org.camunda.bpm.engine.history.HistoricJobLog; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.history.HistoricTaskInstanceReportResult; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.history.UserOperationLogEntry; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.identity.User; +import org.camunda.bpm.engine.impl.TaskQueryImpl; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.form.CamundaFormRefImpl; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.impl.persistence.entity.MetricIntervalEntity; +import org.camunda.bpm.engine.impl.persistence.entity.ResourceEntity; +import org.camunda.bpm.engine.impl.telemetry.dto.ApplicationServerImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.CommandImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.DatabaseImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.InternalsImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.JdkImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.LicenseKeyDataImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.MetricImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.ProductImpl; +import org.camunda.bpm.engine.impl.telemetry.dto.TelemetryDataImpl; +import org.camunda.bpm.engine.management.ActivityStatistics; +import org.camunda.bpm.engine.management.IncidentStatistics; +import org.camunda.bpm.engine.management.JobDefinition; +import org.camunda.bpm.engine.management.MetricIntervalValue; +import org.camunda.bpm.engine.management.MetricsQuery; +import org.camunda.bpm.engine.management.ProcessDefinitionStatistics; +import org.camunda.bpm.engine.management.SetJobRetriesBuilder; +import org.camunda.bpm.engine.management.SetJobRetriesByJobsAsyncBuilder; +import org.camunda.bpm.engine.management.SetJobRetriesByProcessAsyncBuilder; +import org.camunda.bpm.engine.query.PeriodUnit; +import org.camunda.bpm.engine.query.Query; +import org.camunda.bpm.engine.repository.CaseDefinition; +import org.camunda.bpm.engine.repository.DecisionDefinition; +import org.camunda.bpm.engine.repository.DecisionRequirementsDefinition; +import org.camunda.bpm.engine.repository.Deployment; +import org.camunda.bpm.engine.repository.DeploymentWithDefinitions; +import org.camunda.bpm.engine.repository.ProcessDefinition; +import org.camunda.bpm.engine.repository.Resource; +import org.camunda.bpm.engine.rest.dto.task.TaskQueryDto; +import org.camunda.bpm.engine.runtime.CaseExecution; +import org.camunda.bpm.engine.runtime.CaseInstance; +import org.camunda.bpm.engine.runtime.EventSubscription; +import org.camunda.bpm.engine.runtime.Execution; +import org.camunda.bpm.engine.runtime.Incident; +import org.camunda.bpm.engine.runtime.Job; +import org.camunda.bpm.engine.runtime.MessageCorrelationResult; +import org.camunda.bpm.engine.runtime.MessageCorrelationResultType; +import org.camunda.bpm.engine.runtime.MessageCorrelationResultWithVariables; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.engine.runtime.ProcessInstanceWithVariables; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.task.Attachment; +import org.camunda.bpm.engine.task.Comment; +import org.camunda.bpm.engine.task.DelegationState; +import org.camunda.bpm.engine.task.IdentityLink; +import org.camunda.bpm.engine.task.IdentityLinkType; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.engine.task.TaskCountByCandidateGroupResult; +import org.camunda.bpm.engine.variable.VariableMap; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.impl.value.ObjectValueImpl; +import org.camunda.bpm.engine.variable.value.BytesValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.StringValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * Provides mocks for the basic engine entities, such as + * {@link ProcessDefinition}, {@link User}, etc., that are reused across the + * various kinds of tests. + * + * @author Thorben Lindhauer + * + */ +public abstract class MockProvider { + + public static final String FORMAT_APPLICATION_JSON = "application/json"; + + // general non existing Id + public static final String NON_EXISTING_ID = "nonExistingId"; + + // tenant ids + public static final String EXAMPLE_TENANT_ID = "aTenantId"; + public static final String ANOTHER_EXAMPLE_TENANT_ID = "anotherTenantId"; + public static final String EXAMPLE_TENANT_ID_LIST = EXAMPLE_TENANT_ID + "," + ANOTHER_EXAMPLE_TENANT_ID; + + // task State + public static final String EXAMPLE_HISTORIC_TASK_STATE = "aTaskState"; + + public static final String EXAMPLE_TENANT_NAME = "aTenantName"; + + // case activity ids + public static final String EXAMPLE_CASE_ACTIVITY_ID = "aCaseActivityId"; + public static final String ANOTHER_EXAMPLE_CASE_ACTIVITY_ID = "anotherCaseActivityId"; + public static final String EXAMPLE_CASE_ACTIVITY_ID_LIST = EXAMPLE_CASE_ACTIVITY_ID + "," + ANOTHER_EXAMPLE_CASE_ACTIVITY_ID; + + // version tag + public static final String EXAMPLE_VERSION_TAG = "aVersionTag"; + public static final String ANOTHER_EXAMPLE_VERSION_TAG = "anotherVersionTag"; + + // engine + public static final String EXAMPLE_PROCESS_ENGINE_NAME = "default"; + public static final String ANOTHER_EXAMPLE_PROCESS_ENGINE_NAME = "anotherEngineName"; + public static final String NON_EXISTING_PROCESS_ENGINE_NAME = "aNonExistingEngineName"; + + // task properties + public static final String EXAMPLE_TASK_ID = "anId"; + public static final String EXAMPLE_TASK_NAME = "aName"; + public static final String EXAMPLE_TASK_ASSIGNEE_NAME = "anAssignee"; + public static final String EXAMPLE_TASK_CREATE_TIME = withTimezone("2013-01-23T13:42:42"); + public static final String EXAMPLE_TASK_LAST_UPDATED = withTimezone("2013-01-23T13:42:45"); + public static final String EXAMPLE_TASK_DUE_DATE = withTimezone("2013-01-23T13:42:43"); + public static final String EXAMPLE_FOLLOW_UP_DATE = withTimezone("2013-01-23T13:42:44"); + public static final DelegationState EXAMPLE_TASK_DELEGATION_STATE = DelegationState.RESOLVED; + public static final String EXAMPLE_TASK_DESCRIPTION = "aDescription"; + public static final String EXAMPLE_TASK_EXECUTION_ID = "anExecution"; + public static final String EXAMPLE_TASK_OWNER = "anOwner"; + public static final String EXAMPLE_TASK_PARENT_TASK_ID = "aParentId"; + public static final int EXAMPLE_TASK_PRIORITY = 42; + public static final String EXAMPLE_TASK_DEFINITION_KEY = "aTaskDefinitionKey"; + public static final boolean EXAMPLE_TASK_SUSPENSION_STATE = false; + + public static final boolean EXAMPLE_TASK_ATTACHMENT_STATE = false; + + public static final boolean EXAMPLE_TASK_COMMENT_STATE = false; + + // task comment + public static final String EXAMPLE_TASK_COMMENT_ID = "aTaskCommentId"; + public static final String EXAMPLE_TASK_COMMENT_FULL_MESSAGE = "aTaskCommentFullMessage"; + public static final String EXAMPLE_TASK_COMMENT_TIME = withTimezone("2014-04-24T14:10:44"); + public static final String EXAMPLE_TASK_COMMENT_ROOT_PROCESS_INSTANCE_ID = "aRootProcInstId"; + + //process instance comment + public static final String EXAMPLE_PROCESS_INSTANCE_COMMENT_ID = "aProcessInstanceCommentId"; + public static final String EXAMPLE_PROCESS_INSTANCE_COMMENT_FULL_MESSAGE = "aProcessInstanceCommentFullMessage"; + + + // task attachment + public static final String EXAMPLE_TASK_ATTACHMENT_ID = "aTaskAttachmentId"; + public static final String EXAMPLE_TASK_ATTACHMENT_NAME = "aTaskAttachmentName"; + public static final String EXAMPLE_TASK_ATTACHMENT_DESCRIPTION = "aTaskAttachmentDescription"; + public static final String EXAMPLE_TASK_ATTACHMENT_TYPE = "aTaskAttachmentType"; + public static final String EXAMPLE_TASK_ATTACHMENT_URL = "aTaskAttachmentUrl"; + public static final String EXAMPLE_TASK_ATTACHMENT_CREATE_DATE = withTimezone("2018-07-19T15:02:36"); + public static final String EXAMPLE_TASK_ATTACHMENT_REMOVAL_DATE = withTimezone("2018-10-17T13:35:07"); + public static final String EXAMPLE_TASK_ATTACHMENT_ROOT_PROCESS_INSTANCE_ID = "aRootProcInstId"; + + // task count by candidate group + + public static final int EXAMPLE_TASK_COUNT_BY_CANDIDATE_GROUP = 2; + + // form data + public static final String EXAMPLE_FORM_KEY = "aFormKey"; + public static final String EXAMPLE_DEPLOYMENT_ID = "aDeploymentId"; + public static final String EXAMPLE_RE_DEPLOYMENT_ID = "aReDeploymentId"; + public static final String EXAMPLE_FORM_REF_BINDING = "version"; + public static final int EXAMPLE_FORM_REF_VERSION = 3; + + // form property data + public static final String EXAMPLE_FORM_PROPERTY_ID = "aFormPropertyId"; + public static final String EXAMPLE_FORM_PROPERTY_NAME = "aFormName"; + public static final String EXAMPLE_FORM_PROPERTY_TYPE_NAME = "aFormPropertyTypeName"; + public static final String EXAMPLE_FORM_PROPERTY_VALUE = "aValue"; + public static final boolean EXAMPLE_FORM_PROPERTY_READABLE = true; + public static final boolean EXAMPLE_FORM_PROPERTY_WRITABLE = true; + public static final boolean EXAMPLE_FORM_PROPERTY_REQUIRED = true; + + // process instance + public static final String EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY = "aKey"; + public static final String EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY_LIKE = "aKeyLike"; + public static final String EXAMPLE_PROCESS_INSTANCE_ID = "aProcInstId"; + public static final String EXAMPLE_ROOT_PROCESS_INSTANCE_ID = "aRootProcessInstanceId"; + public static final String EXAMPLE_ROOT_HISTORIC_PROCESS_INSTANCE_ID = "aRootProcInstId"; + public static final String ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID = "anotherId"; + public static final boolean EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED = false; + public static final boolean EXAMPLE_PROCESS_INSTANCE_IS_ENDED = false; + public static final String EXAMPLE_PROCESS_INSTANCE_ID_LIST = EXAMPLE_PROCESS_INSTANCE_ID + "," + ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID; + public static final String EXAMPLE_PROCESS_INSTANCE_ID_LIST_WITH_DUP = EXAMPLE_PROCESS_INSTANCE_ID + "," + ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID + "," + EXAMPLE_PROCESS_INSTANCE_ID; + public static final String EXAMPLE_NON_EXISTENT_PROCESS_INSTANCE_ID = "aNonExistentProcInstId"; + public static final String EXAMPLE_PROCESS_INSTANCE_ID_LIST_WITH_NONEXISTENT_ID = EXAMPLE_PROCESS_INSTANCE_ID + "," + EXAMPLE_NON_EXISTENT_PROCESS_INSTANCE_ID; + + // variable instance + public static final String EXAMPLE_VARIABLE_INSTANCE_ID = "aVariableInstanceId"; + + public static final String SERIALIZABLE_VARIABLE_INSTANCE_ID = "serializableVariableInstanceId"; + public static final String SPIN_VARIABLE_INSTANCE_ID = "spinVariableInstanceId"; + + public static final String EXAMPLE_VARIABLE_INSTANCE_NAME = "aVariableInstanceName"; + public static final String EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME = "aDeserializedVariableInstanceName"; + + public static final StringValue EXAMPLE_PRIMITIVE_VARIABLE_VALUE = Variables.stringValue("aVariableInstanceValue"); + public static final String EXAMPLE_VARIABLE_INSTANCE_PROC_DEF_KEY = "aVariableInstanceProcDefKey"; + public static final String EXAMPLE_VARIABLE_INSTANCE_PROC_DEF_ID = "aVariableInstanceProcDefId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_PROC_INST_ID = "aVariableInstanceProcInstId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_EXECUTION_ID = "aVariableInstanceExecutionId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_CASE_INST_ID = "aVariableInstanceCaseInstId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_CASE_EXECUTION_ID = "aVariableInstanceCaseExecutionId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_TASK_ID = "aVariableInstanceTaskId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_BATCH_ID = "aBatchId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_ACTIVITY_INSTANCE_ID = "aVariableInstanceVariableInstanceId"; + public static final String EXAMPLE_VARIABLE_INSTANCE_ERROR_MESSAGE = "aVariableInstanceErrorMessage"; + public static final String EXAMPLE_VARIABLE_INSTANCE_CASE_DEF_KEY = "aVariableInstanceCaseDefKey"; + public static final String EXAMPLE_VARIABLE_INSTANCE_CASE_DEF_ID = "aVariableInstanceCaseDefId"; + public static final String EXAMPLE_HISTORIC_VARIABLE_INSTANCE_CREATE_TIME = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_VARIABLE_INSTANCE_REMOVAL_TIME = withTimezone("2018-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_VARIABLE_INSTANCE_ROOT_PROC_INST_ID = "aRootProcInstId"; + + public static final String EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE = "aSerializedValue"; + public static final byte[] EXAMPLE_VARIABLE_INSTANCE_BYTE = "aSerializedValue".getBytes(); + public static final String EXAMPLE_VARIABLE_INSTANCE_DESERIALIZED_VALUE = "aDeserializedValue"; + + public static final String EXAMPLE_SPIN_DATA_FORMAT = "aDataFormatId"; + public static final String EXAMPLE_SPIN_ROOT_TYPE = "path.to.a.RootType"; + + + // execution + public static final String EXAMPLE_EXECUTION_ID = "anExecutionId"; + public static final boolean EXAMPLE_EXECUTION_IS_ENDED = false; + + // event subscription + public static final String EXAMPLE_EVENT_SUBSCRIPTION_ID = "anEventSubscriptionId"; + public static final String EXAMPLE_EVENT_SUBSCRIPTION_TYPE = "message"; + public static final String EXAMPLE_EVENT_SUBSCRIPTION_NAME = "anEvent"; + public static final String EXAMPLE_EVENT_SUBSCRIPTION_CREATION_DATE = withTimezone("2013-01-23T13:59:43"); + + // process definition + public static final String EXAMPLE_PROCESS_DEFINITION_ID = "aProcDefId"; + public static final String NON_EXISTING_PROCESS_DEFINITION_ID = "aNonExistingProcDefId"; + public static final String EXAMPLE_PROCESS_DEFINITION_NAME = "aName"; + public static final String EXAMPLE_PROCESS_DEFINITION_NAME_LIKE = "aNameLike"; + public static final String EXAMPLE_PROCESS_DEFINITION_KEY = "aKey"; + public static final String ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY="anotherProcessDefinitionKey"; + public static final String EXAMPLE_KEY_LIST = EXAMPLE_PROCESS_DEFINITION_KEY + "," + ANOTHER_EXAMPLE_PROCESS_DEFINITION_KEY; + + public static final String NON_EXISTING_PROCESS_DEFINITION_KEY = "aNonExistingKey"; + public static final String EXAMPLE_PROCESS_DEFINITION_CATEGORY = "aCategory"; + public static final String EXAMPLE_PROCESS_DEFINITION_DESCRIPTION = "aDescription"; + public static final int EXAMPLE_PROCESS_DEFINITION_VERSION = 42; + public static final String EXAMPLE_PROCESS_DEFINITION_VERSION_TAG = "42"; + public static final String EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME = "aResourceName"; + public static final String EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME = "aResourceName.png"; + public static final boolean EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED = true; + public static final boolean EXAMPLE_PROCESS_DEFINITION_IS_STARTABLE = true; + + public static final String ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID = "aProcessDefinitionId:2"; + public static final String EXAMPLE_PROCESS_DEFINTION_ID_LIST = EXAMPLE_PROCESS_DEFINITION_ID + "," + ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID; + + public static final String EXAMPLE_ACTIVITY_ID = "anActivity"; + public static final String ANOTHER_EXAMPLE_ACTIVITY_ID = "anotherActivity"; + public static final String EXAMPLE_ACTIVITY_ID_LIST = EXAMPLE_ACTIVITY_ID + "," + ANOTHER_EXAMPLE_ACTIVITY_ID; + public static final String NON_EXISTING_ACTIVITY_ID = "aNonExistingActivityId"; + public static final String EXAMPLE_ACTIVITY_INSTANCE_ID = "anActivityInstanceId"; + public static final String EXAMPLE_ACTIVITY_NAME = "anActivityName"; + public static final String EXAMPLE_ACTIVITY_TYPE = "anActivityType"; + public static final String EXAMPLE_PROCESS_DEFINITION_DELAYED_EXECUTION = withTimezone("2013-04-23T13:42:43"); + + // deployment + public static final String NON_EXISTING_DEPLOYMENT_ID = "aNonExistingDeploymentId"; + public static final String EXAMPLE_DEPLOYMENT_NAME = "aName"; + public static final String EXAMPLE_DEPLOYMENT_NAME_LIKE = "aNameLike"; + public static final String EXAMPLE_DEPLOYMENT_SOURCE = "aDeploymentSource"; + public static final String EXAMPLE_DEPLOYMENT_TIME = withTimezone("2013-01-23T13:59:43"); + public static final String EXAMPLE_DEPLOYMENT_TIME_BEFORE = withTimezone("2013-01-03T13:59:43"); + public static final String EXAMPLE_DEPLOYMENT_TIME_AFTER = withTimezone("2013-03-23T13:59:43"); + public static final String NON_EXISTING_DEPLOYMENT_TIME = withTimezone("2013-04-23T13:42:43"); + + // deployment resources + public static final String EXAMPLE_DEPLOYMENT_RESOURCE_ID = "aDeploymentResourceId"; + public static final String NON_EXISTING_DEPLOYMENT_RESOURCE_ID = "aNonExistingDeploymentResourceId"; + public static final String EXAMPLE_DEPLOYMENT_RESOURCE_NAME = "aDeploymentResourceName"; + + public static final String EXAMPLE_DEPLOYMENT_SVG_RESOURCE_ID = "aDeploymentSvgResourceId"; + public static final String EXAMPLE_DEPLOYMENT_SVG_RESOURCE_NAME = "a-svg-resource.svg"; + + public static final String EXAMPLE_DEPLOYMENT_PNG_RESOURCE_ID = "aDeploymentPngResourceId"; + public static final String EXAMPLE_DEPLOYMENT_PNG_RESOURCE_NAME = "an-image-resource.png"; + + public static final String EXAMPLE_DEPLOYMENT_JPG_RESOURCE_ID = "aDeploymentJpgResourceId"; + public static final String EXAMPLE_DEPLOYMENT_JPG_RESOURCE_NAME = "an-image-resource.jpg"; + + public static final String EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_ID = "aDeploymentJpegResourceId"; + public static final String EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_NAME = "an-image-resource.jpeg"; + + public static final String EXAMPLE_DEPLOYMENT_JPE_RESOURCE_ID = "aDeploymentJpeResourceId"; + public static final String EXAMPLE_DEPLOYMENT_JPE_RESOURCE_NAME = "an-image-resource.jpe"; + + public static final String EXAMPLE_DEPLOYMENT_GIF_RESOURCE_ID = "aDeploymentGifResourceId"; + public static final String EXAMPLE_DEPLOYMENT_GIF_RESOURCE_NAME = "an-image-resource.gif"; + + public static final String EXAMPLE_DEPLOYMENT_TIF_RESOURCE_ID = "aDeploymentTifResourceId"; + public static final String EXAMPLE_DEPLOYMENT_TIF_RESOURCE_NAME = "an-image-resource.tif"; + + public static final String EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_ID = "aDeploymentTiffResourceId"; + public static final String EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_NAME = "an-image-resource.tiff"; + + public static final String EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_ID = "aDeploymentBpmnResourceId"; + public static final String EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_NAME = "a-bpmn-resource.bpmn"; + + public static final String EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_ID = "aDeploymentBpmnXmlResourceId"; + public static final String EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_NAME = "a-bpmn-resource.bpmn20.xml"; + + public static final String EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_ID = "aDeploymentCmmnResourceId"; + public static final String EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_NAME = "a-cmmn-resource.cmmn"; + + public static final String EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_ID = "aDeploymentCmmnXmlResourceId"; + public static final String EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_NAME = "a-cmmn-resource.cmmn10.xml"; + + public static final String EXAMPLE_DEPLOYMENT_DMN_RESOURCE_ID = "aDeploymentDmnResourceId"; + public static final String EXAMPLE_DEPLOYMENT_DMN_RESOURCE_NAME = "a-dmn-resource.dmn"; + + public static final String EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_ID = "aDeploymentDmnXmlResourceId"; + public static final String EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_NAME = "a-dmn-resource.dmn11.xml"; + + public static final String EXAMPLE_DEPLOYMENT_XML_RESOURCE_ID = "aDeploymentXmlResourceId"; + public static final String EXAMPLE_DEPLOYMENT_XML_RESOURCE_NAME = "a-xml-resource.xml"; + + public static final String EXAMPLE_DEPLOYMENT_JSON_RESOURCE_ID = "aDeploymentJsonResourceId"; + public static final String EXAMPLE_DEPLOYMENT_JSON_RESOURCE_NAME = "a-json-resource.json"; + + public static final String EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_ID = "aDeploymentGroovyResourceId"; + public static final String EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_NAME = "a-groovy-resource.groovy"; + + public static final String EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_ID = "aDeploymentGroovyResourceId"; + public static final String EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_NAME = "a-java-resource.java"; + + public static final String EXAMPLE_DEPLOYMENT_JS_RESOURCE_ID = "aDeploymentJsResourceId"; + public static final String EXAMPLE_DEPLOYMENT_JS_RESOURCE_NAME = "a-js-resource.js"; + + public static final String EXAMPLE_DEPLOYMENT_PHP_RESOURCE_ID = "aDeploymentPhpResourceId"; + public static final String EXAMPLE_DEPLOYMENT_PHP_RESOURCE_NAME = "a-php-resource.php"; + + public static final String EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_ID = "aDeploymentPythonResourceId"; + public static final String EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_NAME = "a-python-resource.py"; + + public static final String EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_ID = "aDeploymentRubyResourceId"; + public static final String EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_NAME = "a-ruby-resource.rb"; + + public static final String EXAMPLE_DEPLOYMENT_HTML_RESOURCE_ID = "aDeploymentHtmlResourceId"; + public static final String EXAMPLE_DEPLOYMENT_HTML_RESOURCE_NAME = "a-html-resource.html"; + + public static final String EXAMPLE_DEPLOYMENT_TXT_RESOURCE_ID = "aDeploymentTxtResourceId"; + public static final String EXAMPLE_DEPLOYMENT_TXT_RESOURCE_NAME = "a-txt-resource.txt"; + + public static final String EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_ID = "aDeploymentCamundaFormResourceId"; + public static final String EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_NAME = "a-camunda-form-resource.form"; + + public static final String EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_ID = "aDeploymentResourceFilenameId"; + public static final String EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_PATH = "my/path/to/my/bpmn/"; + public static final String EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_PATH_BACKSLASH = "my\\path\\to\\my\\bpmn\\"; + public static final String EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_NAME = "process.bpmn"; + + // statistics + public static final int EXAMPLE_FAILED_JOBS = 42; + public static final int EXAMPLE_INSTANCES = 123; + + public static final long EXAMPLE_INSTANCES_LONG = 123; + public static final long EXAMPLE_FINISHED_LONG = 124; + public static final long EXAMPLE_CANCELED_LONG = 125; + public static final long EXAMPLE_COMPLETE_SCOPE_LONG = 126; + public static final long EXAMPLE_OPEN_INCIDENTS_LONG = 0; + public static final long EXAMPLE_RESOLVED_INCIDENTS_LONG = 0; + public static final long EXAMPLE_DELETED_INCIDENTS_LONG = 0; + + public static final long ANOTHER_EXAMPLE_INSTANCES_LONG = 127; + public static final long ANOTHER_EXAMPLE_FINISHED_LONG = 128; + public static final long ANOTHER_EXAMPLE_CANCELED_LONG = 129; + public static final long ANOTHER_EXAMPLE_COMPLETE_SCOPE_LONG = 130; + public static final long ANOTHER_EXAMPLE_OPEN_INCIDENTS_LONG = 1; + public static final long ANOTHER_EXAMPLE_RESOLVED_INCIDENTS_LONG = 2; + public static final long ANOTHER_EXAMPLE_DELETED_INCIDENTS_LONG = 3; + + public static final long EXAMPLE_AVAILABLE_LONG = 123; + public static final long EXAMPLE_ACTIVE_LONG = 124; + public static final long EXAMPLE_COMPLETED_LONG = 125; + public static final long EXAMPLE_DISABLED_LONG = 126; + public static final long EXAMPLE_ENABLED_LONG = 127; + public static final long EXAMPLE_TERMINATED_LONG = 128; + + public static final long ANOTHER_EXAMPLE_AVAILABLE_LONG = 129; + public static final long ANOTHER_EXAMPLE_ACTIVE_LONG = 130; + public static final long ANOTHER_EXAMPLE_COMPLETED_LONG = 131; + public static final long ANOTHER_EXAMPLE_DISABLED_LONG = 132; + public static final long ANOTHER_EXAMPLE_ENABLED_LONG = 133; + public static final long ANOTHER_EXAMPLE_TERMINATED_LONG = 134; + + public static final int ANOTHER_EXAMPLE_FAILED_JOBS = 43; + public static final int ANOTHER_EXAMPLE_INSTANCES = 124; + + public static final String ANOTHER_EXAMPLE_INCIDENT_TYPE = "anotherIncidentType"; + public static final int ANOTHER_EXAMPLE_INCIDENT_COUNT = 2; + + // user & groups + public static final String EXAMPLE_GROUP_ID = "groupId1"; + public static final String EXAMPLE_GROUP_ID2 = "groupId2"; + public static final String EXAMPLE_GROUP_NAME = "group1"; + public static final String EXAMPLE_GROUP_TYPE = "organizational-unit"; + public static final String EXAMPLE_GROUP_NAME_UPDATE = "group1Update"; + + public static final String EXAMPLE_USER_ID = "userId"; + public static final String EXAMPLE_USER_ID2 = "userId2"; + public static final String EXAMPLE_USER_FIRST_NAME = "firstName"; + public static final String EXAMPLE_USER_LAST_NAME = "lastName"; + public static final String EXAMPLE_USER_EMAIL = "test@example.org"; + public static final String EXAMPLE_USER_PASSWORD = "s3cret"; + + public static final String EXAMPLE_USER_FIRST_NAME_UPDATE = "firstNameUpdate"; + public static final String EXAMPLE_USER_LAST_NAME_UPDATE = "lastNameUpdate"; + public static final String EXAMPLE_USER_EMAIL_UPDATE = "testUpdate@example.org"; + + // Job Definitions + public static final String EXAMPLE_JOB_DEFINITION_ID = "aJobDefId"; + public static final String NON_EXISTING_JOB_DEFINITION_ID = "aNonExistingJobDefId"; + public static final String EXAMPLE_JOB_TYPE = "aJobType"; + public static final String EXAMPLE_JOB_CONFIG = "aJobConfig"; + public static final boolean EXAMPLE_JOB_DEFINITION_IS_SUSPENDED = true; + public static final String EXAMPLE_JOB_DEFINITION_DELAYED_EXECUTION = withTimezone("2013-04-23T13:42:43"); + public static final long EXAMPLE_JOB_DEFINITION_PRIORITY = Integer.MAX_VALUE + 52l; + public static final String EXAMPLE_JOB_DEFINITION_DEPLOYMENT_ID = "aDeploymentId"; + + // Jobs + public static final String EXAMPLE_JOB_ACTIVITY_ID = "aJobActivityId"; + public static final String EXAMPLE_JOB_ID = "aJobId"; + public static final String ANOTHER_EXAMPLE_JOB_ID = "anotherJobId"; + public static final String EXAMPLE_JOB_ID_LIST = EXAMPLE_JOB_ID + "," + ANOTHER_EXAMPLE_JOB_ID; + public static final String NON_EXISTING_JOB_ID = "aNonExistingJobId"; + public static final int EXAMPLE_NEGATIVE_JOB_RETRIES = -3; + public static final int EXAMPLE_JOB_RETRIES = 3; + public static final String EXAMPLE_JOB_NO_EXCEPTION_MESSAGE = ""; + public static final String EXAMPLE_EXCEPTION_MESSAGE = "aExceptionMessage"; + public static final String EXAMPLE_JOB_FAILED_ACTIVITY_ID = "aFailedJobActivityId"; + public static final String EXAMPLE_EMPTY_JOB_ID = ""; + public static final String EXAMPLE_DUE_DATE = withTimezone("2013-04-23T13:42:43"); + public static final Boolean EXAMPLE_WITH_RETRIES_LEFT = true; + public static final Boolean EXAMPLE_EXECUTABLE = true; + public static final Boolean EXAMPLE_TIMERS = true; + public static final Boolean EXAMPLE_MESSAGES = true; + public static final Boolean EXAMPLE_WITH_EXCEPTION = true; + public static final Boolean EXAMPLE_NO_RETRIES_LEFT = true; + public static final Boolean EXAMPLE_JOB_IS_SUSPENDED = true; + public static final long EXAMPLE_JOB_PRIORITY = Integer.MAX_VALUE + 42l; + + public static final String EXAMPLE_RESOURCE_TYPE_NAME = "exampleResource"; + public static final int EXAMPLE_RESOURCE_TYPE_ID = 12345678; + public static final String EXAMPLE_RESOURCE_TYPE_ID_STRING = "12345678"; + public static final String EXAMPLE_RESOURCE_ID = "exampleResourceId"; + public static final String EXAMPLE_PERMISSION_NAME = "READ"; + public static final Permission[] EXAMPLE_GRANT_PERMISSION_VALUES = new Permission[] { Permissions.NONE, Permissions.READ, Permissions.UPDATE }; + public static final Permission[] EXAMPLE_REVOKE_PERMISSION_VALUES = new Permission[] { Permissions.ALL, Permissions.READ, Permissions.UPDATE }; + public static final String[] EXAMPLE_PERMISSION_VALUES_STRING = new String[] { "READ", "UPDATE" }; + public static final String EXAMPLE_AUTH_REMOVAL_TIME = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_AUTH_ROOT_PROCESS_INSTANCE_ID = "aRootProcessInstanceId"; + + public static final String EXAMPLE_AUTHORIZATION_ID = "someAuthorizationId"; + public static final int EXAMPLE_AUTHORIZATION_TYPE = 0; + public static final String EXAMPLE_AUTHORIZATION_TYPE_STRING = "0"; + public static final Boolean EXAMPLE_ACQUIRED = true; + + // process applications + public static final String EXAMPLE_PROCESS_APPLICATION_NAME = "aProcessApplication"; + public static final String EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH = "http://camunda.org/someContext"; + + // Historic Process Instance + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON = "aDeleteReason"; + public static final long EXAMPLE_HISTORIC_PROCESS_INSTANCE_DURATION_MILLIS = 2000l; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_TIME = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_END_TIME = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_REMOVAL_TIME = withTimezone("2013-04-26T13:42:43"); + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_USER_ID = "aStartUserId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_ACTIVITY_ID = "aStartActivityId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_ROOT_PROCESS_INSTANCE_ID = "aRootProcessInstanceId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_PROCESS_INSTANCE_ID = "aSuperProcessInstanceId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_CASE_INSTANCE_ID = "aSuperCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUB_PROCESS_INSTANCE_ID = "aSubProcessInstanceId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_CASE_INSTANCE_ID = "aCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUB_CASE_INSTANCE_ID = "aSubCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_STATE = "aState"; + + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE = withTimezone("2013-01-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_AFTER = withTimezone("2013-01-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_BEFORE = withTimezone("2013-04-23T13:42:43"); + + // historic process instance duration report + public static final long EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG = 10; + public static final long EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN = 5; + public static final long EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX = 15; + public static final int EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_PERIOD = 1; + + // Historic Case Instance + public static final long EXAMPLE_HISTORIC_CASE_INSTANCE_DURATION_MILLIS = 2000l; + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_TIME = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSE_TIME = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_USER_ID = "aCreateUserId"; + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_CASE_INSTANCE_ID = "aSuperCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_SUB_CASE_INSTANCE_ID = "aSubCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_PROCESS_INSTANCE_ID = "aSuperProcessInstanceId"; + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_SUB_PROCESS_INSTANCE_ID = "aSuperProcessInstanceId"; + + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_AFTER = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_BEFORE = withTimezone("2013-01-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_AFTER = withTimezone("2013-01-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_BEFORE = withTimezone("2013-04-23T13:42:43"); + + public static final boolean EXAMPLE_HISTORIC_CASE_INSTANCE_IS_ACTIVE = true; + public static final boolean EXAMPLE_HISTORIC_CASE_INSTANCE_IS_COMPLETED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_INSTANCE_IS_TERMINATED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_INSTANCE_IS_CLOSED = true; + + // Historic Activity Instance + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_ID = "aHistoricActivityInstanceId"; + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_PARENT_ACTIVITY_INSTANCE_ID = "aHistoricParentActivityInstanceId"; + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID = "aHistoricCalledProcessInstanceId"; + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID = "aHistoricCalledCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_START_TIME = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_END_TIME = withTimezone("2013-04-23T18:42:43"); + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_REMOVAL_TIME = withTimezone("2013-04-23T13:42:43"); + public static final long EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_DURATION = 2000l; + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_STARTED_AFTER = withTimezone("2013-04-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_STARTED_BEFORE = withTimezone("2013-01-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_FINISHED_AFTER = withTimezone("2013-01-23T13:42:43"); + public static final String EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_FINISHED_BEFORE = withTimezone("2013-04-23T13:42:43"); + public static final boolean EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_CANCELED = true; + public static final boolean EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_COMPLETE_SCOPE = true; + public static final String EXAMPLE_HISTORIC_ACTIVITY_ROOT_PROCESS_INSTANCE_ID = "aRootProcInstId"; + public static final long EXAMPLE_HISTORIC_ACTIVITY_SEQUENCE_COUNTER = 10L; + + // Historic Case Activity Instance + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID = "aCaseActivityInstanceId"; + public static final String EXAMPLE_HISTORIC_ANOTHER_CASE_ACTIVITY_INSTANCE_ID = "anotherCaseActivityInstanceId"; + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_PARENT_CASE_ACTIVITY_INSTANCE_ID = "aParentCaseActivityId"; + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_ID = "aCaseActivityId"; + public static final String EXAMPLE_HISTORIC_ANOTHER_CASE_ACTIVITY_ID = "anotherCaseActivityId"; + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_NAME = "aCaseActivityName"; + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_TYPE = "aCaseActivityType"; + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID = "aCalledProcessInstanceId"; + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID = "aCalledCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATE_TIME = withTimezone("2014-04-23T18:42:42"); + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME = withTimezone("2014-04-23T18:42:43"); + public static final long EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_DURATION = 2000l; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_REQUIRED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_AVAILABLE = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ENABLED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_DISABLED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ACTIVE = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_FAILED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_SUSPENDED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_COMPLETED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_TERMINATED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_UNFINISHED = true; + public static final boolean EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_FINISHED = true; + + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATED_AFTER = withTimezone("2014-04-23T18:41:42"); + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATED_BEFORE = withTimezone("2014-04-23T18:43:42"); + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ENDED_AFTER = withTimezone("2014-04-23T18:41:43"); + public static final String EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ENDED_BEFORE = withTimezone("2014-04-23T18:43:43"); + + // user operation log + public static final String EXAMPLE_USER_OPERATION_LOG_ID = "userOpLogId"; + public static final String EXAMPLE_USER_OPERATION_ID = "opId"; + public static final String EXAMPLE_USER_OPERATION_TYPE = UserOperationLogEntry.OPERATION_TYPE_CLAIM; + public static final String EXAMPLE_USER_OPERATION_ENTITY = EntityTypes.TASK; + public static final String EXAMPLE_USER_OPERATION_PROPERTY = "opProperty"; + public static final String EXAMPLE_USER_OPERATION_ORG_VALUE = "orgValue"; + public static final String EXAMPLE_USER_OPERATION_NEW_VALUE = "newValue"; + public static final String EXAMPLE_USER_OPERATION_TIMESTAMP = withTimezone("2014-02-20T16:53:37"); + public static final String EXAMPLE_USER_OPERATION_ANNOTATION = "anAnnotation"; + + // historic detail + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_ID = "aHistoricVariableUpdateId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_PROC_DEF_KEY = "aProcDefKey"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_PROC_DEF_ID = "aProcDefId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_PROC_INST_ID = "aProcInst"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_ACT_INST_ID = "anActInst"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_EXEC_ID = "anExecutionId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_OPERATION_ID = "anOperationId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_TASK_ID = "aTaskId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_TIME = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_NAME = "aVariableName"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_TYPE_NAME = "String"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_VALUE_TYPE_NAME = "String"; + public static final int EXAMPLE_HISTORIC_VAR_UPDATE_REVISION = 1; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_ERROR = "anErrorMessage"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_VAR_INST_ID = "aVariableInstanceId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_CASE_DEF_KEY = "aCaseDefKey"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_CASE_DEF_ID = "aCaseDefId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_CASE_INST_ID = "aCaseInstId"; + public static final String EXAMPLE_HISTORIC_VAR_UPDATE_CASE_EXEC_ID = "aCaseExecId"; + + public static final String EXAMPLE_HISTORIC_FORM_FIELD_ID = "anId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_KEY = "aProcDefKey"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_ID = "aProcDefId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_PROC_INST_ID = "aProcInst"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_ACT_INST_ID = "anActInst"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_EXEC_ID = "anExecutionId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_OPERATION_ID = "anOperationId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_TASK_ID = "aTaskId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_TIME = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_FORM_FIELD_FIELD_ID = "aFormFieldId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_VALUE = "aFormFieldValue"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_KEY = "aCaseDefKey"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_ID = "aCaseDefId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_CASE_INST_ID = "aCaseInstId"; + public static final String EXAMPLE_HISTORIC_FORM_FIELD_CASE_EXEC_ID = "aCaseExecId"; + public static final String EXAMPLE_HISTORIC_FORM_ROOT_PROCESS_INSTANCE_ID = "aRootProcInstId"; + + // historic task instance + public static final String EXAMPLE_HISTORIC_TASK_INST_ID = "aHistoricTaskInstanceId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_ID = "aProcDefId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_KEY = "aProcDefKey"; + public static final String EXAMPLE_HISTORIC_TASK_INST_PROC_INST_ID = "aProcInstId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_PROC_INST_BUSINESS_KEY = "aBusinessKey"; + public static final String EXAMPLE_HISTORIC_TASK_INST_EXEC_ID = "anExecId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_ACT_INST_ID = "anActInstId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_NAME = "aName"; + public static final String EXAMPLE_HISTORIC_TASK_INST_DESCRIPTION = "aDescription"; + public static final String EXAMPLE_HISTORIC_TASK_INST_DELETE_REASON = "aDeleteReason"; + public static final String EXAMPLE_HISTORIC_TASK_INST_OWNER = "anOwner"; + public static final String EXAMPLE_HISTORIC_TASK_INST_ASSIGNEE = "anAssignee"; + public static final String EXAMPLE_HISTORIC_TASK_INST_START_TIME = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_TASK_INST_END_TIME = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_TASK_INST_REMOVAL_TIME = withTimezone("2018-01-01T00:00:00"); + public static final Long EXAMPLE_HISTORIC_TASK_INST_DURATION = 5000L; + public static final String EXAMPLE_HISTORIC_TASK_INST_DEF_KEY = "aTaskDefinitionKey"; + public static final int EXAMPLE_HISTORIC_TASK_INST_PRIORITY = 60; + public static final String EXAMPLE_HISTORIC_TASK_INST_DUE_DATE = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_TASK_INST_PARENT_TASK_ID = "aParentTaskId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_KEY = "aCaseDefinitionKey"; + public static final String EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_ID = "aCaseDefinitionId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_CASE_INST_ID = "aCaseInstanceId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_CASE_EXEC_ID = "aCaseExecutionId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_TASK_INVOLVED_USER = "aUserId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_TASK_INVOLVED_GROUP = "aGroupId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_TASK_HAD_CANDIDATE_USER = "cUserId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_TASK_HAD_CANDIDATE_GROUP = "cGroupId"; + public static final String EXAMPLE_HISTORIC_TASK_INST_ROOT_PROC_INST_ID = "aRootProcInstId"; + + // Incident + public static final String EXAMPLE_INCIDENT_ID = "anIncidentId"; + public static final String EXAMPLE_INCIDENT_TIMESTAMP = withTimezone("2014-01-02T00:00:00"); + public static final String EXAMPLE_INCIDENT_TIMESTAMP_AFTER = withTimezone("2014-01-03T00:00:00"); + public static final String EXAMPLE_INCIDENT_TIMESTAMP_BEFORE = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_INCIDENT_TYPE = "anIncidentType"; + public static final String EXAMPLE_INCIDENT_EXECUTION_ID = "anExecutionId"; + public static final String EXAMPLE_INCIDENT_ACTIVITY_ID = "anActivityId"; + public static final String EXAMPLE_INCIDENT_FAILED_ACTIVITY_ID = "aFailedActivityId"; + public static final String EXAMPLE_INCIDENT_PROC_INST_ID = "aProcInstId"; + public static final String EXAMPLE_INCIDENT_PROC_DEF_ID = "aProcDefId"; + public static final String EXAMPLE_INCIDENT_CAUSE_INCIDENT_ID = "aCauseIncidentId"; + public static final String EXAMPLE_INCIDENT_ROOT_CAUSE_INCIDENT_ID = "aRootCauseIncidentId"; + public static final String EXAMPLE_INCIDENT_CONFIGURATION = "aConfiguration"; + public static final String EXAMPLE_INCIDENT_MESSAGE = "anIncidentMessage"; + public static final String EXAMPLE_INCIDENT_MESSAGE_LIKE = "%anIncidentMessageLike%"; + public static final int EXAMPLE_INCIDENT_COUNT = 1; + + // Historic Incident + public static final String EXAMPLE_HIST_INCIDENT_ID = "anIncidentId"; + public static final String EXAMPLE_HIST_INCIDENT_CREATE_TIME = withTimezone("2014-01-02T00:00:00"); + public static final String EXAMPLE_HIST_INCIDENT_CREATE_TIME_AFTER = withTimezone("2014-01-03T00:00:00"); + public static final String EXAMPLE_HIST_INCIDENT_CREATE_TIME_BEFORE = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HIST_INCIDENT_END_TIME = withTimezone("2014-01-02T00:00:00"); + public static final String EXAMPLE_HIST_INCIDENT_END_TIME_AFTER = withTimezone("2014-01-03T00:00:00"); + public static final String EXAMPLE_HIST_INCIDENT_END_TIME_BEFORE = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HIST_INCIDENT_REMOVAL_TIME = withTimezone("2018-01-01T00:00:00"); + public static final String EXAMPLE_HIST_INCIDENT_TYPE = "anIncidentType"; + public static final String EXAMPLE_HIST_INCIDENT_EXECUTION_ID = "anExecutionId"; + public static final String EXAMPLE_HIST_INCIDENT_ACTIVITY_ID = "anActivityId"; + public static final String EXAMPLE_HIST_INCIDENT_FAILED_ACTIVITY_ID = "aFailedActivityId"; + public static final String EXAMPLE_HIST_INCIDENT_PROC_INST_ID = "aProcInstId"; + public static final String EXAMPLE_HIST_INCIDENT_PROC_DEF_ID = "aProcDefId"; + public static final String EXAMPLE_HIST_INCIDENT_PROC_DEF_KEY = "aProcDefKey"; + public static final String EXAMPLE_HIST_INCIDENT_ROOT_PROC_INST_ID = "aRootProcInstId"; + public static final String EXAMPLE_HIST_INCIDENT_CAUSE_INCIDENT_ID = "aCauseIncidentId"; + public static final String EXAMPLE_HIST_INCIDENT_ROOT_CAUSE_INCIDENT_ID = "aRootCauseIncidentId"; + public static final String EXAMPLE_HIST_INCIDENT_CONFIGURATION = "aConfiguration"; + public static final String EXAMPLE_HIST_INCIDENT_HISTORY_CONFIGURATION = "aHistoryConfiguration"; + public static final String EXAMPLE_HIST_INCIDENT_MESSAGE = "anIncidentMessage"; + public static final boolean EXAMPLE_HIST_INCIDENT_STATE_OPEN = false; + public static final boolean EXAMPLE_HIST_INCIDENT_STATE_DELETED = false; + public static final boolean EXAMPLE_HIST_INCIDENT_STATE_RESOLVED = true; + + // Historic Identity Link + public static final String EXAMPLE_HIST_IDENTITY_LINK_TYPE = "assignee"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_OPERATION_TYPE = "add"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_TIME = withTimezone("2014-01-05T00:00:00"); + public static final String EXAMPLE_HIST_IDENTITY_LINK_REMOVAL_TIME = withTimezone("2018-01-05T00:00:00"); + public static final String EXAMPLE_HIST_IDENTITY_LINK_DATE_BEFORE = withTimezone("2014-01-01T00:00:00"); + public static final String EXAMPLE_HIST_IDENTITY_LINK_DATE_AFTER = withTimezone("2014-01-06T00:00:00"); + public static final String EXAMPLE_HIST_IDENTITY_LINK_ASSIGNER_ID = "aAssignerId"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_TASK_ID = "aTaskId"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_USER_ID = "aUserId"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_GROUP_ID = "aGroupId"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_ID = "aProcDefId"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_KEY = "aProcDefKey"; + public static final String EXAMPLE_HIST_IDENTITY_LINK_ROOT_PROC_INST_ID = "aRootProcInstId"; + + // case definition + public static final String EXAMPLE_CASE_DEFINITION_ID = "aCaseDefnitionId"; + public static final String ANOTHER_EXAMPLE_CASE_DEFINITION_ID = "anotherCaseDefnitionId"; + public static final String EXAMPLE_CASE_DEFINITION_ID_LIST = EXAMPLE_CASE_DEFINITION_ID + "," + ANOTHER_EXAMPLE_CASE_DEFINITION_ID; + public static final String EXAMPLE_CASE_DEFINITION_KEY = "aCaseDefinitionKey"; + public static final int EXAMPLE_CASE_DEFINITION_VERSION = 1; + public static final String EXAMPLE_CASE_DEFINITION_CATEGORY = "aCaseDefinitionCategory"; + public static final String EXAMPLE_CASE_DEFINITION_NAME = "aCaseDefinitionName"; + public static final String EXAMPLE_CASE_DEFINITION_NAME_LIKE = "aCaseDefinitionNameLike"; + public static final String EXAMPLE_CASE_DEFINITION_RESOURCE_NAME = "aCaseDefinitionResourceName"; + public static final String EXAMPLE_CASE_DEFINITION_DIAGRAM_RESOURCE_NAME = "aResourceName.png"; + + // case instance + public static final String EXAMPLE_CASE_INSTANCE_ID = "aCaseInstId"; + public static final String EXAMPLE_CASE_INSTANCE_BUSINESS_KEY = "aBusinessKey"; + public static final String EXAMPLE_CASE_INSTANCE_BUSINESS_KEY_LIKE = "aBusinessKeyLike"; + public static final String EXAMPLE_CASE_INSTANCE_CASE_DEFINITION_ID = "aCaseDefinitionId"; + public static final boolean EXAMPLE_CASE_INSTANCE_IS_ACTIVE = true; + public static final boolean EXAMPLE_CASE_INSTANCE_IS_COMPLETED = true; + public static final boolean EXAMPLE_CASE_INSTANCE_IS_TERMINATED = true; + + // case execution + public static final String EXAMPLE_CASE_EXECUTION_ID = "aCaseExecutionId"; + public static final String ANOTHER_EXAMPLE_CASE_EXECUTION_ID = "anotherCaseExecutionId"; + public static final String EXAMPLE_CASE_EXECUTION_CASE_INSTANCE_ID = "aCaseInstanceId"; + public static final String EXAMPLE_CASE_EXECUTION_PARENT_ID = "aParentId"; + public static final String EXAMPLE_CASE_EXECUTION_CASE_DEFINITION_ID = "aCaseDefinitionId"; + public static final String EXAMPLE_CASE_EXECUTION_ACTIVITY_ID = "anActivityId"; + public static final String EXAMPLE_CASE_EXECUTION_ACTIVITY_NAME = "anActivityName"; + public static final String EXAMPLE_CASE_EXECUTION_ACTIVITY_TYPE = "anActivityType"; + public static final String EXAMPLE_CASE_EXECUTION_ACTIVITY_DESCRIPTION = "anActivityDescription"; + public static final boolean EXAMPLE_CASE_EXECUTION_IS_REQUIRED = true; + public static final boolean EXAMPLE_CASE_EXECUTION_IS_ENABLED = true; + public static final boolean EXAMPLE_CASE_EXECUTION_IS_ACTIVE = true; + public static final boolean EXAMPLE_CASE_EXECUTION_IS_DISABLED = true; + + // filter + public static final String EXAMPLE_FILTER_ID = "aFilterId"; + public static final String ANOTHER_EXAMPLE_FILTER_ID = "anotherFilterId"; + public static final String EXAMPLE_FILTER_RESOURCE_TYPE = EntityTypes.TASK; + public static final String EXAMPLE_FILTER_NAME = "aFilterName"; + public static final String EXAMPLE_FILTER_OWNER = "aFilterOwner"; + public static final Query EXAMPLE_FILTER_QUERY = new TaskQueryImpl().taskName("test").processVariableValueEquals("foo", "bar").caseInstanceVariableValueEquals("foo", "bar").taskVariableValueEquals("foo", "bar"); + public static final TaskQueryDto EXAMPLE_FILTER_QUERY_DTO = TaskQueryDto.fromQuery(EXAMPLE_FILTER_QUERY); + public static final Map EXAMPLE_FILTER_PROPERTIES = Collections.singletonMap("color", (Object) "#112233"); + + // decision definition + public static final String EXAMPLE_DECISION_DEFINITION_ID_IN = "aDecisionDefinitionId,anotherDecisionDefinitionId"; + public static final String EXAMPLE_DECISION_DEFINITION_ID = "aDecisionDefinitionId"; + public static final String ANOTHER_EXAMPLE_DECISION_DEFINITION_ID = "anotherDecisionDefinitionId"; + public static final String EXAMPLE_DECISION_DEFINITION_ID_LIST = EXAMPLE_DECISION_DEFINITION_ID + "," + ANOTHER_EXAMPLE_DECISION_DEFINITION_ID; + public static final String EXAMPLE_DECISION_DEFINITION_KEY = "aDecisionDefinitionKey"; + public static final String ANOTHER_DECISION_DEFINITION_KEY = "anotherDecisionDefinitionKey"; + public static final String EXAMPLE_DECISION_DEFINITION_KEY_IN = "aDecisionDefinitionKey,anotherDecisionDefinitionKey"; + public static final int EXAMPLE_DECISION_DEFINITION_VERSION = 1; + public static final String EXAMPLE_DECISION_DEFINITION_CATEGORY = "aDecisionDefinitionCategory"; + public static final String EXAMPLE_DECISION_DEFINITION_NAME = "aDecisionDefinitionName"; + public static final String EXAMPLE_DECISION_DEFINITION_NAME_LIKE = "aDecisionDefinitionNameLike"; + public static final String EXAMPLE_DECISION_DEFINITION_RESOURCE_NAME = "aDecisionDefinitionResourceName"; + public static final String EXAMPLE_DECISION_DEFINITION_DIAGRAM_RESOURCE_NAME = "aResourceName.png"; + + public static final String EXAMPLE_DECISION_OUTPUT_KEY = "aDecisionOutput"; + public static final StringValue EXAMPLE_DECISION_OUTPUT_VALUE = Variables.stringValue("aDecisionOutputValue"); + + // decision requirement definition + public static final String EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID = "aDecisionRequirementsDefinitionId"; + public static final String EXAMPLE_DECISION_INSTANCE_ID = "aDecisionInstanceId"; + public static final String ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID = "anotherDecisionRequirementsDefinitionId"; + public static final String EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID_LIST = EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID + "," + ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID; + public static final String EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY = "aDecisionRequirementsDefinitionKey"; + public static final int EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION = 1; + public static final String EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY = "aDecisionRequirementsDefinitionCategory"; + public static final String EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME = "aDecisionRequirementsDefinitionName"; + public static final String EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME = "aDecisionRequirementsDefinitionResourceName"; + public static final String EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_DIAGRAM_RESOURCE_NAME = "aResourceName.png"; + + // historic job log + + public static final String EXAMPLE_HISTORIC_JOB_LOG_ID = "aHistoricJobLogId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_TIMESTAMP = withTimezone(withTimezone("2015-01-01T00:00:00")); + public static final String EXAMPLE_HISTORIC_JOB_LOG_REMOVAL_TIME = withTimezone(withTimezone("2018-01-01T00:00:00")); + + public static final String EXAMPLE_HISTORIC_JOB_LOG_JOB_ID = "aJobId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_JOB_DUE_DATE = withTimezone("2015-10-01T00:00:00"); + public static final int EXAMPLE_HISTORIC_JOB_LOG_JOB_RETRIES = 5; + public static final long EXAMPLE_HISTORIC_JOB_LOG_JOB_PRIORITY = Integer.MAX_VALUE + 42l; + public static final String EXAMPLE_HISTORIC_JOB_LOG_JOB_EXCEPTION_MSG = "aJobExceptionMsg"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_ID = "aJobDefId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_TYPE = "aJobDefType"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_CONFIG = "aJobDefConfig"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_ACTIVITY_ID = "anActId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_FAILED_ACTIVITY_ID = "aFailedActId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_EXECUTION_ID = "anExecId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_PROC_INST_ID = "aProcInstId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_ID = "aProcDefId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_KEY = "aProcDefKey"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_DEPLOYMENT_ID = "aDeploymentId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_ROOT_PROC_INST_ID = "aRootProcInstId"; + public static final String EXAMPLE_HISTORIC_JOB_LOG_HOSTNAME = "aHostname"; + public static final boolean EXAMPLE_HISTORIC_JOB_LOG_IS_CREATION_LOG= true; + public static final boolean EXAMPLE_HISTORIC_JOB_LOG_IS_FAILURE_LOG = true; + public static final boolean EXAMPLE_HISTORIC_JOB_LOG_IS_SUCCESS_LOG = true; + public static final boolean EXAMPLE_HISTORIC_JOB_LOG_IS_DELETION_LOG = true; + + // historic decision instance + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_ID = "aHistoricDecisionInstanceId"; + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_ID_IN = "aHistoricDecisionInstanceId,anotherHistoricDecisionInstanceId"; + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_ID = "aHistoricDecisionInstanceActivityId"; + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_ID_IN = "aHistoricDecisionInstanceActivityId,anotherHistoricDecisionInstanceActivityId"; + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_INSTANCE_ID = "aHistoricDecisionInstanceActivityInstanceId"; + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_INSTANCE_ID_IN = "aHistoricDecisionInstanceActivityInstanceId,anotherHistoricDecisionInstanceActivityInstanceId"; + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATION_TIME = withTimezone("2015-09-07T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_REMOVAL_TIME = withTimezone("2015-09-10T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATED_BEFORE = withTimezone("2015-09-08T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATED_AFTER = withTimezone("2015-09-06T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_INSTANCE_USER_ID = "aUserId"; + public static final Double EXAMPLE_HISTORIC_DECISION_INSTANCE_COLLECT_RESULT_VALUE = 42.0; + public static final String EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_ID = "aDecisionInputInstanceId"; + public static final String EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CLAUSE_ID = "aDecisionInputClauseId"; + public static final String EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CLAUSE_NAME = "aDecisionInputClauseName"; + public static final String EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CREATE_TIME = withTimezone("2015-09-06T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_REMOVAL_TIME = withTimezone("2015-10-18T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_INPUT_ROOT_PROCESS_INSTANCE_ID = "aRootProcInstId"; + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_ID = "aDecisionInputInstanceId"; + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_VARIABLE_NAME = "aDecisionInputInstanceName"; + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CLAUSE_ID = "aDecisionInputClauseId"; + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CLAUSE_NAME = "aDecisionInputClauseName"; + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_RULE_ID = "aDecisionInputRuleId"; + public static final Integer EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_RULE_ORDER = 12; + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CREATE_TIME = withTimezone("2015-09-06T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_REMOVAL_TIME = withTimezone("2015-10-18T11:00:00"); + public static final String EXAMPLE_HISTORIC_DECISION_OUTPUT_ROOT_PROCESS_INSTANCE_ID = "aRootProcInstId"; + public static final ObjectValue EXAMPLE_HISTORIC_DECISION_SERIALIZED_VALUE = MockObjectValue.fromObjectValue(Variables.objectValue("test").serializationDataFormat("aDataFormat").create()).objectTypeName("aTypeName"); + public static final BytesValue EXAMPLE_HISTORIC_DECISION_BYTE_ARRAY_VALUE = Variables.byteArrayValue("test".getBytes()); + public static final StringValue EXAMPLE_HISTORIC_DECISION_STRING_VALUE = Variables.stringValue("test"); + + // metrics + public static final String EXAMPLE_METRICS_START_DATE = withTimezone("2015-01-01T00:00:00"); + public static final String EXAMPLE_METRICS_END_DATE = withTimezone("2015-02-01T00:00:00"); + public static final String EXAMPLE_METRICS_REPORTER = "REPORTER"; + public static final String EXAMPLE_METRICS_NAME = "metricName"; + + // external task + public static final String EXTERNAL_TASK_ID = "anExternalTaskId"; + public static final String EXTERNAL_TASK_ANOTHER_ID = "anotherExternalTaskId"; + public static final String EXTERNAL_TASK_ID_LIST = EXTERNAL_TASK_ID + "," + EXTERNAL_TASK_ANOTHER_ID; + public static final String EXTERNAL_TASK_ERROR_MESSAGE = "some error"; + public static final String EXTERNAL_TASK_LOCK_EXPIRATION_TIME = withTimezone("2015-10-05T13:25:00"); + public static final String EXTERNAL_TASK_CREATE_TIME = withTimezone("2015-10-05T12:25:00"); + public static final Integer EXTERNAL_TASK_RETRIES = 5; + public static final boolean EXTERNAL_TASK_SUSPENDED = true; + public static final String EXTERNAL_TASK_TOPIC_NAME = "aTopic"; + public static final String EXTERNAL_TASK_WORKER_ID = "aWorkerId"; + public static final long EXTERNAL_TASK_PRIORITY = Integer.MAX_VALUE + 466L; + + // batch + public static final String EXAMPLE_BATCH_ID = "aBatchId"; + public static final String EXAMPLE_BATCH_TYPE = "aBatchType"; + public static final int EXAMPLE_BATCH_TOTAL_JOBS = 10; + public static final int EXAMPLE_BATCH_JOBS_CREATED = 9; + public static final int EXAMPLE_BATCH_JOBS_PER_SEED = 11; + public static final int EXAMPLE_INVOCATIONS_PER_BATCH_JOB = 12; + public static final String EXAMPLE_SEED_JOB_DEFINITION_ID = "aSeedJobDefinitionId"; + public static final String EXAMPLE_MONITOR_JOB_DEFINITION_ID = "aMonitorJobDefinitionId"; + public static final String EXAMPLE_BATCH_JOB_DEFINITION_ID = "aBatchJobDefinitionId"; + public static final String EXAMPLE_HISTORIC_BATCH_START_TIME = withTimezone("2016-04-12T15:29:33"); + public static final String EXAMPLE_HISTORIC_BATCH_END_TIME = withTimezone("2016-04-12T16:23:34"); + public static final String EXAMPLE_HISTORIC_BATCH_REMOVAL_TIME = withTimezone("2016-04-12T16:23:34"); + public static final int EXAMPLE_BATCH_REMAINING_JOBS = 21; + public static final int EXAMPLE_BATCH_COMPLETED_JOBS = 22; + public static final int EXAMPLE_BATCH_FAILED_JOBS = 23; + + // tasks + public static final Long EXAMPLE_HISTORIC_TASK_REPORT_COUNT = 12L; + public static final String EXAMPLE_HISTORIC_TASK_REPORT_DEFINITION = "aTaskDefinition"; + public static final String EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEFINITION = "aProcessDefinition"; + public static final String EXAMPLE_HISTORIC_TASK_START_TIME = withTimezone("2016-04-12T15:29:33"); + public static final String EXAMPLE_HISTORIC_TASK_END_TIME = withTimezone("2016-04-12T16:23:34"); + public static final String EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_ID = "aProcessDefinitionId:1:1"; + public static final String EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_NAME = "aProcessDefinitionName"; + public static final String EXAMPLE_HISTORIC_TASK_REPORT_TASK_NAME = "aTaskName"; + + // historic task instance duration report + public static final long EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_AVG = 10; + public static final long EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MIN = 5; + public static final long EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MAX = 15; + public static final int EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_PERIOD = 1; + + // historic external task log + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID = "aHistoricExternalTaskLogId"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TIMESTAMP = withTimezone("2015-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_REMOVAL_TIME = withTimezone("2018-01-01T00:00:00"); + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXTERNAL_TASK_ID = "anExternalTaskId"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TOPIC_NAME = "aTopicName"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_WORKER_ID = "aWorkerId"; + public static final int EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_RETRIES = 5; + public static final long EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PRIORITY = Integer.MAX_VALUE + 42l; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ERROR_MSG = "aEXTERNAL_TASKExceptionMsg"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_ID = "anActId"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_INSTANCE_ID = "anActInstanceId"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXECUTION_ID = "anExecId"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_INST_ID = "aProcInstId"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_ID = "aProcDefId"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_KEY = "aProcDefKey"; + public static final String EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ROOT_PROC_INST_ID = "aRootProcInstId"; + public static final boolean EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_CREATION_LOG= true; + public static final boolean EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_FAILURE_LOG = true; + public static final boolean EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_SUCCESS_LOG = true; + public static final boolean EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_DELETION_LOG = true; + public static final String EXAMPLE_JOB_CREATE_TIME = withTimezone("2015-01-01T00:00:00"); + + // problems + public static final int EXAMPLE_PROBLEM_LINE = 77; + public static final int EXAMPLE_PROBLEM_COLUMN = 78; + public static final String EXAMPLE_PROBLEM_ELEMENT_ID = "element_79"; + public static final int EXAMPLE_PROBLEM_LINE_2 = 87; + public static final int EXAMPLE_PROBLEM_COLUMN_2 = 88; + public static final String EXAMPLE_PROBLEM_ELEMENT_ID_2 = "element_89"; + public static final String EXAMPLE_RESOURCE_NAME = "abc"; + public static final List EXAMPLE_ELEMENT_IDS = Arrays.asList(EXAMPLE_PROBLEM_ELEMENT_ID, EXAMPLE_PROBLEM_ELEMENT_ID_2); + + // Telemetry + public static final String EXAMPLE_TELEMETRY_INSTALLATION_ID = "8343cc7a-8ad1-42d4-97d2-43452c0bdfa3"; + public static final String EXAMPLE_TELEMETRY_PRODUCT_NAME = "Camunda BPM Runtime"; + public static final String EXAMPLE_TELEMETRY_PRODUCT_VERSION = "7.14.0"; + public static final String EXAMPLE_TELEMETRY_PRODUCT_EDITION = "enterprise"; + public static final String EXAMPLE_TELEMETRY_DB_VENDOR = "h2"; + public static final String EXAMPLE_TELEMETRY_DB_VERSION = "1.4.190 (2015-10-11)"; + public static final String EXAMPLE_TELEMETRY_APP_SERVER_VENDOR = "Wildfly"; + public static final String EXAMPLE_TELEMETRY_APP_SERVER_VERSION = "WildFly Full 19.0.0.Final (WildFly Core 11.0.0.Final) - 2.0.30.Final"; + public static final String EXAMPLE_TELEMETRY_TELEMETRY_CONFIGURE_CMD = "TelemetryConfigureCmd"; + public static final String EXAMPLE_TELEMETRY_IS_TELEMETRY_ENABLED_CMD = "IsTelemetryEnabledCmd"; + public static final String EXAMPLE_TELEMETRY_GET_TELEMETRY_DATA_CMD = "GetTelemetryDataCmd"; + public static final String EXAMPLE_TELEMETRY_LICENSE_CUSTOMER_NAME = "customer name"; + public static final String EXAMPLE_TELEMETRY_LICENSE_TYPE = "UNIFIED"; + public static final String EXAMPLE_TELEMETRY_LICENSE_VALID_UNTIL = "2022-09-30"; + public static final boolean EXAMPLE_TELEMETRY_LICENSE_UNLIMITED = false; + public static final Map EXAMPLE_TELEMETRY_LICENSE_FEATURES = Collections.singletonMap("camundaBPM", "true"); + public static final String EXAMPLE_TELEMETRY_LICENSE_RAW = "customer=customer name;expiryDate=2022-09-30;camundaBPM=true;optimize=false;cawemo=false"; + public static final String EXAMPLE_TELEMETRY_JDK_VERSION = "14.0.2"; + public static final String EXAMPLE_TELEMETRY_JDK_VENDOR = "Oracle Corporation"; + public static final String EXAMPLE_TELEMETRY_DATA_COLLECTION_START_DATE = withTimezone("2022-01-01T00:00:00"); + + public static final DatabaseImpl EXAMPLE_TELEMETRY_DATABASE = new DatabaseImpl(EXAMPLE_TELEMETRY_DB_VENDOR, + EXAMPLE_TELEMETRY_DB_VERSION); + public static final ApplicationServerImpl EXAMPLE_TELEMETRY_SERVER = new ApplicationServerImpl( + EXAMPLE_TELEMETRY_APP_SERVER_VENDOR, EXAMPLE_TELEMETRY_APP_SERVER_VERSION); + public static final LicenseKeyDataImpl EXAMPLE_TELEMETRY_LICENSE = new LicenseKeyDataImpl( + EXAMPLE_TELEMETRY_LICENSE_CUSTOMER_NAME, EXAMPLE_TELEMETRY_LICENSE_TYPE, EXAMPLE_TELEMETRY_LICENSE_VALID_UNTIL, + EXAMPLE_TELEMETRY_LICENSE_UNLIMITED, EXAMPLE_TELEMETRY_LICENSE_FEATURES, EXAMPLE_TELEMETRY_LICENSE_RAW); + public static final JdkImpl EXAMPLE_TELEMETRY_JDK = new JdkImpl(EXAMPLE_TELEMETRY_JDK_VERSION, EXAMPLE_TELEMETRY_JDK_VENDOR); + public static final InternalsImpl EXAMPLE_TELEMETRY_INTERNALS = new InternalsImpl(EXAMPLE_TELEMETRY_DATABASE, + EXAMPLE_TELEMETRY_SERVER, EXAMPLE_TELEMETRY_LICENSE, EXAMPLE_TELEMETRY_JDK); + static { + EXAMPLE_TELEMETRY_INTERNALS.setCamundaIntegration( + Stream.of("spring-boot-starter", "camunda-bpm-run").collect(Collectors.toCollection(HashSet::new))); + EXAMPLE_TELEMETRY_INTERNALS + .setWebapps(Stream.of("cockpit", "admin").collect(Collectors.toCollection(HashSet::new))); + EXAMPLE_TELEMETRY_INTERNALS + .setCommands(Stream.of(new Object[][] { { "StartProcessInstanceCmd", 40 }, { "FetchExternalTasksCmd", 100 } }) + .collect(Collectors.toMap(data -> (String) data[0], data -> new CommandImpl((Integer) data[1])))); + EXAMPLE_TELEMETRY_INTERNALS.setMetrics(Stream + .of(new Object[][] { { "process-instances", 936L }, { "flow-node-instances", 6125L }, + { "decision-instances", 140L }, { "executed-decision-elements", 732L } }) + .collect(Collectors.toMap(data -> (String) data[0], data -> new MetricImpl((Long) data[1])))); + EXAMPLE_TELEMETRY_INTERNALS.setCamundaIntegration(Collections.singleton("spring-boot")); + EXAMPLE_TELEMETRY_INTERNALS.setWebapps(Collections.singleton("cockpit")); + EXAMPLE_TELEMETRY_INTERNALS.setDataCollectionStartDate(DateTimeUtil.parseDate(EXAMPLE_TELEMETRY_DATA_COLLECTION_START_DATE)); + } + public static final ProductImpl EXAMPLE_TELEMETRY_PRODUCT = new ProductImpl(EXAMPLE_TELEMETRY_PRODUCT_NAME, + EXAMPLE_TELEMETRY_PRODUCT_VERSION, EXAMPLE_TELEMETRY_PRODUCT_EDITION, EXAMPLE_TELEMETRY_INTERNALS); + public static final TelemetryDataImpl EXAMPLE_TELEMETRY_DATA = new TelemetryDataImpl(EXAMPLE_TELEMETRY_INSTALLATION_ID, EXAMPLE_TELEMETRY_PRODUCT); + + public static Task createMockTask() { + return mockTask().build(); + } + + public static MockTaskBuilder mockTask() { + return new MockTaskBuilder() + .id(EXAMPLE_TASK_ID).name(EXAMPLE_TASK_NAME) + .assignee(EXAMPLE_TASK_ASSIGNEE_NAME) + .createTime(DateTimeUtil.parseDate(EXAMPLE_TASK_CREATE_TIME)) + .lastUpdated(DateTimeUtil.parseDate(EXAMPLE_TASK_LAST_UPDATED)) + .dueDate(DateTimeUtil.parseDate(EXAMPLE_TASK_DUE_DATE)) + .followUpDate(DateTimeUtil.parseDate(EXAMPLE_FOLLOW_UP_DATE)) + .delegationState(EXAMPLE_TASK_DELEGATION_STATE).description(EXAMPLE_TASK_DESCRIPTION) + .executionId(EXAMPLE_TASK_EXECUTION_ID).owner(EXAMPLE_TASK_OWNER) + .parentTaskId(EXAMPLE_TASK_PARENT_TASK_ID) + .priority(EXAMPLE_TASK_PRIORITY) + .processDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .processInstanceId(EXAMPLE_PROCESS_INSTANCE_ID) + .taskDefinitionKey(EXAMPLE_TASK_DEFINITION_KEY) + .caseDefinitionId(EXAMPLE_CASE_DEFINITION_ID) + .caseInstanceId(EXAMPLE_CASE_INSTANCE_ID) + .caseExecutionId(EXAMPLE_CASE_EXECUTION_ID) + .formKey(EXAMPLE_FORM_KEY) + .camundaFormRef(EXAMPLE_FORM_KEY, EXAMPLE_FORM_REF_BINDING, EXAMPLE_FORM_REF_VERSION) + .tenantId(EXAMPLE_TENANT_ID) + .taskState(EXAMPLE_HISTORIC_TASK_STATE) + .hasAttachment(EXAMPLE_TASK_ATTACHMENT_STATE) + .hasComment(EXAMPLE_TASK_COMMENT_STATE); + } + + public static List createMockTasks() { + List mocks = new ArrayList<>(); + mocks.add(createMockTask()); + return mocks; + } + + public static TaskFormData createMockTaskFormData() { + FormProperty mockFormProperty = mock(FormProperty.class); + when(mockFormProperty.getId()).thenReturn(EXAMPLE_FORM_PROPERTY_ID); + when(mockFormProperty.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_NAME); + when(mockFormProperty.getValue()).thenReturn(EXAMPLE_FORM_PROPERTY_VALUE); + when(mockFormProperty.isReadable()).thenReturn(EXAMPLE_FORM_PROPERTY_READABLE); + when(mockFormProperty.isWritable()).thenReturn(EXAMPLE_FORM_PROPERTY_WRITABLE); + when(mockFormProperty.isRequired()).thenReturn(EXAMPLE_FORM_PROPERTY_REQUIRED); + + FormType mockFormType = mock(FormType.class); + when(mockFormType.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_TYPE_NAME); + when(mockFormProperty.getType()).thenReturn(mockFormType); + + TaskFormData mockFormData = mock(TaskFormData.class); + when(mockFormData.getFormKey()).thenReturn(EXAMPLE_FORM_KEY); + when(mockFormData.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + + List mockFormProperties = new ArrayList<>(); + mockFormProperties.add(mockFormProperty); + when(mockFormData.getFormProperties()).thenReturn(mockFormProperties); + return mockFormData; + } + + public static TaskFormData createMockTaskFormDataUsingFormFieldsWithoutFormKey() { + FormField mockFormField = mock(FormField.class); + when(mockFormField.getId()).thenReturn(EXAMPLE_FORM_PROPERTY_ID); + when(mockFormField.getLabel()).thenReturn(EXAMPLE_FORM_PROPERTY_NAME); + when(mockFormField.getDefaultValue()).thenReturn(EXAMPLE_FORM_PROPERTY_VALUE); + + FormType mockFormType = mock(FormType.class); + when(mockFormType.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_TYPE_NAME); + when(mockFormField.getType()).thenReturn(mockFormType); + + TaskFormData mockFormData = mock(TaskFormData.class); + when(mockFormData.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + + List mockFormFields = new ArrayList<>(); + mockFormFields.add(mockFormField); + when(mockFormData.getFormFields()).thenReturn(mockFormFields); + return mockFormData; + } + + public static TaskFormData createMockTaskFormDataUsingFormRef() { + FormType mockFormType = mock(FormType.class); + when(mockFormType.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_TYPE_NAME); + + TaskFormData mockFormData = mock(TaskFormData.class); + when(mockFormData.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + + CamundaFormRefImpl formRef = new CamundaFormRefImpl(EXAMPLE_FORM_KEY, EXAMPLE_FORM_REF_BINDING); + formRef.setVersion(EXAMPLE_FORM_REF_VERSION); + when(mockFormData.getCamundaFormRef()).thenReturn(formRef); + + return mockFormData; + } + + // task comment + public static Comment createMockTaskComment() { + Comment mockComment = mock(Comment.class); + when(mockComment.getId()).thenReturn(EXAMPLE_TASK_COMMENT_ID); + when(mockComment.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(mockComment.getUserId()).thenReturn(EXAMPLE_USER_ID); + when(mockComment.getTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_TASK_COMMENT_TIME)); + when(mockComment.getFullMessage()).thenReturn(EXAMPLE_TASK_COMMENT_FULL_MESSAGE); + when(mockComment.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_TASK_COMMENT_TIME)); + when(mockComment.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mockComment.getRootProcessInstanceId()).thenReturn(EXAMPLE_TASK_COMMENT_ROOT_PROCESS_INSTANCE_ID); + return mockComment; + } + + public static List createMockTaskComments() { + List mocks = new ArrayList<>(); + mocks.add(createMockTaskComment()); + return mocks; + } + + // task attachment + public static Attachment createMockTaskAttachment() { + Attachment mockAttachment = mock(Attachment.class); + when(mockAttachment.getId()).thenReturn(EXAMPLE_TASK_ATTACHMENT_ID); + when(mockAttachment.getName()).thenReturn(EXAMPLE_TASK_ATTACHMENT_NAME); + when(mockAttachment.getDescription()).thenReturn(EXAMPLE_TASK_ATTACHMENT_DESCRIPTION); + when(mockAttachment.getType()).thenReturn(EXAMPLE_TASK_ATTACHMENT_TYPE); + when(mockAttachment.getUrl()).thenReturn(EXAMPLE_TASK_ATTACHMENT_URL); + when(mockAttachment.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(mockAttachment.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mockAttachment.getCreateTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_TASK_ATTACHMENT_CREATE_DATE)); + when(mockAttachment.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_TASK_ATTACHMENT_REMOVAL_DATE)); + when(mockAttachment.getRootProcessInstanceId()).thenReturn(EXAMPLE_TASK_ATTACHMENT_ROOT_PROCESS_INSTANCE_ID); + + return mockAttachment; + } + + public static List createMockTaskAttachments() { + List mocks = new ArrayList<>(); + mocks.add(createMockTaskAttachment()); + return mocks; + } + + public static List createMockTaskCountByCandidateGroupReport() { + TaskCountByCandidateGroupResult mock = mock(TaskCountByCandidateGroupResult.class); + when(mock.getGroupName()).thenReturn(EXAMPLE_GROUP_ID); + when(mock.getTaskCount()).thenReturn(EXAMPLE_TASK_COUNT_BY_CANDIDATE_GROUP); + + List mockList = new ArrayList<>(); + mockList.add(mock); + return mockList; + } + + public static List createMockHistoricTaskInstanceReport() { + HistoricTaskInstanceReportResult mock = mock(HistoricTaskInstanceReportResult.class); + when(mock.getCount()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_COUNT); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_ID); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEFINITION); + when(mock.getProcessDefinitionName()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_NAME); + when(mock.getTenantId()).thenReturn(EXAMPLE_TENANT_ID); + when(mock.getTaskName()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_TASK_NAME); + + return Collections.singletonList(mock); + } + + public static List createMockHistoricTaskInstanceReportWithProcDef() { + HistoricTaskInstanceReportResult mock = mock(HistoricTaskInstanceReportResult.class); + when(mock.getCount()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_COUNT); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_ID); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEFINITION); + when(mock.getProcessDefinitionName()).thenReturn(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_NAME); + when(mock.getTenantId()).thenReturn(EXAMPLE_TENANT_ID); + when(mock.getTaskName()).thenReturn(null); + + return Collections.singletonList(mock); + } + + public static List createMockHistoricTaskInstanceDurationReport(PeriodUnit periodUnit) { + DurationReportResult mock = mock(DurationReportResult.class); + when(mock.getAverage()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_AVG); + when(mock.getMinimum()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MIN); + when(mock.getMaximum()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MAX); + when(mock.getPeriod()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_PERIOD); + when(mock.getPeriodUnit()).thenReturn(periodUnit); + + List mockList = new ArrayList<>(); + mockList.add(mock); + return mockList; + } + + + // form data + public static StartFormData createMockStartFormData(ProcessDefinition definition) { + FormProperty mockFormProperty = mock(FormProperty.class); + when(mockFormProperty.getId()).thenReturn(EXAMPLE_FORM_PROPERTY_ID); + when(mockFormProperty.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_NAME); + when(mockFormProperty.getValue()).thenReturn(EXAMPLE_FORM_PROPERTY_VALUE); + when(mockFormProperty.isReadable()).thenReturn(EXAMPLE_FORM_PROPERTY_READABLE); + when(mockFormProperty.isWritable()).thenReturn(EXAMPLE_FORM_PROPERTY_WRITABLE); + when(mockFormProperty.isRequired()).thenReturn(EXAMPLE_FORM_PROPERTY_REQUIRED); + + FormType mockFormType = mock(FormType.class); + when(mockFormType.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_TYPE_NAME); + when(mockFormProperty.getType()).thenReturn(mockFormType); + + StartFormData mockFormData = mock(StartFormData.class); + when(mockFormData.getFormKey()).thenReturn(EXAMPLE_FORM_KEY); + when(mockFormData.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + when(mockFormData.getProcessDefinition()).thenReturn(definition); + + List mockFormProperties = new ArrayList<>(); + mockFormProperties.add(mockFormProperty); + when(mockFormData.getFormProperties()).thenReturn(mockFormProperties); + return mockFormData; + } + + public static StartFormData createMockStartFormDataUsingFormFieldsWithoutFormKey(ProcessDefinition definition) { + FormField mockFormField = mock(FormField.class); + when(mockFormField.getId()).thenReturn(EXAMPLE_FORM_PROPERTY_ID); + when(mockFormField.getLabel()).thenReturn(EXAMPLE_FORM_PROPERTY_NAME); + when(mockFormField.getDefaultValue()).thenReturn(EXAMPLE_FORM_PROPERTY_VALUE); + + FormType mockFormType = mock(FormType.class); + when(mockFormType.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_TYPE_NAME); + when(mockFormField.getType()).thenReturn(mockFormType); + + StartFormData mockFormData = mock(StartFormData.class); + when(mockFormData.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + when(mockFormData.getProcessDefinition()).thenReturn(definition); + + List mockFormFields = new ArrayList<>(); + mockFormFields.add(mockFormField); + when(mockFormData.getFormFields()).thenReturn(mockFormFields); + + return mockFormData; + } + + public static StartFormData createMockStartFormDataUsingFormRef() { + FormType mockFormType = mock(FormType.class); + when(mockFormType.getName()).thenReturn(EXAMPLE_FORM_PROPERTY_TYPE_NAME); + + StartFormData mockFormData = mock(StartFormData.class); + when(mockFormData.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + + CamundaFormRefImpl formRef = new CamundaFormRefImpl(EXAMPLE_FORM_KEY, EXAMPLE_FORM_REF_BINDING); + formRef.setVersion(EXAMPLE_FORM_REF_VERSION); + when(mockFormData.getCamundaFormRef()).thenReturn(formRef); + + return mockFormData; + } + + public static ProcessInstanceWithVariables createMockInstanceWithVariables() { + return createMockInstanceWithVariables(EXAMPLE_TENANT_ID); + } + + public static ProcessInstanceWithVariables createMockInstanceWithVariables(String tenantId) { + ProcessInstanceWithVariables mock = mock(ProcessInstanceWithVariables.class); + + when(mock.getId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getBusinessKey()).thenReturn(EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + when(mock.getCaseInstanceId()).thenReturn(EXAMPLE_CASE_INSTANCE_ID); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.isSuspended()).thenReturn(EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED); + when(mock.isEnded()).thenReturn(EXAMPLE_PROCESS_INSTANCE_IS_ENDED); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.getVariables()).thenReturn(createMockSerializedVariables()); + return mock; + } + + + public static ProcessInstance createMockInstance() { + return createMockInstance(EXAMPLE_TENANT_ID); + } + + public static ProcessInstance createMockInstance(String tenantId) { + ProcessInstance mock = mock(ProcessInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getBusinessKey()).thenReturn(EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + when(mock.getCaseInstanceId()).thenReturn(EXAMPLE_CASE_INSTANCE_ID); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.isSuspended()).thenReturn(EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED); + when(mock.isEnded()).thenReturn(EXAMPLE_PROCESS_INSTANCE_IS_ENDED); + when(mock.getTenantId()).thenReturn(tenantId); + + return mock; + } + + public static VariableInstance createMockVariableInstance() { + return mockVariableInstance().build(); + } + + public static MockVariableInstanceBuilder mockVariableInstance() { + return new MockVariableInstanceBuilder() + .id(EXAMPLE_VARIABLE_INSTANCE_ID) + .name(EXAMPLE_VARIABLE_INSTANCE_NAME) + .typedValue(EXAMPLE_PRIMITIVE_VARIABLE_VALUE) + .processInstanceId(EXAMPLE_VARIABLE_INSTANCE_PROC_INST_ID) + .executionId(EXAMPLE_VARIABLE_INSTANCE_EXECUTION_ID) + .caseInstanceId(EXAMPLE_VARIABLE_INSTANCE_CASE_INST_ID) + .caseExecutionId(EXAMPLE_VARIABLE_INSTANCE_CASE_EXECUTION_ID) + .taskId(EXAMPLE_VARIABLE_INSTANCE_TASK_ID) + .activityInstanceId(EXAMPLE_VARIABLE_INSTANCE_ACTIVITY_INSTANCE_ID) + .tenantId(EXAMPLE_TENANT_ID) + .batchId(EXAMPLE_VARIABLE_INSTANCE_BATCH_ID) + .errorMessage(null); + } + + public static VariableInstance createMockVariableInstance(TypedValue value) { + return mockVariableInstance().typedValue(value).build(); + } + + public static VariableMap createMockSerializedVariables() { + VariableMap variables = Variables.createVariables(); + ObjectValue serializedVar = Variables.serializedObjectValue(EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE) + .serializationDataFormat(FORMAT_APPLICATION_JSON) + .objectTypeName(ArrayList.class.getName()) + .create(); + + ObjectValue deserializedVar = new ObjectValueImpl(EXAMPLE_VARIABLE_INSTANCE_DESERIALIZED_VALUE, + EXAMPLE_VARIABLE_INSTANCE_SERIALIZED_VALUE, + FORMAT_APPLICATION_JSON, Object.class.getName(), true); + variables.putValueTyped(EXAMPLE_VARIABLE_INSTANCE_NAME, serializedVar); + variables.putValueTyped(EXAMPLE_DESERIALIZED_VARIABLE_INSTANCE_NAME, deserializedVar); + return variables; + } + + public static Execution createMockExecution() { + return createMockExecution(EXAMPLE_TENANT_ID); + } + + public static Execution createMockExecution(String tenantId) { + Execution mock = mock(Execution.class); + + when(mock.getId()).thenReturn(EXAMPLE_EXECUTION_ID); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.isEnded()).thenReturn(EXAMPLE_EXECUTION_IS_ENDED); + when(mock.getTenantId()).thenReturn(tenantId); + + return mock; + } + + public static EventSubscription createMockEventSubscription() { + return createMockEventSubscription(EXAMPLE_TENANT_ID); + } + + public static EventSubscription createMockEventSubscription(String tenantId) { + EventSubscription mock = mock(EventSubscription.class); + + when(mock.getId()).thenReturn(EXAMPLE_EVENT_SUBSCRIPTION_ID); + when(mock.getEventType()).thenReturn(EXAMPLE_EVENT_SUBSCRIPTION_TYPE); + when(mock.getEventName()).thenReturn(EXAMPLE_EVENT_SUBSCRIPTION_NAME); + when(mock.getExecutionId()).thenReturn(EXAMPLE_EXECUTION_ID); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(mock.getCreated()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_EVENT_SUBSCRIPTION_CREATION_DATE)); + when(mock.getTenantId()).thenReturn(tenantId); + + return mock; + } + + // statistics + public static List createMockProcessDefinitionStatistics() { + ProcessDefinitionStatistics statistics = mock(ProcessDefinitionStatistics.class); + when(statistics.getFailedJobs()).thenReturn(EXAMPLE_FAILED_JOBS); + when(statistics.getInstances()).thenReturn(EXAMPLE_INSTANCES); + when(statistics.getId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(statistics.getName()).thenReturn(EXAMPLE_PROCESS_DEFINITION_NAME); + when(statistics.getKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(statistics.getTenantId()).thenReturn(EXAMPLE_TENANT_ID); + when(statistics.getVersionTag()).thenReturn(EXAMPLE_VERSION_TAG); + when(statistics.getCategory()).thenReturn(EXAMPLE_PROCESS_DEFINITION_CATEGORY); + when(statistics.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + when(statistics.getDiagramResourceName()).thenReturn(EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME); + when(statistics.getResourceName()).thenReturn(EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME); + when(statistics.getVersion()).thenReturn(EXAMPLE_PROCESS_DEFINITION_VERSION); + when(statistics.getDescription()).thenReturn(EXAMPLE_PROCESS_DEFINITION_DESCRIPTION); + + IncidentStatistics incidentStaticits = mock(IncidentStatistics.class); + when(incidentStaticits.getIncidentType()).thenReturn(EXAMPLE_INCIDENT_TYPE); + when(incidentStaticits.getIncidentCount()).thenReturn(EXAMPLE_INCIDENT_COUNT); + + List exampleIncidentList = new ArrayList<>(); + exampleIncidentList.add(incidentStaticits); + when(statistics.getIncidentStatistics()).thenReturn(exampleIncidentList); + + ProcessDefinitionStatistics anotherStatistics = mock(ProcessDefinitionStatistics.class); + when(anotherStatistics.getFailedJobs()).thenReturn(ANOTHER_EXAMPLE_FAILED_JOBS); + when(anotherStatistics.getInstances()).thenReturn(ANOTHER_EXAMPLE_INSTANCES); + when(anotherStatistics.getId()).thenReturn(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + when(anotherStatistics.getName()).thenReturn(EXAMPLE_PROCESS_DEFINITION_NAME); + when(anotherStatistics.getKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(anotherStatistics.getTenantId()).thenReturn(ANOTHER_EXAMPLE_TENANT_ID); + when(anotherStatistics.getVersionTag()).thenReturn(ANOTHER_EXAMPLE_VERSION_TAG); + + IncidentStatistics anotherIncidentStaticits = mock(IncidentStatistics.class); + when(anotherIncidentStaticits.getIncidentType()).thenReturn(ANOTHER_EXAMPLE_INCIDENT_TYPE); + when(anotherIncidentStaticits.getIncidentCount()).thenReturn(ANOTHER_EXAMPLE_INCIDENT_COUNT); + + List anotherExampleIncidentList = new ArrayList<>(); + anotherExampleIncidentList.add(anotherIncidentStaticits); + when(anotherStatistics.getIncidentStatistics()).thenReturn(anotherExampleIncidentList); + + List processDefinitionResults = new ArrayList<>(); + processDefinitionResults.add(statistics); + processDefinitionResults.add(anotherStatistics); + + return processDefinitionResults; + } + + public static List createMockActivityStatistics() { + ActivityStatistics statistics = mock(ActivityStatistics.class); + when(statistics.getFailedJobs()).thenReturn(EXAMPLE_FAILED_JOBS); + when(statistics.getInstances()).thenReturn(EXAMPLE_INSTANCES); + when(statistics.getId()).thenReturn(EXAMPLE_ACTIVITY_ID); + + IncidentStatistics incidentStaticits = mock(IncidentStatistics.class); + when(incidentStaticits.getIncidentType()).thenReturn(EXAMPLE_INCIDENT_TYPE); + when(incidentStaticits.getIncidentCount()).thenReturn(EXAMPLE_INCIDENT_COUNT); + + List exampleIncidentList = new ArrayList<>(); + exampleIncidentList.add(incidentStaticits); + when(statistics.getIncidentStatistics()).thenReturn(exampleIncidentList); + + ActivityStatistics anotherStatistics = mock(ActivityStatistics.class); + when(anotherStatistics.getFailedJobs()).thenReturn(ANOTHER_EXAMPLE_FAILED_JOBS); + when(anotherStatistics.getInstances()).thenReturn(ANOTHER_EXAMPLE_INSTANCES); + when(anotherStatistics.getId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + + IncidentStatistics anotherIncidentStaticits = mock(IncidentStatistics.class); + when(anotherIncidentStaticits.getIncidentType()).thenReturn(ANOTHER_EXAMPLE_INCIDENT_TYPE); + when(anotherIncidentStaticits.getIncidentCount()).thenReturn(ANOTHER_EXAMPLE_INCIDENT_COUNT); + + List anotherExampleIncidentList = new ArrayList<>(); + anotherExampleIncidentList.add(anotherIncidentStaticits); + when(anotherStatistics.getIncidentStatistics()).thenReturn(anotherExampleIncidentList); + + List activityResults = new ArrayList<>(); + activityResults.add(statistics); + activityResults.add(anotherStatistics); + + return activityResults; + } + + // process definition + public static List createMockDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockDefinition()); + return mocks; + } + + public static List createMockTwoDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockDefinition()); + mocks.add(createMockAnotherDefinition()); + return mocks; + } + + public static MockDefinitionBuilder mockDefinition() { + return new MockDefinitionBuilder().id(EXAMPLE_PROCESS_DEFINITION_ID).category(EXAMPLE_PROCESS_DEFINITION_CATEGORY) + .name(EXAMPLE_PROCESS_DEFINITION_NAME).key(EXAMPLE_PROCESS_DEFINITION_KEY).description(EXAMPLE_PROCESS_DEFINITION_DESCRIPTION) + .versionTag(EXAMPLE_VERSION_TAG).version(EXAMPLE_PROCESS_DEFINITION_VERSION).resource(EXAMPLE_PROCESS_DEFINITION_RESOURCE_NAME).deploymentId(EXAMPLE_DEPLOYMENT_ID) + .diagram(EXAMPLE_PROCESS_DEFINITION_DIAGRAM_RESOURCE_NAME).suspended(EXAMPLE_PROCESS_DEFINITION_IS_SUSPENDED); + } + + public static ProcessDefinition createMockDefinition() { + return mockDefinition().build(); + } + + public static ProcessDefinition createMockAnotherDefinition() { + return mockDefinition().id(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID).build(); + } + + // deployments + public static List createMockDeployments() { + List mocks = new ArrayList<>(); + mocks.add(createMockDeployment()); + return mocks; + } + + public static Deployment createMockDeployment() { + return createMockDeployment(EXAMPLE_TENANT_ID); + } + + public static Deployment createMockDeployment(String tenantId) { + Deployment mockDeployment = mock(Deployment.class); + when(mockDeployment.getId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + when(mockDeployment.getName()).thenReturn(EXAMPLE_DEPLOYMENT_NAME); + when(mockDeployment.getDeploymentTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_DEPLOYMENT_TIME)); + when(mockDeployment.getSource()).thenReturn(EXAMPLE_DEPLOYMENT_SOURCE); + when(mockDeployment.getTenantId()).thenReturn(tenantId); + return mockDeployment; + } + + public static DeploymentWithDefinitions createMockDeploymentWithDefinitions() { + return createMockDeploymentWithDefinitions(EXAMPLE_TENANT_ID); + } + + public static DeploymentWithDefinitions createMockDeploymentWithDefinitions(String tenantId) { + DeploymentWithDefinitions mockDeployment = mock(DeploymentWithDefinitions.class); + when(mockDeployment.getId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + when(mockDeployment.getName()).thenReturn(EXAMPLE_DEPLOYMENT_NAME); + when(mockDeployment.getDeploymentTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_DEPLOYMENT_TIME)); + when(mockDeployment.getSource()).thenReturn(EXAMPLE_DEPLOYMENT_SOURCE); + when(mockDeployment.getTenantId()).thenReturn(tenantId); + List mockDefinitions = createMockDefinitions(); + when(mockDeployment.getDeployedProcessDefinitions()).thenReturn(mockDefinitions); + + List mockCaseDefinitions = createMockCaseDefinitions(); + when(mockDeployment.getDeployedCaseDefinitions()).thenReturn(mockCaseDefinitions); + + List mockDecisionDefinitions = createMockDecisionDefinitions(); + when(mockDeployment.getDeployedDecisionDefinitions()).thenReturn(mockDecisionDefinitions); + + List mockDecisionRequirementsDefinitions = createMockDecisionRequirementsDefinitions(); + when(mockDeployment.getDeployedDecisionRequirementsDefinitions()).thenReturn(mockDecisionRequirementsDefinitions); + + return mockDeployment; + } + + public static Deployment createMockRedeployment() { + Deployment mockDeployment = mock(Deployment.class); + when(mockDeployment.getId()).thenReturn(EXAMPLE_RE_DEPLOYMENT_ID); + when(mockDeployment.getName()).thenReturn(EXAMPLE_DEPLOYMENT_NAME); + when(mockDeployment.getDeploymentTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_DEPLOYMENT_TIME)); + when(mockDeployment.getSource()).thenReturn(EXAMPLE_DEPLOYMENT_SOURCE); + + return mockDeployment; + } + + // deployment resources + public static List createMockDeploymentResources() { + List mocks = new ArrayList<>(); + mocks.add(createMockDeploymentResource()); + return mocks; + } + + public static Resource createMockDeploymentResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + + return mockResource; + } + + public static Resource createMockDeploymentSvgResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_SVG_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_SVG_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentPngResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_PNG_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_PNG_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentJpgResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_JPG_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_JPG_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentJpegResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_JPEG_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentJpeResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_JPE_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_JPE_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentGifResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_GIF_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_GIF_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentTifResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_TIF_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_TIF_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentTiffResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_TIFF_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentBpmnResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_BPMN_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentBpmnXmlResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_BPMN_XML_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentCmmnResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_CMMN_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentCmmnXmlResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_CMMN_XML_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentDmnResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_DMN_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_DMN_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentDmnXmlResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_DMN_XML_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentXmlResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_XML_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_XML_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentJsonResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_JSON_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_JSON_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentGroovyResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_GROOVY_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentJavaResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_JAVA_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentJsResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_JS_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_JS_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentPhpResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_PHP_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_PHP_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentPythonResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_PYTHON_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentRubyResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_RUBY_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentHtmlResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_HTML_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_HTML_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentTxtResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_TXT_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_TXT_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentCamundaFormResource() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_CAMFORM_RESOURCE_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentResourceFilename() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_PATH + EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + public static Resource createMockDeploymentResourceFilenameBackslash() { + Resource mockResource = mock(ResourceEntity.class); + when(mockResource.getId()).thenReturn(EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_ID); + when(mockResource.getName()).thenReturn(EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_PATH_BACKSLASH + EXAMPLE_DEPLOYMENT_RESOURCE_FILENAME_NAME); + when(mockResource.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + return mockResource; + } + + // user, groups and tenants + + public static Group createMockGroup() { + return mockGroup().build(); + } + + public static MockGroupBuilder mockGroup() { + return new MockGroupBuilder() + .id(EXAMPLE_GROUP_ID) + .name(EXAMPLE_GROUP_NAME) + .type(EXAMPLE_GROUP_TYPE); + } + + public static Group createMockGroupUpdate() { + Group mockGroup = mock(Group.class); + when(mockGroup.getId()).thenReturn(EXAMPLE_GROUP_ID); + when(mockGroup.getName()).thenReturn(EXAMPLE_GROUP_NAME_UPDATE); + + return mockGroup; + } + + public static List createMockGroups() { + List mockGroups = new ArrayList<>(); + mockGroups.add(createMockGroup()); + return mockGroups; + } + + public static User createMockUser() { + return mockUser().build(); + } + + public static MockUserBuilder mockUser() { + return new MockUserBuilder() + .id(EXAMPLE_USER_ID) + .firstName(EXAMPLE_USER_FIRST_NAME) + .lastName(EXAMPLE_USER_LAST_NAME) + .email(EXAMPLE_USER_EMAIL) + .password(EXAMPLE_USER_PASSWORD); + } + + public static Tenant createMockTenant() { + Tenant mockTenant = mock(Tenant.class); + when(mockTenant.getId()).thenReturn(EXAMPLE_TENANT_ID); + when(mockTenant.getName()).thenReturn(EXAMPLE_TENANT_NAME); + return mockTenant; + } + + public static Authentication createMockAuthentication() { + Authentication mockAuthentication = mock(Authentication.class); + + when(mockAuthentication.getUserId()).thenReturn(EXAMPLE_USER_ID); + + return mockAuthentication; + } + + // jobs + public static Job createMockJob() { + return mockJob().tenantId(EXAMPLE_TENANT_ID).build(); + } + + public static MockJobBuilder mockJob() { + return new MockJobBuilder() + .id(EXAMPLE_JOB_ID) + .processInstanceId(EXAMPLE_PROCESS_INSTANCE_ID) + .executionId(EXAMPLE_EXECUTION_ID) + .processDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .processDefinitionKey(EXAMPLE_PROCESS_DEFINITION_KEY) + .retries(EXAMPLE_JOB_RETRIES) + .exceptionMessage(EXAMPLE_JOB_NO_EXCEPTION_MESSAGE) + .dueDate(DateTimeUtil.parseDate(EXAMPLE_DUE_DATE)) + .suspended(EXAMPLE_JOB_IS_SUSPENDED) + .priority(EXAMPLE_JOB_PRIORITY) + .jobDefinitionId(EXAMPLE_JOB_DEFINITION_ID) + .createTime(DateTimeUtil.parseDate(EXAMPLE_JOB_CREATE_TIME)) + .failedActivityId(EXAMPLE_JOB_FAILED_ACTIVITY_ID) + .batchId(EXAMPLE_BATCH_ID); + } + + public static List createMockJobs() { + List mockList = new ArrayList<>(); + mockList.add(createMockJob()); + return mockList; + } + + public static List createMockEmptyJobList() { + return new ArrayList<>(); + } + + public static User createMockUserUpdate() { + User mockUser = mock(User.class); + when(mockUser.getId()).thenReturn(EXAMPLE_USER_ID); + when(mockUser.getFirstName()).thenReturn(EXAMPLE_USER_FIRST_NAME_UPDATE); + when(mockUser.getLastName()).thenReturn(EXAMPLE_USER_LAST_NAME_UPDATE); + when(mockUser.getEmail()).thenReturn(EXAMPLE_USER_EMAIL_UPDATE); + when(mockUser.getPassword()).thenReturn(EXAMPLE_USER_PASSWORD); + return mockUser; + } + + public static List createMockUsers() { + ArrayList list = new ArrayList<>(); + list.add(createMockUser()); + return list; + } + + public static Authorization createMockGlobalAuthorization() { + Authorization mockAuthorization = mock(Authorization.class); + + when(mockAuthorization.getId()).thenReturn(EXAMPLE_AUTHORIZATION_ID); + when(mockAuthorization.getAuthorizationType()).thenReturn(Authorization.AUTH_TYPE_GLOBAL); + when(mockAuthorization.getUserId()).thenReturn(Authorization.ANY); + + when(mockAuthorization.getResourceType()).thenReturn(EXAMPLE_RESOURCE_TYPE_ID); + when(mockAuthorization.getResourceId()).thenReturn(EXAMPLE_RESOURCE_ID); + when(mockAuthorization.getPermissions(Permissions.values())).thenReturn(EXAMPLE_GRANT_PERMISSION_VALUES); + + when(mockAuthorization.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_AUTH_REMOVAL_TIME)); + when(mockAuthorization.getRootProcessInstanceId()).thenReturn(EXAMPLE_AUTH_ROOT_PROCESS_INSTANCE_ID); + + return mockAuthorization; + } + + public static Authorization createMockGrantAuthorization() { + Authorization mockAuthorization = mock(Authorization.class); + + when(mockAuthorization.getId()).thenReturn(EXAMPLE_AUTHORIZATION_ID); + when(mockAuthorization.getAuthorizationType()).thenReturn(Authorization.AUTH_TYPE_GRANT); + when(mockAuthorization.getUserId()).thenReturn(EXAMPLE_USER_ID); + + when(mockAuthorization.getResourceType()).thenReturn(EXAMPLE_RESOURCE_TYPE_ID); + when(mockAuthorization.getResourceId()).thenReturn(EXAMPLE_RESOURCE_ID); + when(mockAuthorization.getPermissions(Permissions.values())).thenReturn(EXAMPLE_GRANT_PERMISSION_VALUES); + + return mockAuthorization; + } + + public static Authorization createMockRevokeAuthorization() { + Authorization mockAuthorization = mock(Authorization.class); + + when(mockAuthorization.getId()).thenReturn(EXAMPLE_AUTHORIZATION_ID); + when(mockAuthorization.getAuthorizationType()).thenReturn(Authorization.AUTH_TYPE_REVOKE); + when(mockAuthorization.getUserId()).thenReturn(EXAMPLE_USER_ID); + + when(mockAuthorization.getResourceType()).thenReturn(EXAMPLE_RESOURCE_TYPE_ID); + when(mockAuthorization.getResourceId()).thenReturn(EXAMPLE_RESOURCE_ID); + when(mockAuthorization.getPermissions(Permissions.values())).thenReturn(EXAMPLE_REVOKE_PERMISSION_VALUES); + + return mockAuthorization; + } + + public static List createMockAuthorizations() { + return Arrays.asList(createMockGlobalAuthorization(), createMockGrantAuthorization(), createMockRevokeAuthorization()); + } + + public static List createMockGrantAuthorizations() { + return Arrays.asList(createMockGrantAuthorization()); + } + + public static List createMockRevokeAuthorizations() { + return Arrays.asList(createMockRevokeAuthorization()); + } + + public static List createMockGlobalAuthorizations() { + return Arrays.asList(createMockGlobalAuthorization()); + } + + public static Date createMockDuedate() { + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.DATE, 3); + return cal.getTime(); + } // process application + + public static ProcessApplicationInfo createMockProcessApplicationInfo() { + ProcessApplicationInfo appInfo = mock(ProcessApplicationInfo.class); + Map mockAppProperties = new HashMap<>(); + String mockServletContextPath = MockProvider.EXAMPLE_PROCESS_APPLICATION_CONTEXT_PATH; + mockAppProperties.put(ProcessApplicationInfo.PROP_SERVLET_CONTEXT_PATH, mockServletContextPath); + when(appInfo.getProperties()).thenReturn(mockAppProperties); + return appInfo; + } + + // History + public static List createMockHistoricActivityInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockHistoricActivityInstance()); + return mockList; + } + + public static HistoricActivityInstance createMockHistoricActivityInstance() { + return createMockHistoricActivityInstance(EXAMPLE_TENANT_ID); + } + + public static HistoricActivityInstance createMockHistoricActivityInstance(String tenantId) { + HistoricActivityInstance mock = mock(HistoricActivityInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_ID); + when(mock.getParentActivityInstanceId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_PARENT_ACTIVITY_INSTANCE_ID); + when(mock.getActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(mock.getActivityName()).thenReturn(EXAMPLE_ACTIVITY_NAME); + when(mock.getActivityType()).thenReturn(EXAMPLE_ACTIVITY_TYPE); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getExecutionId()).thenReturn(EXAMPLE_EXECUTION_ID); + when(mock.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(mock.getCalledProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID); + when(mock.getCalledCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID); + when(mock.getAssignee()).thenReturn(EXAMPLE_TASK_ASSIGNEE_NAME); + when(mock.getStartTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_START_TIME)); + when(mock.getEndTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_END_TIME)); + when(mock.getDurationInMillis()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_DURATION); + when(mock.isCanceled()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_CANCELED); + when(mock.isCompleteScope()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_COMPLETE_SCOPE); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_REMOVAL_TIME)); + when(mock.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_ROOT_PROCESS_INSTANCE_ID); + + return mock; + } + + public static List createMockRunningHistoricActivityInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockRunningHistoricActivityInstance()); + return mockList; + } + + public static HistoricActivityInstance createMockRunningHistoricActivityInstance() { + HistoricActivityInstance mock = mock(HistoricActivityInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_ID); + when(mock.getParentActivityInstanceId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_PARENT_ACTIVITY_INSTANCE_ID); + when(mock.getActivityId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(mock.getActivityName()).thenReturn(EXAMPLE_ACTIVITY_NAME); + when(mock.getActivityType()).thenReturn(EXAMPLE_ACTIVITY_TYPE); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getExecutionId()).thenReturn(EXAMPLE_EXECUTION_ID); + when(mock.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(mock.getCalledProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID); + when(mock.getCalledCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID); + when(mock.getAssignee()).thenReturn(EXAMPLE_TASK_ASSIGNEE_NAME); + when(mock.getStartTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_START_TIME)); + when(mock.getEndTime()).thenReturn(null); + when(mock.getDurationInMillis()).thenReturn(null); + + return mock; + } + + public static List createMockHistoricCaseActivityInstances() { + ArrayList mockList = new ArrayList<>(); + mockList.add(createMockHistoricCaseActivityInstance()); + return mockList; + } + + public static HistoricCaseActivityInstance createMockHistoricCaseActivityInstance() { + return createMockHistoricCaseActivityInstance(EXAMPLE_TENANT_ID); + } + + public static HistoricCaseActivityInstance createMockHistoricCaseActivityInstance(String tenantId) { + HistoricCaseActivityInstance mock = mock(HistoricCaseActivityInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID); + when(mock.getParentCaseActivityInstanceId()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_PARENT_CASE_ACTIVITY_INSTANCE_ID); + when(mock.getCaseActivityId()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_ID); + when(mock.getCaseActivityName()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_NAME); + when(mock.getCaseActivityType()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_TYPE); + when(mock.getCaseDefinitionId()).thenReturn(EXAMPLE_CASE_DEFINITION_ID); + when(mock.getCaseInstanceId()).thenReturn(EXAMPLE_CASE_INSTANCE_ID); + when(mock.getCaseExecutionId()).thenReturn(EXAMPLE_CASE_EXECUTION_ID); + when(mock.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(mock.getCalledProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID); + when(mock.getCalledCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID); + when(mock.getCreateTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATE_TIME)); + when(mock.getEndTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME)); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.getDurationInMillis()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_DURATION); + when(mock.isRequired()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_REQUIRED); + when(mock.isAvailable()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_AVAILABLE); + when(mock.isEnabled()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ENABLED); + when(mock.isDisabled()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_DISABLED); + when(mock.isActive()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ACTIVE); + when(mock.isCompleted()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_COMPLETED); + when(mock.isTerminated()).thenReturn(EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_TERMINATED); + + return mock; + } + + public static List createMockRunningHistoricCaseActivityInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockRunningHistoricCaseActivityInstance()); + return mockList; + } + + public static HistoricCaseActivityInstance createMockRunningHistoricCaseActivityInstance() { + HistoricCaseActivityInstance mock = createMockHistoricCaseActivityInstance(); + + when(mock.getEndTime()).thenReturn(null); + when(mock.getDurationInMillis()).thenReturn(null); + when(mock.isAvailable()).thenReturn(false); + when(mock.isEnabled()).thenReturn(false); + when(mock.isDisabled()).thenReturn(false); + when(mock.isActive()).thenReturn(true); + when(mock.isCompleted()).thenReturn(false); + when(mock.isTerminated()).thenReturn(false); + + return mock; + } + + public static List createMockHistoricActivityStatistics() { + HistoricActivityStatistics statistics = mock(HistoricActivityStatistics.class); + + when(statistics.getId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(statistics.getInstances()).thenReturn(EXAMPLE_INSTANCES_LONG); + when(statistics.getCanceled()).thenReturn(EXAMPLE_CANCELED_LONG); + when(statistics.getFinished()).thenReturn(EXAMPLE_FINISHED_LONG); + when(statistics.getCompleteScope()).thenReturn(EXAMPLE_COMPLETE_SCOPE_LONG); + when(statistics.getOpenIncidents()).thenReturn(EXAMPLE_OPEN_INCIDENTS_LONG); + when(statistics.getResolvedIncidents()).thenReturn(EXAMPLE_RESOLVED_INCIDENTS_LONG); + when(statistics.getDeletedIncidents()).thenReturn(EXAMPLE_DELETED_INCIDENTS_LONG); + + HistoricActivityStatistics anotherStatistics = mock(HistoricActivityStatistics.class); + + when(anotherStatistics.getId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + when(anotherStatistics.getInstances()).thenReturn(ANOTHER_EXAMPLE_INSTANCES_LONG); + when(anotherStatistics.getCanceled()).thenReturn(ANOTHER_EXAMPLE_CANCELED_LONG); + when(anotherStatistics.getFinished()).thenReturn(ANOTHER_EXAMPLE_FINISHED_LONG); + when(anotherStatistics.getCompleteScope()).thenReturn(ANOTHER_EXAMPLE_COMPLETE_SCOPE_LONG); + when(anotherStatistics.getOpenIncidents()).thenReturn(ANOTHER_EXAMPLE_OPEN_INCIDENTS_LONG); + when(anotherStatistics.getResolvedIncidents()).thenReturn(ANOTHER_EXAMPLE_RESOLVED_INCIDENTS_LONG); + when(anotherStatistics.getDeletedIncidents()).thenReturn(ANOTHER_EXAMPLE_DELETED_INCIDENTS_LONG); + + List activityResults = new ArrayList<>(); + activityResults.add(statistics); + activityResults.add(anotherStatistics); + + return activityResults; + } + + public static List createMockHistoricCaseActivityStatistics() { + HistoricCaseActivityStatistics statistics = mock(HistoricCaseActivityStatistics.class); + + when(statistics.getId()).thenReturn(EXAMPLE_ACTIVITY_ID); + when(statistics.getActive()).thenReturn(EXAMPLE_ACTIVE_LONG); + when(statistics.getAvailable()).thenReturn(EXAMPLE_AVAILABLE_LONG); + when(statistics.getCompleted()).thenReturn(EXAMPLE_COMPLETED_LONG); + when(statistics.getDisabled()).thenReturn(EXAMPLE_DISABLED_LONG); + when(statistics.getEnabled()).thenReturn(EXAMPLE_ENABLED_LONG); + when(statistics.getTerminated()).thenReturn(EXAMPLE_TERMINATED_LONG); + + HistoricCaseActivityStatistics anotherStatistics = mock(HistoricCaseActivityStatistics.class); + + when(anotherStatistics.getId()).thenReturn(ANOTHER_EXAMPLE_ACTIVITY_ID); + when(anotherStatistics.getActive()).thenReturn(ANOTHER_EXAMPLE_ACTIVE_LONG); + when(anotherStatistics.getAvailable()).thenReturn(ANOTHER_EXAMPLE_AVAILABLE_LONG); + when(anotherStatistics.getCompleted()).thenReturn(ANOTHER_EXAMPLE_COMPLETED_LONG); + when(anotherStatistics.getDisabled()).thenReturn(ANOTHER_EXAMPLE_DISABLED_LONG); + when(anotherStatistics.getEnabled()).thenReturn(ANOTHER_EXAMPLE_ENABLED_LONG); + when(anotherStatistics.getTerminated()).thenReturn(ANOTHER_EXAMPLE_TERMINATED_LONG); + + List activityResults = new ArrayList<>(); + activityResults.add(statistics); + activityResults.add(anotherStatistics); + + return activityResults; + } + + public static List createMockHistoricProcessInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockHistoricProcessInstance()); + return mockList; + } + + public static HistoricProcessInstance createMockHistoricProcessInstance() { + return createMockHistoricProcessInstance(EXAMPLE_TENANT_ID); + } + + public static HistoricProcessInstance createMockHistoricProcessInstance(String tenantId) { + HistoricProcessInstance mock = mock(HistoricProcessInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getBusinessKey()).thenReturn(EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(mock.getProcessDefinitionName()).thenReturn(EXAMPLE_PROCESS_DEFINITION_NAME); + when(mock.getProcessDefinitionVersion()).thenReturn(EXAMPLE_PROCESS_DEFINITION_VERSION); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getDeleteReason()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON); + when(mock.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_PROCESS_INSTANCE_REMOVAL_TIME)); + when(mock.getEndTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_PROCESS_INSTANCE_END_TIME)); + when(mock.getStartTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_TIME)); + when(mock.getDurationInMillis()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_DURATION_MILLIS); + when(mock.getStartUserId()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_USER_ID); + when(mock.getStartActivityId()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_ACTIVITY_ID); + when(mock.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_ROOT_PROCESS_INSTANCE_ID); + when(mock.getSuperProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_PROCESS_INSTANCE_ID); + when(mock.getSuperCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_CASE_INSTANCE_ID); + when(mock.getCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_CASE_INSTANCE_ID); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.getState()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_STATE); + when(mock.getRestartedProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + + return mock; + } + + public static List createMockRunningHistoricProcessInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockHistoricProcessInstanceUnfinished()); + return mockList; + } + + public static HistoricProcessInstance createMockHistoricProcessInstanceUnfinished() { + HistoricProcessInstance mock = mock(HistoricProcessInstance.class); + when(mock.getId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getBusinessKey()).thenReturn(EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getDeleteReason()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON); + when(mock.getEndTime()).thenReturn(null); + when(mock.getStartTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_TIME)); + when(mock.getDurationInMillis()).thenReturn(EXAMPLE_HISTORIC_PROCESS_INSTANCE_DURATION_MILLIS); + return mock; + } + + public static List createMockHistoricProcessInstanceDurationReportByMonth() { + DurationReportResult mock = mock(DurationReportResult.class); + when(mock.getAverage()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG); + when(mock.getMinimum()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN); + when(mock.getMaximum()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX); + when(mock.getPeriod()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_PERIOD); + when(mock.getPeriodUnit()).thenReturn(PeriodUnit.MONTH); + + List mockList = new ArrayList<>(); + mockList.add(mock); + return mockList; + } + + public static List createMockHistoricProcessInstanceDurationReportByQuarter() { + DurationReportResult mock = mock(DurationReportResult.class); + when(mock.getAverage()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG); + when(mock.getMinimum()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN); + when(mock.getMaximum()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX); + when(mock.getPeriod()).thenReturn(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_PERIOD); + when(mock.getPeriodUnit()).thenReturn(PeriodUnit.QUARTER); + + List mockList = new ArrayList<>(); + mockList.add(mock); + return mockList; + } + + public static List createMockHistoricCaseInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockHistoricCaseInstance()); + return mockList; + } + + public static HistoricCaseInstance createMockHistoricCaseInstance() { + return createMockHistoricCaseInstance(EXAMPLE_TENANT_ID); + } + + public static HistoricCaseInstance createMockHistoricCaseInstance(String tenantId) { + HistoricCaseInstance mock = mock(HistoricCaseInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_CASE_INSTANCE_ID); + when(mock.getBusinessKey()).thenReturn(EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + when(mock.getCaseDefinitionId()).thenReturn(EXAMPLE_CASE_DEFINITION_ID); + when(mock.getCaseDefinitionKey()).thenReturn(EXAMPLE_CASE_DEFINITION_KEY); + when(mock.getCaseDefinitionName()).thenReturn(EXAMPLE_CASE_DEFINITION_NAME); + when(mock.getCreateTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_TIME)); + when(mock.getCloseTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSE_TIME)); + when(mock.getDurationInMillis()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_DURATION_MILLIS); + when(mock.getCreateUserId()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_USER_ID); + when(mock.getSuperCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_CASE_INSTANCE_ID); + when(mock.getSuperProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_PROCESS_INSTANCE_ID); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.isActive()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_IS_ACTIVE); + when(mock.isCompleted()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_IS_COMPLETED); + when(mock.isTerminated()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_IS_TERMINATED); + when(mock.isClosed()).thenReturn(EXAMPLE_HISTORIC_CASE_INSTANCE_IS_CLOSED); + + return mock; + } + + public static List createMockRunningHistoricCaseInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockHistoricCaseInstanceNotClosed()); + return mockList; + } + + public static HistoricCaseInstance createMockHistoricCaseInstanceNotClosed() { + HistoricCaseInstance mock = createMockHistoricCaseInstance(); + + when(mock.getCloseTime()).thenReturn(null); + when(mock.getDurationInMillis()).thenReturn(null); + when(mock.isActive()).thenReturn(true); + when(mock.isCompleted()).thenReturn(false); + when(mock.isTerminated()).thenReturn(false); + when(mock.isClosed()).thenReturn(false); + + return mock; + } + + public static HistoricVariableInstance createMockHistoricVariableInstance() { + return mockHistoricVariableInstance(EXAMPLE_TENANT_ID).build(); + } + + public static MockHistoricVariableInstanceBuilder mockHistoricVariableInstance() { + return mockHistoricVariableInstance(EXAMPLE_TENANT_ID); + } + + public static MockHistoricVariableInstanceBuilder mockHistoricVariableInstance(String tenantId) { + return new MockHistoricVariableInstanceBuilder() + .id(EXAMPLE_VARIABLE_INSTANCE_ID) + .name(EXAMPLE_VARIABLE_INSTANCE_NAME) + .typedValue(EXAMPLE_PRIMITIVE_VARIABLE_VALUE) + .processDefinitionKey(EXAMPLE_VARIABLE_INSTANCE_PROC_DEF_KEY) + .processDefinitionId(EXAMPLE_VARIABLE_INSTANCE_PROC_DEF_ID) + .processInstanceId(EXAMPLE_VARIABLE_INSTANCE_PROC_INST_ID) + .executionId(EXAMPLE_VARIABLE_INSTANCE_EXECUTION_ID) + .activityInstanceId(EXAMPLE_VARIABLE_INSTANCE_ACTIVITY_INSTANCE_ID) + .caseDefinitionKey(EXAMPLE_VARIABLE_INSTANCE_CASE_DEF_KEY) + .caseDefinitionId(EXAMPLE_VARIABLE_INSTANCE_CASE_DEF_ID) + .caseInstanceId(EXAMPLE_VARIABLE_INSTANCE_CASE_INST_ID) + .caseExecutionId(EXAMPLE_VARIABLE_INSTANCE_CASE_EXECUTION_ID) + .taskId(EXAMPLE_VARIABLE_INSTANCE_TASK_ID) + .tenantId(tenantId) + .errorMessage(null) + .createTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_VARIABLE_INSTANCE_CREATE_TIME)) + .removalTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_VARIABLE_INSTANCE_REMOVAL_TIME)) + .rootProcessInstanceId(EXAMPLE_HISTORIC_VARIABLE_INSTANCE_ROOT_PROC_INST_ID); + } + + public static List createAnotherMockProcessInstanceList() { + List mockProcessInstanceList = new ArrayList<>(); + mockProcessInstanceList.add(createMockInstance()); + mockProcessInstanceList.add(createAnotherMockInstance()); + return mockProcessInstanceList; + } + + public static ProcessInstance createAnotherMockInstance() { + ProcessInstance mock = mock(ProcessInstance.class); + + when(mock.getId()).thenReturn(ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getBusinessKey()).thenReturn(EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(mock.getProcessInstanceId()).thenReturn(ANOTHER_EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.isSuspended()).thenReturn(EXAMPLE_PROCESS_INSTANCE_IS_SUSPENDED); + when(mock.isEnded()).thenReturn(EXAMPLE_PROCESS_INSTANCE_IS_ENDED); + + return mock; + } + + public static Set createMockSetFromList(String list){ + return new HashSet<>(Arrays.asList(list.split(","))); + } + + public static IdentityLink createMockUserAssigneeIdentityLink() { + IdentityLink identityLink = mock(IdentityLink.class); + when(identityLink.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(identityLink.getType()).thenReturn(IdentityLinkType.ASSIGNEE); + when(identityLink.getUserId()).thenReturn(EXAMPLE_TASK_ASSIGNEE_NAME); + + return identityLink; + } + + public static IdentityLink createMockUserOwnerIdentityLink() { + IdentityLink identityLink = mock(IdentityLink.class); + when(identityLink.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(identityLink.getType()).thenReturn(IdentityLinkType.OWNER); + when(identityLink.getUserId()).thenReturn(EXAMPLE_TASK_OWNER); + + return identityLink; + } + + public static IdentityLink createMockCandidateGroupIdentityLink() { + IdentityLink identityLink = mock(IdentityLink.class); + when(identityLink.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(identityLink.getType()).thenReturn(IdentityLinkType.CANDIDATE); + when(identityLink.getGroupId()).thenReturn(EXAMPLE_GROUP_ID); + + return identityLink; + } + + public static IdentityLink createAnotherMockCandidateGroupIdentityLink() { + IdentityLink identityLink = mock(IdentityLink.class); + when(identityLink.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(identityLink.getType()).thenReturn(IdentityLinkType.CANDIDATE); + when(identityLink.getGroupId()).thenReturn(EXAMPLE_GROUP_ID2); + + return identityLink; + } + + // Historic identity link + public static HistoricIdentityLinkLog createMockHistoricIdentityLink() { + return createMockHistoricIdentityLink(EXAMPLE_TENANT_ID); + } + + public static HistoricIdentityLinkLog createMockHistoricIdentityLink(String tenantId) { + HistoricIdentityLinkLog identityLink = mock(HistoricIdentityLinkLog.class); + + when(identityLink.getAssignerId()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_ASSIGNER_ID); + when(identityLink.getTenantId()).thenReturn(tenantId); + when(identityLink.getGroupId()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_GROUP_ID); + when(identityLink.getTaskId()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_TASK_ID); + when(identityLink.getUserId()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_USER_ID); + when(identityLink.getGroupId()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_GROUP_ID); + when(identityLink.getType()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_TYPE); + when(identityLink.getOperationType()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_OPERATION_TYPE); + when(identityLink.getProcessDefinitionId()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_ID); + when(identityLink.getProcessDefinitionKey()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_KEY); + when(identityLink.getTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HIST_IDENTITY_LINK_TIME)); + when(identityLink.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HIST_IDENTITY_LINK_REMOVAL_TIME)); + when(identityLink.getRootProcessInstanceId()).thenReturn(EXAMPLE_HIST_IDENTITY_LINK_ROOT_PROC_INST_ID); + + return identityLink; + } + + public static List createMockHistoricIdentityLinks() { + List entries = new ArrayList<>(); + entries.add(createMockHistoricIdentityLink()); + return entries; + } + + // job definition + public static List createMockJobDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockJobDefinition()); + return mocks; + } + + public static JobDefinition createMockJobDefinition() { + return mockJobDefinition().build(); + } + + public static MockJobDefinitionBuilder mockJobDefinition() { + return new MockJobDefinitionBuilder() + .id(EXAMPLE_JOB_DEFINITION_ID) + .activityId(EXAMPLE_ACTIVITY_ID) + .jobConfiguration(EXAMPLE_JOB_CONFIG) + .jobType(EXAMPLE_JOB_TYPE) + .jobPriority(EXAMPLE_JOB_DEFINITION_PRIORITY) + .suspended(EXAMPLE_JOB_DEFINITION_IS_SUSPENDED) + .processDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .processDefinitionKey(EXAMPLE_PROCESS_DEFINITION_KEY) + .deploymentId(EXAMPLE_JOB_DEFINITION_DEPLOYMENT_ID); + } + + public static List createUserOperationLogEntries() { + List entries = new ArrayList<>(); + entries.add(createUserOperationLogEntry()); + return entries; + } + + private static UserOperationLogEntry createUserOperationLogEntry() { + UserOperationLogEntry entry = mock(UserOperationLogEntry.class); + when(entry.getId()).thenReturn(EXAMPLE_USER_OPERATION_LOG_ID); + when(entry.getDeploymentId()).thenReturn(EXAMPLE_DEPLOYMENT_ID); + when(entry.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(entry.getProcessDefinitionKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(entry.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(entry.getExecutionId()).thenReturn(EXAMPLE_EXECUTION_ID); + when(entry.getCaseDefinitionId()).thenReturn(EXAMPLE_CASE_DEFINITION_ID); + when(entry.getCaseInstanceId()).thenReturn(EXAMPLE_CASE_INSTANCE_ID); + when(entry.getCaseExecutionId()).thenReturn(EXAMPLE_CASE_EXECUTION_ID); + when(entry.getTaskId()).thenReturn(EXAMPLE_TASK_ID); + when(entry.getJobId()).thenReturn(EXAMPLE_JOB_ID); + when(entry.getJobDefinitionId()).thenReturn(EXAMPLE_JOB_DEFINITION_ID); + when(entry.getBatchId()).thenReturn(EXAMPLE_BATCH_ID); + when(entry.getUserId()).thenReturn(EXAMPLE_USER_ID); + when(entry.getTimestamp()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_USER_OPERATION_TIMESTAMP)); + when(entry.getOperationId()).thenReturn(EXAMPLE_USER_OPERATION_ID); + when(entry.getOperationType()).thenReturn(EXAMPLE_USER_OPERATION_TYPE); + when(entry.getEntityType()).thenReturn(EXAMPLE_USER_OPERATION_ENTITY); + when(entry.getProperty()).thenReturn(EXAMPLE_USER_OPERATION_PROPERTY); + when(entry.getOrgValue()).thenReturn(EXAMPLE_USER_OPERATION_ORG_VALUE); + when(entry.getNewValue()).thenReturn(EXAMPLE_USER_OPERATION_NEW_VALUE); + return entry; + } + + // historic detail //////////////////// + + public static HistoricVariableUpdate createMockHistoricVariableUpdate() { + return mockHistoricVariableUpdate(EXAMPLE_TENANT_ID).build(); + } + + public static MockHistoricVariableUpdateBuilder mockHistoricVariableUpdate() { + return mockHistoricVariableUpdate(EXAMPLE_TENANT_ID); + } + + public static MockHistoricVariableUpdateBuilder mockHistoricVariableUpdate(String tenantId) { + return new MockHistoricVariableUpdateBuilder() + .id(EXAMPLE_HISTORIC_VAR_UPDATE_ID) + .processDefinitionKey(EXAMPLE_HISTORIC_VAR_UPDATE_PROC_DEF_KEY) + .processDefinitionId(EXAMPLE_HISTORIC_VAR_UPDATE_PROC_DEF_ID) + .processInstanceId(EXAMPLE_HISTORIC_VAR_UPDATE_PROC_INST_ID) + .activityInstanceId(EXAMPLE_HISTORIC_VAR_UPDATE_ACT_INST_ID) + .executionId(EXAMPLE_HISTORIC_VAR_UPDATE_EXEC_ID) + .taskId(EXAMPLE_HISTORIC_VAR_UPDATE_TASK_ID) + .time(EXAMPLE_HISTORIC_VAR_UPDATE_TIME) + .name(EXAMPLE_HISTORIC_VAR_UPDATE_NAME) + .variableInstanceId(EXAMPLE_HISTORIC_VAR_UPDATE_VAR_INST_ID) + .typedValue(EXAMPLE_PRIMITIVE_VARIABLE_VALUE) + .revision(EXAMPLE_HISTORIC_VAR_UPDATE_REVISION) + .errorMessage(null) + .caseDefinitionKey(EXAMPLE_HISTORIC_VAR_UPDATE_CASE_DEF_KEY) + .caseDefinitionId(EXAMPLE_HISTORIC_VAR_UPDATE_CASE_DEF_ID) + .caseInstanceId(EXAMPLE_HISTORIC_VAR_UPDATE_CASE_INST_ID) + .caseExecutionId(EXAMPLE_HISTORIC_VAR_UPDATE_CASE_EXEC_ID) + .tenantId(tenantId) + .initial(false); + } + + public static HistoricFormField createMockHistoricFormField() { + return createMockHistoricFormField(EXAMPLE_TENANT_ID); + } + + public static HistoricFormField createMockHistoricFormField(String tenantId) { + HistoricFormField historicFromField = mock(HistoricFormField.class); + + when(historicFromField.getId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_ID); + when(historicFromField.getProcessDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_KEY); + when(historicFromField.getProcessDefinitionId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_ID); + when(historicFromField.getProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_PROC_INST_ID); + when(historicFromField.getActivityInstanceId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_ACT_INST_ID); + when(historicFromField.getExecutionId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_EXEC_ID); + when(historicFromField.getTaskId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_TASK_ID); + when(historicFromField.getTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_FORM_FIELD_TIME)); + when(historicFromField.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_FORM_FIELD_TIME)); + when(historicFromField.getFieldId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_FIELD_ID); + when(historicFromField.getFieldValue()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_VALUE); + when(historicFromField.getCaseDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_KEY); + when(historicFromField.getCaseDefinitionId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_ID); + when(historicFromField.getCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_CASE_INST_ID); + when(historicFromField.getCaseExecutionId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_CASE_EXEC_ID); + when(historicFromField.getTenantId()).thenReturn(tenantId); + when(historicFromField.getUserOperationId()).thenReturn(EXAMPLE_HISTORIC_FORM_FIELD_OPERATION_ID); + when(historicFromField.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_FORM_ROOT_PROCESS_INSTANCE_ID); + + return historicFromField; + } + + public static List createMockHistoricFormFields() { + List entries = new ArrayList<>(); + entries.add(createMockHistoricFormField()); + return entries; + } + + public static List createMockHistoricDetails() { + return createMockHistoricDetails(EXAMPLE_TENANT_ID); + } + + public static List createMockHistoricDetails(String tenantId) { + List entries = new ArrayList<>(); + entries.add(mockHistoricVariableUpdate(tenantId).build()); + entries.add(createMockHistoricFormField(tenantId)); + return entries; + } + + public static HistoricTaskInstance createMockHistoricTaskInstance() { + return createMockHistoricTaskInstance(EXAMPLE_TENANT_ID); + } + + public static HistoricTaskInstance createMockHistoricTaskInstance(String tenantId) { + return createMockHistoricTaskInstance(tenantId, EXAMPLE_HISTORIC_TASK_INST_DUE_DATE); + } + + public static HistoricTaskInstance createMockHistoricTaskInstance(String tenantId, String dueDateString) { + HistoricTaskInstance taskInstance = mock(HistoricTaskInstance.class); + + when(taskInstance.getId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_ID); + when(taskInstance.getProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_PROC_INST_ID); + when(taskInstance.getActivityInstanceId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_ACT_INST_ID); + when(taskInstance.getExecutionId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_EXEC_ID); + when(taskInstance.getProcessDefinitionId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_ID); + when(taskInstance.getProcessDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_KEY); + when(taskInstance.getName()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_NAME); + when(taskInstance.getDescription()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DESCRIPTION); + when(taskInstance.getDeleteReason()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DELETE_REASON); + when(taskInstance.getOwner()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_OWNER); + when(taskInstance.getAssignee()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_ASSIGNEE); + when(taskInstance.getStartTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_TASK_INST_START_TIME)); + when(taskInstance.getEndTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_TASK_INST_END_TIME)); + when(taskInstance.getDurationInMillis()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DURATION); + when(taskInstance.getTaskDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_DEF_KEY); + when(taskInstance.getPriority()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_PRIORITY); + when(taskInstance.getDueDate()).thenReturn(dueDateString == null ? null : DateTimeUtil.parseDate(dueDateString)); + when(taskInstance.getFollowUpDate()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE)); + when(taskInstance.getParentTaskId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_PARENT_TASK_ID); + when(taskInstance.getCaseDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_KEY); + when(taskInstance.getCaseDefinitionId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_ID); + when(taskInstance.getCaseInstanceId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_CASE_INST_ID); + when(taskInstance.getCaseExecutionId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_CASE_EXEC_ID); + when(taskInstance.getTenantId()).thenReturn(tenantId); + when(taskInstance.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_TASK_INST_REMOVAL_TIME)); + when(taskInstance.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_TASK_INST_ROOT_PROC_INST_ID); + when(taskInstance.getTaskState()).thenReturn(EXAMPLE_HISTORIC_TASK_STATE); + + return taskInstance; + } + + public static List createMockHistoricTaskInstances() { + List entries = new ArrayList<>(); + entries.add(createMockHistoricTaskInstance()); + return entries; + } + + // Incident /////////////////////////////////////// + + public static Incident createMockIncident() { + return createMockIncident(EXAMPLE_TENANT_ID); + } + + public static Incident createMockIncident(String tenantId) { + Incident incident = mock(Incident.class); + + when(incident.getId()).thenReturn(EXAMPLE_INCIDENT_ID); + when(incident.getIncidentTimestamp()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_INCIDENT_TIMESTAMP)); + when(incident.getIncidentType()).thenReturn(EXAMPLE_INCIDENT_TYPE); + when(incident.getExecutionId()).thenReturn(EXAMPLE_INCIDENT_EXECUTION_ID); + when(incident.getActivityId()).thenReturn(EXAMPLE_INCIDENT_ACTIVITY_ID); + when(incident.getFailedActivityId()).thenReturn(EXAMPLE_INCIDENT_FAILED_ACTIVITY_ID); + when(incident.getProcessInstanceId()).thenReturn(EXAMPLE_INCIDENT_PROC_INST_ID); + when(incident.getProcessDefinitionId()).thenReturn(EXAMPLE_INCIDENT_PROC_DEF_ID); + when(incident.getCauseIncidentId()).thenReturn(EXAMPLE_INCIDENT_CAUSE_INCIDENT_ID); + when(incident.getRootCauseIncidentId()).thenReturn(EXAMPLE_INCIDENT_ROOT_CAUSE_INCIDENT_ID); + when(incident.getConfiguration()).thenReturn(EXAMPLE_INCIDENT_CONFIGURATION); + when(incident.getIncidentMessage()).thenReturn(EXAMPLE_INCIDENT_MESSAGE); + when(incident.getTenantId()).thenReturn(tenantId); + when(incident.getJobDefinitionId()).thenReturn(EXAMPLE_JOB_DEFINITION_ID); + when(incident.getAnnotation()).thenReturn(EXAMPLE_USER_OPERATION_ANNOTATION); + + return incident; + } + + public static List createMockIncidents() { + List entries = new ArrayList<>(); + entries.add(createMockIncident()); + return entries; + } + + // Historic Incident /////////////////////////////////////// + public static HistoricIncident createMockHistoricIncident() { + return createMockHistoricIncident(EXAMPLE_TENANT_ID); + } + + public static HistoricIncident createMockHistoricIncident(String tenantId) { + HistoricIncident incident = mock(HistoricIncident.class); + + when(incident.getId()).thenReturn(EXAMPLE_HIST_INCIDENT_ID); + when(incident.getCreateTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HIST_INCIDENT_CREATE_TIME)); + when(incident.getEndTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HIST_INCIDENT_END_TIME)); + when(incident.getIncidentType()).thenReturn(EXAMPLE_HIST_INCIDENT_TYPE); + when(incident.getExecutionId()).thenReturn(EXAMPLE_HIST_INCIDENT_EXECUTION_ID); + when(incident.getActivityId()).thenReturn(EXAMPLE_HIST_INCIDENT_ACTIVITY_ID); + when(incident.getFailedActivityId()).thenReturn(EXAMPLE_HIST_INCIDENT_FAILED_ACTIVITY_ID); + when(incident.getProcessInstanceId()).thenReturn(EXAMPLE_HIST_INCIDENT_PROC_INST_ID); + when(incident.getProcessDefinitionId()).thenReturn(EXAMPLE_HIST_INCIDENT_PROC_DEF_ID); + when(incident.getProcessDefinitionKey()).thenReturn(EXAMPLE_HIST_INCIDENT_PROC_DEF_KEY); + when(incident.getCauseIncidentId()).thenReturn(EXAMPLE_HIST_INCIDENT_CAUSE_INCIDENT_ID); + when(incident.getRootCauseIncidentId()).thenReturn(EXAMPLE_HIST_INCIDENT_ROOT_CAUSE_INCIDENT_ID); + when(incident.getConfiguration()).thenReturn(EXAMPLE_HIST_INCIDENT_CONFIGURATION); + when(incident.getIncidentMessage()).thenReturn(EXAMPLE_HIST_INCIDENT_MESSAGE); + when(incident.isOpen()).thenReturn(EXAMPLE_HIST_INCIDENT_STATE_OPEN); + when(incident.isDeleted()).thenReturn(EXAMPLE_HIST_INCIDENT_STATE_DELETED); + when(incident.isResolved()).thenReturn(EXAMPLE_HIST_INCIDENT_STATE_RESOLVED); + when(incident.getTenantId()).thenReturn(tenantId); + when(incident.getJobDefinitionId()).thenReturn(EXAMPLE_JOB_DEFINITION_ID); + when(incident.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HIST_INCIDENT_REMOVAL_TIME)); + when(incident.getRootProcessInstanceId()).thenReturn(EXAMPLE_HIST_INCIDENT_ROOT_PROC_INST_ID); + when(incident.getAnnotation()).thenReturn(EXAMPLE_USER_OPERATION_ANNOTATION); + + return incident; + } + + public static List createMockHistoricIncidents() { + List entries = new ArrayList<>(); + entries.add(createMockHistoricIncident()); + return entries; + } + + // case definition + public static List createMockCaseDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockCaseDefinition()); + return mocks; + } + + public static List createMockTwoCaseDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockCaseDefinition()); + mocks.add(createAnotherMockCaseDefinition()); + return mocks; + } + + public static MockCaseDefinitionBuilder mockCaseDefinition() { + return new MockCaseDefinitionBuilder() + .id(EXAMPLE_CASE_DEFINITION_ID) + .category(EXAMPLE_CASE_DEFINITION_CATEGORY) + .name(EXAMPLE_CASE_DEFINITION_NAME) + .key(EXAMPLE_CASE_DEFINITION_KEY) + .version(EXAMPLE_CASE_DEFINITION_VERSION) + .resource(EXAMPLE_CASE_DEFINITION_RESOURCE_NAME) + .diagram(EXAMPLE_CASE_DEFINITION_DIAGRAM_RESOURCE_NAME) + .deploymentId(EXAMPLE_DEPLOYMENT_ID); + } + + public static CaseDefinition createMockCaseDefinition() { + return mockCaseDefinition().build(); + } + + public static CaseDefinition createAnotherMockCaseDefinition() { + return mockCaseDefinition() + .id(ANOTHER_EXAMPLE_CASE_DEFINITION_ID) + .tenantId(ANOTHER_EXAMPLE_TENANT_ID) + .build(); + } + + // case instance + public static List createMockCaseInstances() { + List mocks = new ArrayList<>(); + mocks.add(createMockCaseInstance()); + return mocks; + } + + public static CaseInstance createMockCaseInstance() { + return createMockCaseInstance(EXAMPLE_TENANT_ID); + } + + public static CaseInstance createMockCaseInstance(String tenantId) { + CaseInstance mock = mock(CaseInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_CASE_INSTANCE_ID); + when(mock.getBusinessKey()).thenReturn(EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + when(mock.getCaseDefinitionId()).thenReturn(EXAMPLE_CASE_INSTANCE_CASE_DEFINITION_ID); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.isActive()).thenReturn(EXAMPLE_CASE_INSTANCE_IS_ACTIVE); + when(mock.isCompleted()).thenReturn(EXAMPLE_CASE_INSTANCE_IS_COMPLETED); + when(mock.isTerminated()).thenReturn(EXAMPLE_CASE_INSTANCE_IS_TERMINATED); + + return mock; + } + + // case execution + public static List createMockCaseExecutions() { + List mocks = new ArrayList<>(); + mocks.add(createMockCaseExecution()); + return mocks; + } + + public static CaseExecution createMockCaseExecution() { + return createMockCaseExecution(EXAMPLE_TENANT_ID); + } + + public static CaseExecution createMockCaseExecution(String tenantId) { + CaseExecution mock = mock(CaseExecution.class); + + when(mock.getId()).thenReturn(EXAMPLE_CASE_EXECUTION_ID); + when(mock.getCaseInstanceId()).thenReturn(EXAMPLE_CASE_EXECUTION_CASE_INSTANCE_ID); + when(mock.getParentId()).thenReturn(EXAMPLE_CASE_EXECUTION_PARENT_ID); + when(mock.getCaseDefinitionId()).thenReturn(EXAMPLE_CASE_EXECUTION_CASE_DEFINITION_ID); + when(mock.getActivityId()).thenReturn(EXAMPLE_CASE_EXECUTION_ACTIVITY_ID); + when(mock.getActivityName()).thenReturn(EXAMPLE_CASE_EXECUTION_ACTIVITY_NAME); + when(mock.getActivityType()).thenReturn(EXAMPLE_CASE_EXECUTION_ACTIVITY_TYPE); + when(mock.getActivityDescription()).thenReturn(EXAMPLE_CASE_EXECUTION_ACTIVITY_DESCRIPTION); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.isRequired()).thenReturn(EXAMPLE_CASE_EXECUTION_IS_REQUIRED); + when(mock.isActive()).thenReturn(EXAMPLE_CASE_EXECUTION_IS_ACTIVE); + when(mock.isEnabled()).thenReturn(EXAMPLE_CASE_EXECUTION_IS_ENABLED); + when(mock.isDisabled()).thenReturn(EXAMPLE_CASE_EXECUTION_IS_DISABLED); + + return mock; + } + + public static VariableMap createMockFormVariables() { + VariableMap mock = Variables.createVariables(); + mock.putValueTyped(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE); + return mock; + } + + public static List createMockFilters() { + List mocks = new ArrayList<>(); + mocks.add(createMockFilter(EXAMPLE_FILTER_ID)); + mocks.add(createMockFilter(ANOTHER_EXAMPLE_FILTER_ID)); + return mocks; + } + + public static Filter createMockFilter() { + return createMockFilter(EXAMPLE_FILTER_ID); + } + + public static Filter createMockFilter(String id) { + return createMockFilter(id, EXAMPLE_FILTER_QUERY); + } + + public static Filter createMockFilter(String id, Query query) { + Filter mock = mockFilter() + .id(id) + .resourceType(EXAMPLE_FILTER_RESOURCE_TYPE) + .name(EXAMPLE_FILTER_NAME) + .owner(EXAMPLE_FILTER_OWNER) + .query(query) + .properties(EXAMPLE_FILTER_PROPERTIES) + .build(); + + doThrow(new NotValidException("Name must not be null")) + .when(mock).setName(null); + doThrow(new NotValidException("Name must not be empty")) + .when(mock).setName(""); + doThrow(new NotValidException("Query must not be null")) + .when(mock).setQuery(null); + + return mock; + } + + public static MockFilterBuilder mockFilter() { + return new MockFilterBuilder() + .id(EXAMPLE_FILTER_ID) + .resourceType(EXAMPLE_FILTER_RESOURCE_TYPE) + .name(EXAMPLE_FILTER_NAME) + .owner(EXAMPLE_FILTER_OWNER) + .query(EXAMPLE_FILTER_QUERY) + .properties(EXAMPLE_FILTER_PROPERTIES); + } + + public static FilterQuery createMockFilterQuery() { + List mockFilters = createMockFilters(); + + FilterQuery query = mock(FilterQuery.class); + + when(query.list()).thenReturn(mockFilters); + when(query.count()).thenReturn((long) mockFilters.size()); + when(query.filterId(any())).thenReturn(query); + when(query.singleResult()).thenReturn(mockFilters.get(0)); + + FilterQuery nonExistingQuery = mock(FilterQuery.class); + when(query.filterId(NON_EXISTING_ID)).thenReturn(nonExistingQuery); + when(nonExistingQuery.singleResult()).thenReturn(null); + + return query; + + } + + public static MetricsQuery createMockMeterQuery() { + + MetricsQuery query = mock(MetricsQuery.class); + + when(query.name(any())).thenReturn(query); + when(query.reporter(any())).thenReturn(query); + when(query.limit(anyInt())).thenReturn(query); + when(query.offset(anyInt())).thenReturn(query); + when(query.startDate(any())).thenReturn(query); + when(query.endDate(any())).thenReturn(query); + + return query; + + } + + public static List createMockMetricIntervalResult() { + List metrics = new ArrayList<>(); + + MetricIntervalEntity entity1 = new MetricIntervalEntity(new Date(15 * 60 * 1000 * 1), EXAMPLE_METRICS_NAME, EXAMPLE_METRICS_REPORTER); + entity1.setValue(21); + + MetricIntervalEntity entity2 = new MetricIntervalEntity(new Date(15 * 60 * 1000 * 2), EXAMPLE_METRICS_NAME, EXAMPLE_METRICS_REPORTER); + entity2.setValue(22); + + MetricIntervalEntity entity3 = new MetricIntervalEntity(new Date(15 * 60 * 1000 * 3), EXAMPLE_METRICS_NAME, EXAMPLE_METRICS_REPORTER); + entity3.setValue(23); + + metrics.add(entity3); + metrics.add(entity2); + metrics.add(entity1); + + return metrics; + } + + // decision definition + public static List createMockDecisionDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockDecisionDefinition()); + return mocks; + } + + public static List createMockTwoDecisionDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockDecisionDefinition()); + mocks.add(createAnotherMockDecisionDefinition()); + return mocks; + } + + public static MockDecisionDefinitionBuilder mockDecisionDefinition() { + MockDecisionDefinitionBuilder builder = new MockDecisionDefinitionBuilder(); + + return builder + .id(EXAMPLE_DECISION_DEFINITION_ID) + .category(EXAMPLE_DECISION_DEFINITION_CATEGORY) + .name(EXAMPLE_DECISION_DEFINITION_NAME) + .key(EXAMPLE_DECISION_DEFINITION_KEY) + .version(EXAMPLE_DECISION_DEFINITION_VERSION) + .resource(EXAMPLE_DECISION_DEFINITION_RESOURCE_NAME) + .diagram(EXAMPLE_DECISION_DEFINITION_DIAGRAM_RESOURCE_NAME) + .deploymentId(EXAMPLE_DEPLOYMENT_ID) + .decisionRequirementsDefinitionId(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID) + .decisionRequirementsDefinitionKey(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + } + + public static DecisionDefinition createMockDecisionDefinition() { + return mockDecisionDefinition().build(); + } + + public static DecisionDefinition createAnotherMockDecisionDefinition() { + return mockDecisionDefinition() + .id(ANOTHER_EXAMPLE_DECISION_DEFINITION_ID) + .tenantId(ANOTHER_EXAMPLE_TENANT_ID) + .build(); + } + + // decision requirements definition + public static MockDecisionRequirementsDefinitionBuilder mockDecisionRequirementsDefinition() { + MockDecisionRequirementsDefinitionBuilder builder = new MockDecisionRequirementsDefinitionBuilder(); + + return builder + .id(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID) + .category(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_CATEGORY) + .name(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_NAME) + .key(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY) + .version(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_VERSION) + .resource(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_RESOURCE_NAME) + .diagram(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_DIAGRAM_RESOURCE_NAME) + .deploymentId(EXAMPLE_DEPLOYMENT_ID); + } + + public static DecisionRequirementsDefinition createMockDecisionRequirementsDefinition() { + return mockDecisionRequirementsDefinition().build(); + } + + public static DecisionRequirementsDefinition createAnotherMockDecisionRequirementsDefinition() { + return mockDecisionRequirementsDefinition() + .id(ANOTHER_EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID) + .tenantId(ANOTHER_EXAMPLE_TENANT_ID) + .build(); + } + + public static List createMockDecisionRequirementsDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockDecisionRequirementsDefinition()); + return mocks; + } + + public static List createMockTwoDecisionRequirementsDefinitions() { + List mocks = new ArrayList<>(); + mocks.add(createMockDecisionRequirementsDefinition()); + mocks.add(createAnotherMockDecisionRequirementsDefinition()); + return mocks; + } + + // Historic job log + + public static List createMockHistoricJobLogs() { + List mocks = new ArrayList<>(); + mocks.add(createMockHistoricJobLog()); + return mocks; + } + + public static HistoricJobLog createMockHistoricJobLog() { + return createMockHistoricJobLog(EXAMPLE_TENANT_ID); + } + + public static HistoricJobLog createMockHistoricJobLog(String tenantId) { + HistoricJobLog mock = mock(HistoricJobLog.class); + + when(mock.getId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_ID); + when(mock.getTimestamp()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_JOB_LOG_TIMESTAMP)); + when(mock.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_JOB_LOG_REMOVAL_TIME)); + + when(mock.getJobId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_JOB_ID); + when(mock.getJobDueDate()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_JOB_LOG_JOB_DUE_DATE)); + when(mock.getJobRetries()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_JOB_RETRIES); + when(mock.getJobPriority()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_JOB_PRIORITY); + when(mock.getJobExceptionMessage()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_JOB_EXCEPTION_MSG); + + when(mock.getJobDefinitionId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_ID); + when(mock.getJobDefinitionType()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_TYPE); + when(mock.getJobDefinitionConfiguration()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_CONFIG); + + when(mock.getActivityId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_ACTIVITY_ID); + when(mock.getFailedActivityId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_FAILED_ACTIVITY_ID); + when(mock.getExecutionId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_EXECUTION_ID); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_PROC_INST_ID); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_ID); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_KEY); + when(mock.getDeploymentId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_DEPLOYMENT_ID); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_ROOT_PROC_INST_ID); + when(mock.getHostname()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_HOSTNAME); + when(mock.getBatchId()).thenReturn(EXAMPLE_BATCH_ID); + + when(mock.isCreationLog()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_IS_CREATION_LOG); + when(mock.isFailureLog()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_IS_FAILURE_LOG); + when(mock.isSuccessLog()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_IS_SUCCESS_LOG); + when(mock.isDeletionLog()).thenReturn(EXAMPLE_HISTORIC_JOB_LOG_IS_DELETION_LOG); + + return mock; + } + + // Historic decision instance + + public static List createMockHistoricDecisionInstances() { + List mockList = new ArrayList<>(); + mockList.add(createMockHistoricDecisionInstance()); + return mockList; + } + + public static HistoricDecisionInstance createMockHistoricDecisionInstanceBase() { + return createMockHistoricDecisionInstanceBase(EXAMPLE_TENANT_ID); + } + + public static HistoricDecisionInstance createMockHistoricDecisionInstanceBase(String tenantId) { + HistoricDecisionInstance mock = mock(HistoricDecisionInstance.class); + + when(mock.getId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + when(mock.getDecisionDefinitionId()).thenReturn(EXAMPLE_DECISION_DEFINITION_ID); + when(mock.getDecisionDefinitionKey()).thenReturn(EXAMPLE_DECISION_DEFINITION_KEY); + when(mock.getDecisionDefinitionName()).thenReturn(EXAMPLE_DECISION_DEFINITION_NAME); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_PROCESS_DEFINITION_KEY); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_PROCESS_INSTANCE_ID); + when(mock.getCaseDefinitionId()).thenReturn(EXAMPLE_CASE_DEFINITION_ID); + when(mock.getCaseDefinitionKey()).thenReturn(EXAMPLE_CASE_DEFINITION_KEY); + when(mock.getCaseInstanceId()).thenReturn(EXAMPLE_CASE_INSTANCE_ID); + when(mock.getActivityId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_ID); + when(mock.getActivityInstanceId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_INSTANCE_ID); + when(mock.getEvaluationTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATION_TIME)); + when(mock.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_DECISION_INSTANCE_REMOVAL_TIME)); + when(mock.getUserId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_USER_ID); + when(mock.getCollectResultValue()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_COLLECT_RESULT_VALUE); + when(mock.getRootDecisionInstanceId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + when(mock.getRootProcessInstanceId()).thenReturn(EXAMPLE_ROOT_HISTORIC_PROCESS_INSTANCE_ID); + when(mock.getDecisionRequirementsDefinitionId()).thenReturn(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + when(mock.getDecisionRequirementsDefinitionKey()).thenReturn(EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + when(mock.getTenantId()).thenReturn(tenantId); + + return mock; + } + + public static HistoricDecisionInstance createMockHistoricDecisionInstance() { + HistoricDecisionInstance mock = createMockHistoricDecisionInstanceBase(); + when(mock.getInputs()).thenThrow(new ProcessEngineException("ENGINE-03060 The input instances for the historic decision instance are not fetched. You must call 'includeInputs()' on the query to enable fetching.")); + when(mock.getOutputs()).thenThrow(new ProcessEngineException("ENGINE-03061 The output instances for the historic decision instance are not fetched. You must call 'includeOutputs()' on the query to enable fetching.")); + return mock; + } + + public static HistoricDecisionInstance createMockHistoricDecisionInstanceWithInputs() { + List inputs = createMockHistoricDecisionInputInstances(); + + HistoricDecisionInstance mock = createMockHistoricDecisionInstanceBase(); + when(mock.getInputs()).thenReturn(inputs); + when(mock.getOutputs()).thenThrow(new ProcessEngineException("ENGINE-03061 The output instances for the historic decision instance are not fetched. You must call 'includeOutputs()' on the query to enable fetching.")); + return mock; + } + + public static HistoricDecisionInstance createMockHistoricDecisionInstanceWithOutputs() { + List outputs = createMockHistoricDecisionOutputInstances(); + + HistoricDecisionInstance mock = createMockHistoricDecisionInstanceBase(); + when(mock.getInputs()).thenThrow(new ProcessEngineException("ENGINE-03060 The input instances for the historic decision instance are not fetched. You must call 'includeInputs()' on the query to enable fetching.")); + when(mock.getOutputs()).thenReturn(outputs); + return mock; + } + + public static HistoricDecisionInstance createMockHistoricDecisionInstanceWithInputsAndOutputs() { + List inputs = createMockHistoricDecisionInputInstances(); + List outputs = createMockHistoricDecisionOutputInstances(); + + HistoricDecisionInstance mock = createMockHistoricDecisionInstanceBase(); + when(mock.getInputs()).thenReturn(inputs); + when(mock.getOutputs()).thenReturn(outputs); + return mock; + } + + public static List createMockHistoricDecisionInputInstances() { + List mockInputs = new ArrayList<>(); + mockInputs.add(createMockHistoricDecisionInput(EXAMPLE_HISTORIC_DECISION_STRING_VALUE)); + mockInputs.add(createMockHistoricDecisionInput(EXAMPLE_HISTORIC_DECISION_BYTE_ARRAY_VALUE)); + mockInputs.add(createMockHistoricDecisionInput(EXAMPLE_HISTORIC_DECISION_SERIALIZED_VALUE)); + return mockInputs; + } + + public static HistoricDecisionInputInstance createMockHistoricDecisionInput(TypedValue typedValue) { + HistoricDecisionInputInstance input = mock(HistoricDecisionInputInstance.class); + when(input.getId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_ID); + when(input.getDecisionInstanceId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + when(input.getClauseId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CLAUSE_ID); + when(input.getClauseName()).thenReturn(EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CLAUSE_NAME); + when(input.getTypedValue()).thenReturn(typedValue); + when(input.getErrorMessage()).thenReturn(null); + when(input.getCreateTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CREATE_TIME)); + when(input.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_REMOVAL_TIME)); + when(input.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INPUT_ROOT_PROCESS_INSTANCE_ID); + + return input; + } + + public static List createMockHistoricDecisionOutputInstances() { + List mockOutputs = new ArrayList<>(); + mockOutputs.add(createMockHistoricDecisionOutput(EXAMPLE_HISTORIC_DECISION_STRING_VALUE)); + mockOutputs.add(createMockHistoricDecisionOutput(EXAMPLE_HISTORIC_DECISION_BYTE_ARRAY_VALUE)); + mockOutputs.add(createMockHistoricDecisionOutput(EXAMPLE_HISTORIC_DECISION_SERIALIZED_VALUE)); + return mockOutputs; + } + + public static HistoricDecisionOutputInstance createMockHistoricDecisionOutput(TypedValue typedValue) { + HistoricDecisionOutputInstance output = mock(HistoricDecisionOutputInstance.class); + when(output.getId()).thenReturn(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_ID); + when(output.getDecisionInstanceId()).thenReturn(EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + when(output.getClauseId()).thenReturn(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CLAUSE_ID); + when(output.getClauseName()).thenReturn(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CLAUSE_NAME); + when(output.getRuleId()).thenReturn(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_RULE_ID); + when(output.getRuleOrder()).thenReturn(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_RULE_ORDER); + when(output.getVariableName()).thenReturn(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_VARIABLE_NAME); + when(output.getTypedValue()).thenReturn(typedValue); + when(output.getErrorMessage()).thenReturn(null); + when(output.getCreateTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CREATE_TIME)); + when(output.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_REMOVAL_TIME)); + when(output.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_DECISION_OUTPUT_ROOT_PROCESS_INSTANCE_ID); + return output; + } + + // external task + + public static MockExternalTaskBuilder mockExternalTask() { + return new MockExternalTaskBuilder() + .id(EXTERNAL_TASK_ID) + .activityId(EXAMPLE_ACTIVITY_ID) + .activityInstanceId(EXAMPLE_ACTIVITY_INSTANCE_ID) + .errorMessage(EXTERNAL_TASK_ERROR_MESSAGE) + .executionId(EXAMPLE_EXECUTION_ID) + .lockExpirationTime(DateTimeUtil.parseDate(EXTERNAL_TASK_LOCK_EXPIRATION_TIME)) + .createTime(DateTimeUtil.parseDate(EXTERNAL_TASK_CREATE_TIME)) + .processDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID) + .processDefinitionKey(EXAMPLE_PROCESS_DEFINITION_KEY) + .processDefinitionVersionTag(EXAMPLE_PROCESS_DEFINITION_VERSION_TAG) + .processInstanceId(EXAMPLE_PROCESS_INSTANCE_ID) + .retries(EXTERNAL_TASK_RETRIES) + .suspended(EXTERNAL_TASK_SUSPENDED) + .topicName(EXTERNAL_TASK_TOPIC_NAME) + .workerId(EXTERNAL_TASK_WORKER_ID) + .tenantId(EXAMPLE_TENANT_ID) + .priority(EXTERNAL_TASK_PRIORITY) + .businessKey(EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + + } + + public static ExternalTask createMockExternalTask() { + return mockExternalTask().buildExternalTask(); + } + + public static LockedExternalTask createMockLockedExternalTask() { + return mockExternalTask() + .variable(EXAMPLE_VARIABLE_INSTANCE_NAME, EXAMPLE_PRIMITIVE_VARIABLE_VALUE) + .buildLockedExternalTask(); + } + + public static List createMockExternalTasks() { + List mocks = new ArrayList<>(); + mocks.add(createMockExternalTask()); + return mocks; + } + + public static MockDecisionResultBuilder mockDecisionResult() { + return new MockDecisionResultBuilder() + .resultEntries() + .entry(EXAMPLE_DECISION_OUTPUT_KEY, EXAMPLE_DECISION_OUTPUT_VALUE) + .endResultEntries(); + } + + public static DmnDecisionResult createMockDecisionResult() { + return mockDecisionResult().build(); + } + + public static MockBatchBuilder mockBatch() { + return new MockBatchBuilder() + .id(EXAMPLE_BATCH_ID) + .type(EXAMPLE_BATCH_TYPE) + .totalJobs(EXAMPLE_BATCH_TOTAL_JOBS) + .jobsCreated(EXAMPLE_BATCH_JOBS_CREATED) + .batchJobsPerSeed(EXAMPLE_BATCH_JOBS_PER_SEED) + .invocationsPerBatchJob(EXAMPLE_INVOCATIONS_PER_BATCH_JOB) + .seedJobDefinitionId(EXAMPLE_SEED_JOB_DEFINITION_ID) + .monitorJobDefinitionId(EXAMPLE_MONITOR_JOB_DEFINITION_ID) + .batchJobDefinitionId(EXAMPLE_BATCH_JOB_DEFINITION_ID) + .suspended() + .createUserId(EXAMPLE_USER_ID) + .startTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_BATCH_START_TIME)) + .executionStartTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_BATCH_START_TIME)) + .tenantId(EXAMPLE_TENANT_ID); + } + + public static Batch createMockBatch() { + return mockBatch().build(); + } + + public static List createMockBatches() { + List mockList = new ArrayList<>(); + mockList.add(createMockBatch()); + return mockList; + } + + public static MockHistoricBatchBuilder mockHistoricBatch() { + return new MockHistoricBatchBuilder() + .id(EXAMPLE_BATCH_ID) + .type(EXAMPLE_BATCH_TYPE) + .totalJobs(EXAMPLE_BATCH_TOTAL_JOBS) + .batchJobsPerSeed(EXAMPLE_BATCH_JOBS_PER_SEED) + .invocationsPerBatchJob(EXAMPLE_INVOCATIONS_PER_BATCH_JOB) + .seedJobDefinitionId(EXAMPLE_SEED_JOB_DEFINITION_ID) + .monitorJobDefinitionId(EXAMPLE_MONITOR_JOB_DEFINITION_ID) + .batchJobDefinitionId(EXAMPLE_BATCH_JOB_DEFINITION_ID) + .tenantId(EXAMPLE_TENANT_ID) + .createUserId(EXAMPLE_USER_ID) + .startTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_BATCH_START_TIME)) + .executionStartTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_BATCH_START_TIME)) + .endTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_BATCH_END_TIME)) + .removalTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_BATCH_REMOVAL_TIME)); + } + + public static HistoricBatch createMockHistoricBatch() { + return mockHistoricBatch().build(); + } + + public static List createMockHistoricBatches() { + List mockList = new ArrayList<>(); + mockList.add(createMockHistoricBatch()); + return mockList; + } + + public static MockBatchStatisticsBuilder mockBatchStatistics() { + return new MockBatchStatisticsBuilder() + .id(EXAMPLE_BATCH_ID) + .type(EXAMPLE_BATCH_TYPE) + .size(EXAMPLE_BATCH_TOTAL_JOBS) + .jobsCreated(EXAMPLE_BATCH_JOBS_CREATED) + .batchJobsPerSeed(EXAMPLE_BATCH_JOBS_PER_SEED) + .invocationsPerBatchJob(EXAMPLE_INVOCATIONS_PER_BATCH_JOB) + .seedJobDefinitionId(EXAMPLE_SEED_JOB_DEFINITION_ID) + .monitorJobDefinitionId(EXAMPLE_MONITOR_JOB_DEFINITION_ID) + .batchJobDefinitionId(EXAMPLE_BATCH_JOB_DEFINITION_ID) + .tenantId(EXAMPLE_TENANT_ID) + .createUserId(EXAMPLE_USER_ID) + .suspended() + .startTime(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_BATCH_START_TIME)) + .remainingJobs(EXAMPLE_BATCH_REMAINING_JOBS) + .completedJobs(EXAMPLE_BATCH_COMPLETED_JOBS) + .failedJobs(EXAMPLE_BATCH_FAILED_JOBS); + } + + public static BatchStatistics createMockBatchStatistics() { + return mockBatchStatistics().build(); + } + + public static List createMockBatchStatisticsList() { + ArrayList mockList = new ArrayList<>(); + mockList.add(createMockBatchStatistics()); + return mockList; + } + + + public static MessageCorrelationResult createMessageCorrelationResult(MessageCorrelationResultType type) { + MessageCorrelationResult result = mock(MessageCorrelationResult.class); + when(result.getResultType()).thenReturn(type); + + Execution ex = createMockExecution(); + when(result.getExecution()).thenReturn(ex); + + ProcessInstance instance = createMockInstance(); + when(result.getProcessInstance()).thenReturn(instance); + + return result; + } + + public static MessageCorrelationResultWithVariables createMessageCorrelationResultWithVariables(MessageCorrelationResultType type) { + MessageCorrelationResultWithVariables result = mock(MessageCorrelationResultWithVariables.class); + when(result.getResultType()).thenReturn(type); + + Execution ex = createMockExecution(); + when(result.getExecution()).thenReturn(ex); + + ProcessInstance instance = createMockInstance(); + when(result.getProcessInstance()).thenReturn(instance); + + when(result.getVariables()).thenReturn(createMockSerializedVariables()); + return result; + } + + public static List createMessageCorrelationResultList(MessageCorrelationResultType type) { + List list = new ArrayList<>(); + list.add(createMessageCorrelationResult(type)); + list.add(createMessageCorrelationResult(type)); + return list; + } + + public static List createMockHistoricDecisionStatistics() { + HistoricDecisionInstanceStatistics statistics = mock(HistoricDecisionInstanceStatistics.class); + + when(statistics.getDecisionDefinitionKey()).thenReturn(EXAMPLE_DECISION_DEFINITION_KEY); + when(statistics.getEvaluations()).thenReturn(1); + + + HistoricDecisionInstanceStatistics anotherStatistics = mock(HistoricDecisionInstanceStatistics.class); + + when(anotherStatistics.getDecisionDefinitionKey()).thenReturn(ANOTHER_DECISION_DEFINITION_KEY); + when(anotherStatistics.getEvaluations()).thenReturn(2); + + List decisionResults = new ArrayList<>(); + decisionResults.add(statistics); + decisionResults.add(anotherStatistics); + + return decisionResults; + } + + // historic external task log + public static List createMockHistoricExternalTaskLogs() { + List mocks = new ArrayList<>(); + mocks.add(createMockHistoricExternalTaskLog()); + return mocks; + } + + public static HistoricExternalTaskLog createMockHistoricExternalTaskLog() { + return createMockHistoricExternalTaskLog(EXAMPLE_TENANT_ID); + } + + public static HistoricExternalTaskLog createMockHistoricExternalTaskLog(String tenantId) { + HistoricExternalTaskLog mock = mock(HistoricExternalTaskLog.class); + + when(mock.getId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID); + when(mock.getTimestamp()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TIMESTAMP)); + when(mock.getRemovalTime()).thenReturn(DateTimeUtil.parseDate(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_REMOVAL_TIME)); + + when(mock.getExternalTaskId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXTERNAL_TASK_ID); + when(mock.getTopicName()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TOPIC_NAME); + when(mock.getWorkerId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_WORKER_ID); + when(mock.getRetries()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_RETRIES); + when(mock.getPriority()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PRIORITY); + when(mock.getErrorMessage()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ERROR_MSG); + + when(mock.getActivityId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_ID); + when(mock.getActivityInstanceId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_INSTANCE_ID); + when(mock.getExecutionId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXECUTION_ID); + when(mock.getProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_INST_ID); + when(mock.getProcessDefinitionId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_ID); + when(mock.getProcessDefinitionKey()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_KEY); + when(mock.getTenantId()).thenReturn(tenantId); + when(mock.getRootProcessInstanceId()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ROOT_PROC_INST_ID); + + when(mock.isCreationLog()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_CREATION_LOG); + when(mock.isFailureLog()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_FAILURE_LOG); + when(mock.isSuccessLog()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_SUCCESS_LOG); + when(mock.isDeletionLog()).thenReturn(EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_DELETION_LOG); + + return mock; + } + + public static SetJobRetriesByJobsAsyncBuilder createMockSetJobRetriesByJobsAsyncBuilder(ManagementService mockManagementService) { + Batch batchEntity = MockProvider.createMockBatch(); + SetJobRetriesByJobsAsyncBuilder mockSetJobRetriesByJobsAsyncBuilder = mock(SetJobRetriesByJobsAsyncBuilder.class); + when(mockManagementService.setJobRetriesByJobsAsync(anyInt())).thenReturn(mockSetJobRetriesByJobsAsyncBuilder); + when(mockSetJobRetriesByJobsAsyncBuilder.jobIds(any())).thenReturn(mockSetJobRetriesByJobsAsyncBuilder); + when(mockSetJobRetriesByJobsAsyncBuilder.jobQuery(any())).thenReturn(mockSetJobRetriesByJobsAsyncBuilder); + when(mockSetJobRetriesByJobsAsyncBuilder.dueDate(any())).thenReturn(mockSetJobRetriesByJobsAsyncBuilder); + when(mockSetJobRetriesByJobsAsyncBuilder.executeAsync()).thenReturn(batchEntity); + return mockSetJobRetriesByJobsAsyncBuilder; + } + + public static SetJobRetriesByProcessAsyncBuilder createMockSetJobRetriesByProcessAsyncBuilder(ManagementService mockManagementService) { + Batch batchEntity = MockProvider.createMockBatch(); + SetJobRetriesByProcessAsyncBuilder mockSetJobRetriesByProcessAsyncBuilder = mock(SetJobRetriesByProcessAsyncBuilder.class); + when(mockManagementService.setJobRetriesByProcessAsync(anyInt())).thenReturn(mockSetJobRetriesByProcessAsyncBuilder); + when(mockSetJobRetriesByProcessAsyncBuilder.processInstanceIds(any())).thenReturn(mockSetJobRetriesByProcessAsyncBuilder); + when(mockSetJobRetriesByProcessAsyncBuilder.processInstanceQuery(any())).thenReturn(mockSetJobRetriesByProcessAsyncBuilder); + when(mockSetJobRetriesByProcessAsyncBuilder.historicProcessInstanceQuery(any())).thenReturn(mockSetJobRetriesByProcessAsyncBuilder); + when(mockSetJobRetriesByProcessAsyncBuilder.dueDate(any())).thenReturn(mockSetJobRetriesByProcessAsyncBuilder); + when(mockSetJobRetriesByProcessAsyncBuilder.executeAsync()).thenReturn(batchEntity); + return mockSetJobRetriesByProcessAsyncBuilder; + } + + public static SetJobRetriesBuilder createMockSetJobRetriesBuilder(ManagementService mockManagementService) { + SetJobRetriesBuilder mockSetJobRetriesBuilder = mock(SetJobRetriesBuilder.class); + when(mockManagementService.setJobRetries(anyInt())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.jobId(any())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.jobIds(any())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.jobDefinitionId(any())).thenReturn(mockSetJobRetriesBuilder); + when(mockSetJobRetriesBuilder.dueDate(any())).thenReturn(mockSetJobRetriesBuilder); + return mockSetJobRetriesBuilder; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockTaskBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockTaskBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..e5e70468ba83f678bee92cd30ee1e236eb74501b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockTaskBuilder.java @@ -0,0 +1,218 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Date; + +import org.camunda.bpm.engine.form.CamundaFormRef; +import org.camunda.bpm.engine.impl.form.CamundaFormRefImpl; +import org.camunda.bpm.engine.task.DelegationState; +import org.camunda.bpm.engine.task.Task; + +public class MockTaskBuilder { + + private String id; + private String name; + private String assignee; + private Date createTime; + private Date lastUpdated; + private Date dueDate; + private Date followUpDate; + private DelegationState delegationState; + private String description; + private String executionId; + private String owner; + private String parentTaskId; + private int priority; + private String processDefinitionId; + private String processInstanceId; + private String taskDefinitionKey; + private String caseDefinitionId; + private String caseInstanceId; + private String caseExecutionId; + private String formKey; + private CamundaFormRef camundaFormRef; + private String tenantId; + private boolean hasAttachment; + + private boolean hasComment; + + + + private String taskState; + + public MockTaskBuilder id(String id) { + this.id = id; + return this; + } + + public MockTaskBuilder name(String name) { + this.name = name; + return this; + } + + public MockTaskBuilder assignee(String assignee) { + this.assignee = assignee; + return this; + } + + public MockTaskBuilder createTime(Date createTime) { + this.createTime = createTime; + return this; + } + + public MockTaskBuilder lastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + return this; + } + + public MockTaskBuilder dueDate(Date dueDate) { + this.dueDate = dueDate; + return this; + } + + public MockTaskBuilder followUpDate(Date followUpDate) { + this.followUpDate = followUpDate; + return this; + } + + public MockTaskBuilder delegationState(DelegationState delegationState) { + this.delegationState = delegationState; + return this; + } + + public MockTaskBuilder description(String description) { + this.description = description; + return this; + } + + public MockTaskBuilder executionId(String executionId) { + this.executionId = executionId; + return this; + } + + public MockTaskBuilder owner(String owner) { + this.owner = owner; + return this; + } + + public MockTaskBuilder parentTaskId(String parentTaskId) { + this.parentTaskId = parentTaskId; + return this; + } + + public MockTaskBuilder priority(int priority) { + this.priority = priority; + return this; + } + + public MockTaskBuilder processDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + return this; + } + + public MockTaskBuilder processInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + return this; + } + + public MockTaskBuilder taskDefinitionKey(String taskDefinitionKey) { + this.taskDefinitionKey = taskDefinitionKey; + return this; + } + + public MockTaskBuilder caseDefinitionId(String caseDefinitionId) { + this.caseDefinitionId = caseDefinitionId; + return this; + } + + public MockTaskBuilder caseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + return this; + } + + public MockTaskBuilder caseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + return this; + } + + public MockTaskBuilder formKey(String exampleFormKey) { + this.formKey = exampleFormKey; + return this; + } + + public MockTaskBuilder camundaFormRef(String key, String binding, Integer version) { + CamundaFormRefImpl camundaFormRef = new CamundaFormRefImpl(key, binding); + camundaFormRef.setVersion(version); + this.camundaFormRef = camundaFormRef; + return this; + } + + public MockTaskBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockTaskBuilder taskState(String taskState) { + this.taskState = taskState; + return this; + } + + public MockTaskBuilder hasAttachment(boolean hasAttachment) { + this.hasAttachment = hasAttachment; + return this; + } + + public MockTaskBuilder hasComment(boolean hasComment) { + this.hasComment = hasComment; + return this; + } + + public Task build() { + Task mockTask = mock(Task.class); + when(mockTask.getId()).thenReturn(id); + when(mockTask.getName()).thenReturn(name); + when(mockTask.getAssignee()).thenReturn(assignee); + when(mockTask.getCreateTime()).thenReturn(createTime); + when(mockTask.getLastUpdated()).thenReturn(lastUpdated); + when(mockTask.getDueDate()).thenReturn(dueDate); + when(mockTask.getFollowUpDate()).thenReturn(followUpDate); + when(mockTask.getDelegationState()).thenReturn(delegationState); + when(mockTask.getDescription()).thenReturn(description); + when(mockTask.getExecutionId()).thenReturn(executionId); + when(mockTask.getOwner()).thenReturn(owner); + when(mockTask.getParentTaskId()).thenReturn(parentTaskId); + when(mockTask.getPriority()).thenReturn(priority); + when(mockTask.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(mockTask.getProcessInstanceId()).thenReturn(processInstanceId); + when(mockTask.getTaskDefinitionKey()).thenReturn(taskDefinitionKey); + when(mockTask.getCaseDefinitionId()).thenReturn(caseDefinitionId); + when(mockTask.getCaseInstanceId()).thenReturn(caseInstanceId); + when(mockTask.getCaseExecutionId()).thenReturn(caseExecutionId); + when(mockTask.getFormKey()).thenReturn(formKey); + when(mockTask.getCamundaFormRef()).thenReturn(camundaFormRef); + when(mockTask.getTenantId()).thenReturn(tenantId); + when(mockTask.getTaskState()).thenReturn(taskState); + when(mockTask.hasAttachment()).thenReturn(hasAttachment); + when(mockTask.hasComment()).thenReturn(hasComment); + return mockTask; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockUserBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockUserBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..8d5909ea4bdc2375795a7fb4466df296a70967b5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockUserBuilder.java @@ -0,0 +1,68 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.identity.User; + +public class MockUserBuilder { + + protected String id; + protected String firstName; + protected String lastName; + protected String email; + protected String password; + + public MockUserBuilder id(String id) { + this.id = id; + return this; + } + + public MockUserBuilder firstName(String firstName) { + this.firstName = firstName; + return this; + } + + public MockUserBuilder lastName(String lastName) { + this.lastName = lastName; + return this; + } + + public MockUserBuilder email(String email) { + this.email = email; + return this; + } + + public MockUserBuilder password(String password) { + this.password = password; + return this; + } + + @SuppressWarnings("unchecked") + public User build() { + User user = mock(User.class); + when(user.getId()).thenReturn(id); + when(user.getFirstName()).thenReturn(firstName); + when(user.getLastName()).thenReturn(lastName); + when(user.getEmail()).thenReturn(email); + when(user.getPassword()).thenReturn(password); + return user; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockVariableInstanceBuilder.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockVariableInstanceBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..9f50a9e0858417e390d346bffab080f70f5c8fea --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/MockVariableInstanceBuilder.java @@ -0,0 +1,226 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.camunda.bpm.engine.impl.persistence.entity.VariableInstanceEntity; +import org.camunda.bpm.engine.runtime.VariableInstance; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.TypedValue; + +/** + * Creates variable mocks and simultaneously provides a ResponseSpecification + * to assert a result of this mock in json; expectations can be overriden using the + * methods {@link JsonSpec#setMatcher(String, org.hamcrest.Matcher)} and + * {@link JsonSpec#setEnclosedJsonSpec(String, JsonSpec)}. + * + * @author Thorben Lindhauer + */ +public class MockVariableInstanceBuilder { + + protected String id; + protected String name; + protected TypedValue typedValue; + protected String processDefinitionId; + protected String processInstanceId; + protected String executionId; + protected String caseInstanceId; + protected String caseExecutionId; + protected String taskId; + protected String batchId; + protected String activityInstanceId; + protected String tenantId; + protected String errorMessage; + + public MockVariableInstanceBuilder id(String id) { + this.id = id; + return this; + } + + public MockVariableInstanceBuilder name(String name) { + this.name = name; + return this; + } + + public MockVariableInstanceBuilder typedValue(TypedValue value) { + this.typedValue = value; + return this; + } + + public MockVariableInstanceBuilder processDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; + return this; + } + + public MockVariableInstanceBuilder processInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + return this; + } + + public MockVariableInstanceBuilder executionId(String executionId) { + this.executionId = executionId; + return this; + } + + public MockVariableInstanceBuilder caseInstanceId(String caseInstanceId) { + this.caseInstanceId = caseInstanceId; + return this; + } + + public MockVariableInstanceBuilder caseExecutionId(String caseExecutionId) { + this.caseExecutionId = caseExecutionId; + return this; + } + + public MockVariableInstanceBuilder taskId(String taskId) { + this.taskId = taskId; + return this; + } + + public MockVariableInstanceBuilder batchId(String batchId) { + this.batchId = batchId; + return this; + } + + public MockVariableInstanceBuilder activityInstanceId(String activityInstanceId) { + this.activityInstanceId = activityInstanceId; + return this; + } + + public MockVariableInstanceBuilder tenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + public MockVariableInstanceBuilder errorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public Object getValue() { + return typedValue.getValue(); + } + + public TypedValue getTypedValue() { + return typedValue; + } + + public String getProcessDefinitionId() { + return processDefinitionId; + } + + public String getProcessInstanceId() { + return processInstanceId; + } + + public String getExecutionId() { + return executionId; + } + + public String getCaseInstanceId() { + return caseInstanceId; + } + + public String getCaseExecutionId() { + return caseExecutionId; + } + + public String getTaskId() { + return taskId; + } + + public String getBatchId() { + return batchId; + } + + public String getActivityInstanceId() { + return activityInstanceId; + } + + public String getTenantId() { + return tenantId; + } + + public String getErrorMessage() { + return errorMessage; + } + + public String getTypeName() { + return typedValue.getType().getName(); + } + + public VariableInstance build() { + VariableInstance mockVariable = mock(VariableInstance.class); + return build(mockVariable); + } + + public VariableInstanceEntity buildEntity() { + VariableInstanceEntity mockVariable = mock(VariableInstanceEntity.class); + if (taskId != null) { + when(mockVariable.getVariableScopeId()).thenReturn(taskId); + } + else if (executionId != null) { + when(mockVariable.getVariableScopeId()).thenReturn(executionId); + } + else { + when(mockVariable.getVariableScopeId()).thenReturn(caseExecutionId); + } + return build(mockVariable); + } + + protected T build(T mockVariable) { + when(mockVariable.getId()).thenReturn(id); + when(mockVariable.getName()).thenReturn(name); + when(mockVariable.getTypeName()).thenReturn(typedValue.getType().getName()); + + if (ObjectValue.class.isAssignableFrom(typedValue.getClass())) { + ObjectValue objectValue = (ObjectValue) typedValue; + if (objectValue.isDeserialized()) { + when(mockVariable.getValue()).thenReturn(typedValue.getValue()); + } else { + when(mockVariable.getValue()).thenReturn(null); + } + } else { + when(mockVariable.getValue()).thenReturn(typedValue.getValue()); + } + + when(mockVariable.getTypedValue()).thenReturn(typedValue); + when(mockVariable.getProcessDefinitionId()).thenReturn(processDefinitionId); + when(mockVariable.getProcessInstanceId()).thenReturn(processInstanceId); + when(mockVariable.getExecutionId()).thenReturn(executionId); + when(mockVariable.getCaseInstanceId()).thenReturn(caseInstanceId); + when(mockVariable.getCaseExecutionId()).thenReturn(caseExecutionId); + when(mockVariable.getTaskId()).thenReturn(taskId); + when(mockVariable.getBatchId()).thenReturn(batchId); + when(mockVariable.getActivityInstanceId()).thenReturn(activityInstanceId); + when(mockVariable.getTenantId()).thenReturn(tenantId); + when(mockVariable.getErrorMessage()).thenReturn(errorMessage); + + return mockVariable; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/NoIntermediaryInvocation.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/NoIntermediaryInvocation.java new file mode 100644 index 0000000000000000000000000000000000000000..e89a5ec9fea42c14bc2f80a77bac6dc4d8ae351b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/NoIntermediaryInvocation.java @@ -0,0 +1,69 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import org.mockito.exceptions.base.MockitoAssertionError; +import org.mockito.internal.exceptions.Reporter; +import org.mockito.internal.invocation.InvocationsFinder; +import org.mockito.internal.verification.api.VerificationData; +import org.mockito.internal.verification.api.VerificationDataInOrder; +import org.mockito.internal.verification.api.VerificationInOrderMode; +import org.mockito.invocation.Invocation; +import org.mockito.verification.VerificationMode; + +/** + * Stricter verification mode than regular Mockito inOrder verification by requiring + * the given invocation to occur directly after the last verified invocation. May be + * useful to verify APIs where order is important, e.g. fluent builders. + * + * @author Thorben Lindhauer + */ +public class NoIntermediaryInvocation implements VerificationInOrderMode, VerificationMode { + + @Override + public void verifyInOrder(VerificationDataInOrder data) { + + Invocation firstUnverifiedInvocation = InvocationsFinder.findFirstUnverifiedInOrder(data.getOrderingContext(), data.getAllInvocations()); + + if (firstUnverifiedInvocation == null) { + Invocation previouslyVerified = InvocationsFinder.findPreviousVerifiedInOrder(data.getAllInvocations(), data.getOrderingContext()); + throw Reporter.wantedButNotInvokedInOrder(data.getWanted(), previouslyVerified); + } + + if (!data.getWanted().matches(firstUnverifiedInvocation)) { + StringBuilder sb = new StringBuilder(); + sb.append("Expected next invocation specified here: \n"); + sb.append(data.getWanted().getLocation()); + sb.append("\n"); + sb.append("but next invocation was: \n"); + sb.append(firstUnverifiedInvocation.getLocation()); + sb.append("\n"); + + throw new MockitoAssertionError(sb.toString()); + } + } + + @Override + public void verify(VerificationData data) { + throw new RuntimeException("Applies only to inorder verification"); + } + + public static final NoIntermediaryInvocation immediatelyAfter() { + return new NoIntermediaryInvocation(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/TaskQueryMatcher.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/TaskQueryMatcher.java new file mode 100644 index 0000000000000000000000000000000000000000..7dbd2446800b43accf593640ace22d0185cb04a7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/TaskQueryMatcher.java @@ -0,0 +1,65 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import org.camunda.bpm.engine.impl.TaskQueryImpl; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.mockito.ArgumentMatcher; + +/** + * @author Thorben Lindhauer + * + */ +public class TaskQueryMatcher extends BaseMatcher { + + protected String taskName; + + @Override + public boolean matches(Object argument) { + if (argument == null) { + return false; + } + + TaskQueryImpl argumentQuery = (TaskQueryImpl) argument; + + if (taskName != null) { + return taskName.equals(argumentQuery.getName()); + } else if (argumentQuery.getName() != null) { + return false; + } + + return true; + } + + public static TaskQueryMatcher hasName(String taskName) { + TaskQueryMatcher matcher = new TaskQueryMatcher(); + matcher.taskName = taskName; + return matcher; + } + + public void describeTo(Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append(": "); + sb.append("taskName="); + sb.append(taskName); + + description.appendText(sb.toString()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ValueGenerator.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ValueGenerator.java new file mode 100644 index 0000000000000000000000000000000000000000..b604d8148bbbc8edaedfdd2ab536f909acce7148 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/ValueGenerator.java @@ -0,0 +1,46 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import java.util.HashMap; +import java.util.Map; + +/** + * Generate distinct values based on a format string + * + * @author Thorben Lindhauer + * + */ +public class ValueGenerator { + + protected int counter = 0; + protected Map values = new HashMap(); + protected String valueFormat; + + public ValueGenerator(String valueFormat) { + this.valueFormat = valueFormat; + } + + public String getValue(String key) { + if (!values.containsKey(key)) { + String nextValue = String.format(valueFormat, counter++); + values.put(key, nextValue); + } + + return values.get(key); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/VariableTypeHelper.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/VariableTypeHelper.java new file mode 100644 index 0000000000000000000000000000000000000000..4bc3bad67dc547bf5bc99ad7e684ca6e41685672 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/VariableTypeHelper.java @@ -0,0 +1,37 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper; + +import org.camunda.bpm.engine.variable.type.ValueType; + +/** + * @author Thorben Lindhauer + * + */ +public class VariableTypeHelper { + + /** + * The REST API is expected to return the variable's value type name in capitalized form. + */ + public static String toExpectedValueTypeName(ValueType type) { + String typeName = type.getName(); + + String expectedName = typeName.substring(0, 1).toUpperCase() + typeName.substring(1); + + return expectedName; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsNullValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsNullValue.java new file mode 100644 index 0000000000000000000000000000000000000000..b56abe6fca6367fc1f4197ec836e26da4224cce1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsNullValue.java @@ -0,0 +1,59 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper.variable; + +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; + +/** + * @author Thorben Lindhauer + * + */ +public class EqualsNullValue extends BaseMatcher { + + public boolean matches(Object argument) { + if (argument == null || !TypedValue.class.isAssignableFrom(argument.getClass())) { + return false; + } + + TypedValue typedValue = (TypedValue) argument; + + if (typedValue.getType() != ValueType.NULL) { + return false; + } + + if (typedValue.getValue() != null) { + return false; + } + + return true; + } + + public static EqualsNullValue matcher() { + return new EqualsNullValue(); + } + + public void describeTo(Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + + description.appendText(sb.toString()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsObjectValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsObjectValue.java new file mode 100644 index 0000000000000000000000000000000000000000..44bbb10280d6efb353b8a8760c6fb2a2c68b680b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsObjectValue.java @@ -0,0 +1,151 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper.variable; + +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.hamcrest.Description; + + +/** + * @author Thorben Lindhauer + * + */ +public class EqualsObjectValue extends EqualsTypedValue { + + protected String serializationFormat; + protected String objectTypeName; + protected String serializedValue; + protected Object value; + protected boolean isDeserialized = false; + + public EqualsObjectValue() { + this.type = ValueType.OBJECT; + } + + public EqualsObjectValue serializationFormat(String serializationFormat) { + this.serializationFormat = serializationFormat; + return this; + } + + public EqualsObjectValue objectTypeName(String objectTypeName) { + this.objectTypeName = objectTypeName; + return this; + } + + public EqualsObjectValue value(Object value) { + this.value = value; + return this; + } + + public EqualsObjectValue isDeserialized() { + this.isDeserialized = true; + return this; + } + + public EqualsObjectValue serializedValue(String serializedValue) { + this.serializedValue = serializedValue; + return this; + } + + public boolean matches(Object argument) { + if (!super.matches(argument)) { + return false; + } + + if (!ObjectValue.class.isAssignableFrom(argument.getClass())) { + return false; + } + + ObjectValue objectValue = (ObjectValue) argument; + + if (isDeserialized) { + if (!objectValue.isDeserialized()) { + return false; + } + + if (value == null) { + if (objectValue.getValue() != null) { + return false; + } + } else { + if (!value.equals(objectValue.getValue())) { + return false; + } + } + + } else { + if (objectValue.isDeserialized()) { + return false; + } + + + if (serializationFormat == null) { + if (objectValue.getSerializationDataFormat() != null) { + return false; + } + } else { + if (!serializationFormat.equals(objectValue.getSerializationDataFormat())) { + return false; + } + } + + if (objectTypeName == null) { + if (objectValue.getObjectTypeName() != null) { + return false; + } + } else { + if (!objectTypeName.equals(objectValue.getObjectTypeName())) { + return false; + } + } + + if (serializedValue == null) { + if (objectValue.getValueSerialized() != null) { + return false; + } + } else { + if (!serializedValue.equals(objectValue.getValueSerialized())) { + return false; + } + } + } + + + return true; + } + + public static EqualsObjectValue objectValueMatcher() { + return new EqualsObjectValue(); + } + + public void describeTo(Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append(": "); + sb.append("serializedValue="); + sb.append(serializedValue); + sb.append(", objectTypeName="); + sb.append(objectTypeName); + sb.append(", serializationFormat="); + sb.append(serializationFormat); + sb.append(", isDeserialized=false"); + + description.appendText(sb.toString()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsPrimitiveValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsPrimitiveValue.java new file mode 100644 index 0000000000000000000000000000000000000000..46ad12ca224d5421695b144e2532e26e1988bc6f --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsPrimitiveValue.java @@ -0,0 +1,144 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper.variable; + +import java.util.Arrays; +import java.util.Date; + +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.PrimitiveValue; +import org.hamcrest.Description; + + +/** + * @author Thorben Lindhauer + * + */ +public class EqualsPrimitiveValue extends EqualsTypedValue { + + protected Object value; + + public EqualsPrimitiveValue value(Object value) { + this.value = value; + return this; + } + + public boolean matches(Object argument) { + if (!super.matches(argument)) { + return false; + } + + if (!PrimitiveValue.class.isAssignableFrom(argument.getClass())) { + return false; + } + + PrimitiveValue primitveValue = (PrimitiveValue) argument; + + if (value == null) { + if (primitveValue.getValue() != null) { + return false; + } + } else { + if (!matchesValues(primitveValue.getValue())) { + return false; + } + } + + return true; + } + + protected boolean matchesValues(Object otherValue) { + // explicit matching for byte[] + if (value instanceof byte[]) { + if (!(otherValue instanceof byte[])) { + return false; + } + + byte[] byteValue = (byte[]) value; + byte[] otherByteValue = (byte[]) otherValue; + + return Arrays.equals(byteValue, otherByteValue); + } + + if (type == ValueType.NUMBER) { + if (!(otherValue instanceof Number)) { + return false; + } + + Number thisNumer = (Number) value; + Number otherNumber = (Number) otherValue; + + return thisNumer.doubleValue() == otherNumber.doubleValue(); + } + + return value.equals(otherValue); + + } + + public static EqualsPrimitiveValue primitiveValueMatcher() { + return new EqualsPrimitiveValue(); + } + + public static EqualsPrimitiveValue integerValue(Integer value) { + return new EqualsPrimitiveValue().type(ValueType.INTEGER).value(value); + } + + public static EqualsPrimitiveValue stringValue(String value) { + return new EqualsPrimitiveValue().type(ValueType.STRING).value(value); + } + + public static EqualsPrimitiveValue booleanValue(Boolean value) { + return new EqualsPrimitiveValue().type(ValueType.BOOLEAN).value(value); + } + + public static EqualsPrimitiveValue shortValue(Short value) { + return new EqualsPrimitiveValue().type(ValueType.SHORT).value(value); + } + + public static EqualsPrimitiveValue doubleValue(Double value) { + return new EqualsPrimitiveValue().type(ValueType.DOUBLE).value(value); + } + + public static EqualsPrimitiveValue longValue(Long value) { + return new EqualsPrimitiveValue().type(ValueType.LONG).value(value); + } + + public static EqualsPrimitiveValue bytesValue(byte[] value) { + return new EqualsPrimitiveValue().type(ValueType.BYTES).value(value); + } + + public static EqualsPrimitiveValue dateValue(Date value) { + return new EqualsPrimitiveValue().type(ValueType.DATE).value(value); + } + + public static EqualsPrimitiveValue numberValue(Number value) { + return new EqualsPrimitiveValue().type(ValueType.NUMBER).value(value); + } + + public void describeTo(Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append(": "); + sb.append("value="); + sb.append(value); + sb.append(", type="); + sb.append(type); + + description.appendText(sb.toString()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsTypedValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsTypedValue.java new file mode 100644 index 0000000000000000000000000000000000000000..772bc6318f20f6ac233152e12474159ba7197567 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsTypedValue.java @@ -0,0 +1,63 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper.variable; + +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; + +/** + * @author Thorben Lindhauer + * + */ +public class EqualsTypedValue> extends BaseMatcher { + + protected ValueType type; + + @SuppressWarnings("unchecked") + public S type(ValueType type) { + this.type = type; + return (S) this; + } + + public boolean matches(Object argument) { + if (argument == null || !TypedValue.class.isAssignableFrom(argument.getClass())) { + return false; + } + + TypedValue typedValue = (TypedValue) argument; + + if (type != null && + !type.equals(typedValue.getType())) { + return false; + } + + return true; + } + + public void describeTo(Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append(": "); + sb.append("type="); + sb.append(type); + + description.appendText(sb.toString()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsUntypedValue.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsUntypedValue.java new file mode 100644 index 0000000000000000000000000000000000000000..dbc2073abb7494df59b6e3fdfc75af26bbc017ca --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/helper/variable/EqualsUntypedValue.java @@ -0,0 +1,74 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.helper.variable; + +import org.camunda.bpm.engine.variable.value.TypedValue; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; + +/** + * @author Thorben Lindhauer + * + */ +public class EqualsUntypedValue extends BaseMatcher { + + protected Object value; + + public EqualsUntypedValue value(Object value) { + this.value = value; + return this; + } + + public boolean matches(Object argument) { + if (argument == null || !TypedValue.class.isAssignableFrom(argument.getClass())) { + return false; + } + + TypedValue typedValue = (TypedValue) argument; + + if (typedValue.getType() != null) { + return false; + } + + if (value == null) { + if (typedValue.getValue() != null) { + return false; + } + } else { + if (!value.equals(typedValue.getValue())) { + return false; + } + } + + return true; + } + + public static EqualsUntypedValue matcher() { + return new EqualsUntypedValue(); + } + + public void describeTo(Description description) { + StringBuilder sb = new StringBuilder(); + sb.append(this.getClass().getSimpleName()); + sb.append(": "); + sb.append("value="); + sb.append(value); + + description.appendText(sb.toString()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricBatchReportServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricBatchReportServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..92ca683ef3a67be12140fc9c9d085dc8425c56b7 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricBatchReportServiceTest.java @@ -0,0 +1,221 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.history.CleanableHistoricBatchReport; +import org.camunda.bpm.engine.history.CleanableHistoricBatchReportResult; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class CleanableHistoricBatchReportServiceTest extends AbstractRestServiceTest { + + private static final String EXAMPLE_TYPE = "batchId1"; + private static final int EXAMPLE_TTL = 5; + private static final long EXAMPLE_FINISHED_COUNT = 10l; + private static final long EXAMPLE_CLEANABLE_COUNT = 5l; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_URL = TEST_RESOURCE_ROOT_PATH + "/history/batch"; + protected static final String HISTORIC_REPORT_URL = HISTORY_URL + "/cleanable-batch-report"; + protected static final String HISTORIC_REPORT_COUNT_URL = HISTORIC_REPORT_URL + "/count"; + + private CleanableHistoricBatchReport historicBatchReport; + + @Before + public void setUpRuntimeData() { + setupHistoryReportMock(); + } + + private void setupHistoryReportMock() { + CleanableHistoricBatchReport report = mock(CleanableHistoricBatchReport.class); + + CleanableHistoricBatchReportResult reportResult = mock(CleanableHistoricBatchReportResult.class); + + when(reportResult.getBatchType()).thenReturn(EXAMPLE_TYPE); + when(reportResult.getHistoryTimeToLive()).thenReturn(EXAMPLE_TTL); + when(reportResult.getFinishedBatchesCount()).thenReturn(EXAMPLE_FINISHED_COUNT); + when(reportResult.getCleanableBatchesCount()).thenReturn(EXAMPLE_CLEANABLE_COUNT); + + CleanableHistoricBatchReportResult anotherReportResult = mock(CleanableHistoricBatchReportResult.class); + + when(anotherReportResult.getBatchType()).thenReturn("batchId2"); + when(anotherReportResult.getHistoryTimeToLive()).thenReturn(null); + when(anotherReportResult.getFinishedBatchesCount()).thenReturn(13l); + when(anotherReportResult.getCleanableBatchesCount()).thenReturn(0l); + + List mocks = new ArrayList(); + mocks.add(reportResult); + mocks.add(anotherReportResult); + + when(report.list()).thenReturn(mocks); + when(report.count()).thenReturn((long) mocks.size()); + + historicBatchReport = report; + when(processEngine.getHistoryService().createCleanableHistoricBatchReport()).thenReturn(historicBatchReport); + } + + @Test + public void testGetReport() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + InOrder inOrder = Mockito.inOrder(historicBatchReport); + inOrder.verify(historicBatchReport).list(); + } + + @Test + public void testReportRetrieval() { + Response response = given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(historicBatchReport); + inOrder.verify(historicBatchReport).list(); + + String content = response.asString(); + List reportResults = from(content).getList(""); + Assert.assertEquals("There should be two report results returned.", 2, reportResults.size()); + Assert.assertNotNull(reportResults.get(0)); + + String returnedBatchType = from(content).getString("[0].batchType"); + int returnedTTL = from(content).getInt("[0].historyTimeToLive"); + long returnedFinishedCount= from(content).getLong("[0].finishedBatchesCount"); + long returnedCleanableCount = from(content).getLong("[0].cleanableBatchesCount"); + + Assert.assertEquals(EXAMPLE_TYPE, returnedBatchType); + Assert.assertEquals(EXAMPLE_TTL, returnedTTL); + Assert.assertEquals(EXAMPLE_FINISHED_COUNT, returnedFinishedCount); + Assert.assertEquals(EXAMPLE_CLEANABLE_COUNT, returnedCleanableCount); + } + + @Test + public void testMissingAuthorization() { + String message = "not authorized"; + when(historicBatchReport.list()).thenThrow(new AuthorizationException(message)); + + given() + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when().get(HISTORIC_REPORT_URL); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_REPORT_COUNT_URL); + + verify(historicBatchReport).count(); + } + + @Test + public void testOrderByFinishedBatchOperationAsc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicBatchReport).orderByFinishedBatchOperation(); + verify(historicBatchReport).asc(); + } + + @Test + public void testOrderByFinishedBatchOperationDesc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "desc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicBatchReport).orderByFinishedBatchOperation(); + verify(historicBatchReport).desc(); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_REPORT_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("finished", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricCaseInstanceReportServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricCaseInstanceReportServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..acf60336d015de151fc054ac7a5336d3f836dad9 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricCaseInstanceReportServiceTest.java @@ -0,0 +1,388 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.history.CleanableHistoricCaseInstanceReport; +import org.camunda.bpm.engine.history.CleanableHistoricCaseInstanceReportResult; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class CleanableHistoricCaseInstanceReportServiceTest extends AbstractRestServiceTest { + + private static final String EXAMPLE_CD_ID = "anId"; + private static final String EXAMPLE_CD_KEY = "aKey"; + private static final String EXAMPLE_CD_NAME = "aName"; + private static final int EXAMPLE_CD_VERSION = 42; + private static final int EXAMPLE_TTL = 5; + private static final long EXAMPLE_FINISHED_CI_COUNT = 10l; + private static final long EXAMPLE_CLEANABLE_CI_COUNT = 5l; + private static final String EXAMPLE_TENANT_ID = "aTenantId"; + + protected static final String ANOTHER_EXAMPLE_CD_ID = "anotherCaseDefId"; + protected static final String ANOTHER_EXAMPLE_CD_KEY = "anotherCaseDefKey"; + protected static final String ANOTHER_EXAMPLE_TENANT_ID = "anotherTenantId"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_URL = TEST_RESOURCE_ROOT_PATH + "/history/case-definition"; + protected static final String HISTORIC_REPORT_URL = HISTORY_URL + "/cleanable-case-instance-report"; + protected static final String HISTORIC_REPORT_COUNT_URL = HISTORIC_REPORT_URL + "/count"; + + private CleanableHistoricCaseInstanceReport historicCaseInstanceReport; + + @Before + public void setUpRuntimeData() { + setupHistoryReportMock(); + } + + private void setupHistoryReportMock() { + CleanableHistoricCaseInstanceReport report = mock(CleanableHistoricCaseInstanceReport.class); + + when(report.caseDefinitionIdIn(anyString())).thenReturn(report); + when(report.caseDefinitionKeyIn(anyString())).thenReturn(report); + + CleanableHistoricCaseInstanceReportResult reportResult = mock(CleanableHistoricCaseInstanceReportResult.class); + + when(reportResult.getCaseDefinitionId()).thenReturn(EXAMPLE_CD_ID); + when(reportResult.getCaseDefinitionKey()).thenReturn(EXAMPLE_CD_KEY); + when(reportResult.getCaseDefinitionName()).thenReturn(EXAMPLE_CD_NAME); + when(reportResult.getCaseDefinitionVersion()).thenReturn(EXAMPLE_CD_VERSION); + when(reportResult.getHistoryTimeToLive()).thenReturn(EXAMPLE_TTL); + when(reportResult.getFinishedCaseInstanceCount()).thenReturn(EXAMPLE_FINISHED_CI_COUNT); + when(reportResult.getCleanableCaseInstanceCount()).thenReturn(EXAMPLE_CLEANABLE_CI_COUNT); + when(reportResult.getTenantId()).thenReturn(EXAMPLE_TENANT_ID); + + CleanableHistoricCaseInstanceReportResult anotherReportResult = mock(CleanableHistoricCaseInstanceReportResult.class); + + when(anotherReportResult.getCaseDefinitionId()).thenReturn(ANOTHER_EXAMPLE_CD_ID); + when(anotherReportResult.getCaseDefinitionKey()).thenReturn(ANOTHER_EXAMPLE_CD_KEY); + when(anotherReportResult.getCaseDefinitionName()).thenReturn("cdName"); + when(anotherReportResult.getCaseDefinitionVersion()).thenReturn(33); + when(anotherReportResult.getHistoryTimeToLive()).thenReturn(null); + when(anotherReportResult.getFinishedCaseInstanceCount()).thenReturn(13l); + when(anotherReportResult.getCleanableCaseInstanceCount()).thenReturn(0l); + when(anotherReportResult.getTenantId()).thenReturn(ANOTHER_EXAMPLE_TENANT_ID); + + + List mocks = new ArrayList(); + mocks.add(reportResult); + mocks.add(anotherReportResult); + + when(report.list()).thenReturn(mocks); + when(report.count()).thenReturn((long) mocks.size()); + + historicCaseInstanceReport = report; + when(processEngine.getHistoryService().createCleanableHistoricCaseInstanceReport()).thenReturn(historicCaseInstanceReport); + } + + @Test + public void testGetReport() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + InOrder inOrder = Mockito.inOrder(historicCaseInstanceReport); + inOrder.verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testReportRetrieval() { + Response response = given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(historicCaseInstanceReport); + inOrder.verify(historicCaseInstanceReport).list(); + + String content = response.asString(); + List reportResults = from(content).getList(""); + Assert.assertEquals("There should be two report results returned.", 2, reportResults.size()); + Assert.assertNotNull(reportResults.get(0)); + + String returnedDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedDefinitionKey = from(content).getString("[0].caseDefinitionKey"); + String returnedDefinitionName = from(content).getString("[0].caseDefinitionName"); + int returnedDefinitionVersion = from(content).getInt("[0].caseDefinitionVersion"); + int returnedTTL = from(content).getInt("[0].historyTimeToLive"); + long returnedFinishedCount= from(content).getLong("[0].finishedCaseInstanceCount"); + long returnedCleanableCount = from(content).getLong("[0].cleanableCaseInstanceCount"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(EXAMPLE_CD_ID, returnedDefinitionId); + Assert.assertEquals(EXAMPLE_CD_KEY, returnedDefinitionKey); + Assert.assertEquals(EXAMPLE_CD_NAME, returnedDefinitionName); + Assert.assertEquals(EXAMPLE_CD_VERSION, returnedDefinitionVersion); + Assert.assertEquals(EXAMPLE_TTL, returnedTTL); + Assert.assertEquals(EXAMPLE_FINISHED_CI_COUNT, returnedFinishedCount); + Assert.assertEquals(EXAMPLE_CLEANABLE_CI_COUNT, returnedCleanableCount); + Assert.assertEquals(EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testMissingAuthorization() { + String message = "not authorized"; + when(historicCaseInstanceReport.list()).thenThrow(new AuthorizationException(message)); + + given() + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when().get(HISTORIC_REPORT_URL); + } + + @Test + public void testQueryByDefinitionId() { + given() + .queryParam("caseDefinitionIdIn", EXAMPLE_CD_ID + "," + ANOTHER_EXAMPLE_CD_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicCaseInstanceReport).caseDefinitionIdIn(EXAMPLE_CD_ID, ANOTHER_EXAMPLE_CD_ID); + verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testQueryByDefinitionKey() { + given() + .queryParam("caseDefinitionKeyIn", EXAMPLE_CD_KEY + "," + ANOTHER_EXAMPLE_CD_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicCaseInstanceReport).caseDefinitionKeyIn(EXAMPLE_CD_KEY, ANOTHER_EXAMPLE_CD_KEY); + verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testQueryByTenantId() { + given() + .queryParam("tenantIdIn", EXAMPLE_TENANT_ID + "," + ANOTHER_EXAMPLE_TENANT_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicCaseInstanceReport).tenantIdIn(EXAMPLE_TENANT_ID, ANOTHER_EXAMPLE_TENANT_ID); + verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testQueryWithoutTenantId() { + given() + .queryParam("withoutTenantId", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicCaseInstanceReport).withoutTenantId(); + verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testQueryCompact() { + given() + .queryParam("compact", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicCaseInstanceReport).compact(); + verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testFullQuery() { + given() + .params(getCompleteQueryParameters()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verifyQueryParameterInvocations(); + verify(historicCaseInstanceReport).list(); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_REPORT_COUNT_URL); + + verify(historicCaseInstanceReport).count(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testFullQueryCount() { + given() + .params(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_REPORT_COUNT_URL); + + verifyQueryParameterInvocations(); + verify(historicCaseInstanceReport).count(); + } + + @Test + public void testOrderByFinishedCaseInstanceAsc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicCaseInstanceReport).orderByFinished(); + verify(historicCaseInstanceReport).asc(); + verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testOrderByFinishedCaseInstanceDesc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "desc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicCaseInstanceReport).orderByFinished(); + verify(historicCaseInstanceReport).desc(); + verify(historicCaseInstanceReport).list(); + verifyNoMoreInteractions(historicCaseInstanceReport); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_REPORT_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("finished", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + } + + protected Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("caseDefinitionIdIn", EXAMPLE_CD_ID + "," + ANOTHER_EXAMPLE_CD_ID); + parameters.put("caseDefinitionKeyIn", EXAMPLE_CD_KEY + "," + ANOTHER_EXAMPLE_CD_KEY); + parameters.put("tenantIdIn", EXAMPLE_TENANT_ID + "," + ANOTHER_EXAMPLE_TENANT_ID); + parameters.put("withoutTenantId", true); + parameters.put("compact", true); + + return parameters; + } + + protected void verifyQueryParameterInvocations() { + verify(historicCaseInstanceReport).caseDefinitionIdIn(EXAMPLE_CD_ID, ANOTHER_EXAMPLE_CD_ID); + verify(historicCaseInstanceReport).caseDefinitionKeyIn(EXAMPLE_CD_KEY, ANOTHER_EXAMPLE_CD_KEY); + verify(historicCaseInstanceReport).tenantIdIn(EXAMPLE_TENANT_ID, ANOTHER_EXAMPLE_TENANT_ID); + verify(historicCaseInstanceReport).withoutTenantId(); + verify(historicCaseInstanceReport).compact(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricDecisionInstanceReportServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricDecisionInstanceReportServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ee52f9e660b0f7300ae0e223b336a54cd91fae14 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricDecisionInstanceReportServiceTest.java @@ -0,0 +1,389 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.history.CleanableHistoricDecisionInstanceReport; +import org.camunda.bpm.engine.history.CleanableHistoricDecisionInstanceReportResult; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class CleanableHistoricDecisionInstanceReportServiceTest extends AbstractRestServiceTest { + + private static final String EXAMPLE_DD_ID = "anId"; + private static final String EXAMPLE_DD_KEY = "aKey"; + private static final String EXAMPLE_DD_NAME = "aName"; + private static final int EXAMPLE_DD_VERSION = 42; + private static final int EXAMPLE_TTL = 5; + private static final long EXAMPLE_FINISHED_DI_COUNT = 1000l; + private static final long EXAMPLE_CLEANABLE_DI_COUNT = 567l; + private static final String EXAMPLE_TENANT_ID = "aTenantId"; + + protected static final String ANOTHER_EXAMPLE_DD_ID = "anotherDefId"; + protected static final String ANOTHER_EXAMPLE_DD_KEY = "anotherDefKey"; + protected static final String ANOTHER_EXAMPLE_TENANT_ID = "anotherTenantId"; + + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_URL = TEST_RESOURCE_ROOT_PATH + "/history/decision-definition"; + protected static final String HISTORIC_REPORT_URL = HISTORY_URL + "/cleanable-decision-instance-report"; + protected static final String HISTORIC_REPORT_COUNT_URL = HISTORIC_REPORT_URL + "/count"; + + private CleanableHistoricDecisionInstanceReport historicDecisionInstanceReport; + + @Before + public void setUpRuntimeData() { + setupHistoryReportMock(); + } + + private void setupHistoryReportMock() { + CleanableHistoricDecisionInstanceReport report = mock(CleanableHistoricDecisionInstanceReport.class); + + when(report.decisionDefinitionIdIn(anyString())).thenReturn(report); + when(report.decisionDefinitionKeyIn(anyString())).thenReturn(report); + + CleanableHistoricDecisionInstanceReportResult reportResult = mock(CleanableHistoricDecisionInstanceReportResult.class); + + when(reportResult.getDecisionDefinitionId()).thenReturn(EXAMPLE_DD_ID); + when(reportResult.getDecisionDefinitionKey()).thenReturn(EXAMPLE_DD_KEY); + when(reportResult.getDecisionDefinitionName()).thenReturn(EXAMPLE_DD_NAME); + when(reportResult.getDecisionDefinitionVersion()).thenReturn(EXAMPLE_DD_VERSION); + when(reportResult.getHistoryTimeToLive()).thenReturn(EXAMPLE_TTL); + when(reportResult.getFinishedDecisionInstanceCount()).thenReturn(EXAMPLE_FINISHED_DI_COUNT); + when(reportResult.getCleanableDecisionInstanceCount()).thenReturn(EXAMPLE_CLEANABLE_DI_COUNT); + when(reportResult.getTenantId()).thenReturn(EXAMPLE_TENANT_ID); + + CleanableHistoricDecisionInstanceReportResult anotherReportResult = mock(CleanableHistoricDecisionInstanceReportResult.class); + + when(anotherReportResult.getDecisionDefinitionId()).thenReturn(ANOTHER_EXAMPLE_DD_ID); + when(anotherReportResult.getDecisionDefinitionKey()).thenReturn(ANOTHER_EXAMPLE_DD_KEY); + when(anotherReportResult.getDecisionDefinitionName()).thenReturn("dpName"); + when(anotherReportResult.getDecisionDefinitionVersion()).thenReturn(33); + when(anotherReportResult.getHistoryTimeToLive()).thenReturn(5); + when(anotherReportResult.getFinishedDecisionInstanceCount()).thenReturn(10l); + when(anotherReportResult.getCleanableDecisionInstanceCount()).thenReturn(0l); + when(anotherReportResult.getTenantId()).thenReturn(ANOTHER_EXAMPLE_TENANT_ID); + + + List mocks = new ArrayList(); + mocks.add(reportResult); + mocks.add(anotherReportResult); + + when(report.list()).thenReturn(mocks); + when(report.count()).thenReturn((long) mocks.size()); + + historicDecisionInstanceReport = report; + when(processEngine.getHistoryService().createCleanableHistoricDecisionInstanceReport()).thenReturn(historicDecisionInstanceReport); + } + + @Test + public void testGetReport() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + InOrder inOrder = Mockito.inOrder(historicDecisionInstanceReport); + inOrder.verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testReportRetrieval() { + Response response = given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(historicDecisionInstanceReport); + inOrder.verify(historicDecisionInstanceReport).list(); + + String content = response.asString(); + List reportResults = from(content).getList(""); + Assert.assertEquals("There should be two report results returned.", 2, reportResults.size()); + Assert.assertNotNull(reportResults.get(0)); + + String returnedDefinitionId = from(content).getString("[0].decisionDefinitionId"); + String returnedDefinitionKey = from(content).getString("[0].decisionDefinitionKey"); + String returnedDefinitionName = from(content).getString("[0].decisionDefinitionName"); + int returnedDefinitionVersion = from(content).getInt("[0].decisionDefinitionVersion"); + int returnedTTL = from(content).getInt("[0].historyTimeToLive"); + long returnedFinishedCount= from(content).getLong("[0].finishedDecisionInstanceCount"); + long returnedCleanableCount = from(content).getLong("[0].cleanableDecisionInstanceCount"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(EXAMPLE_DD_ID, returnedDefinitionId); + Assert.assertEquals(EXAMPLE_DD_KEY, returnedDefinitionKey); + Assert.assertEquals(EXAMPLE_DD_NAME, returnedDefinitionName); + Assert.assertEquals(EXAMPLE_DD_VERSION, returnedDefinitionVersion); + Assert.assertEquals(EXAMPLE_TTL, returnedTTL); + Assert.assertEquals(EXAMPLE_FINISHED_DI_COUNT, returnedFinishedCount); + Assert.assertEquals(EXAMPLE_CLEANABLE_DI_COUNT, returnedCleanableCount); + Assert.assertEquals(EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testMissingAuthorization() { + String message = "not authorized"; + when(historicDecisionInstanceReport.list()).thenThrow(new AuthorizationException(message)); + + given() + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when().get(HISTORIC_REPORT_URL); + } + + @Test + public void testQueryByDefinitionId() { + given() + .queryParam("decisionDefinitionIdIn", EXAMPLE_DD_ID + "," + ANOTHER_EXAMPLE_DD_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicDecisionInstanceReport).decisionDefinitionIdIn(EXAMPLE_DD_ID, ANOTHER_EXAMPLE_DD_ID); + verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testQueryByDefinitionKey() { + given() + .queryParam("decisionDefinitionKeyIn", EXAMPLE_DD_KEY + "," + ANOTHER_EXAMPLE_DD_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicDecisionInstanceReport).decisionDefinitionKeyIn(EXAMPLE_DD_KEY, ANOTHER_EXAMPLE_DD_KEY); + verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testQueryByTenantId() { + given() + .queryParam("tenantIdIn", EXAMPLE_TENANT_ID + "," + ANOTHER_EXAMPLE_TENANT_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicDecisionInstanceReport).tenantIdIn(EXAMPLE_TENANT_ID, ANOTHER_EXAMPLE_TENANT_ID); + verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testQueryWithoutTenantId() { + given() + .queryParam("withoutTenantId", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicDecisionInstanceReport).withoutTenantId(); + verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testQueryCompact() { + given() + .queryParam("compact", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicDecisionInstanceReport).compact(); + verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testFullQuery() { + given() + .params(getCompleteQueryParameters()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verifyQueryParameterInvocations(); + verify(historicDecisionInstanceReport).list(); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_REPORT_COUNT_URL); + + verify(historicDecisionInstanceReport).count(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testFullQueryCount() { + given() + .params(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_REPORT_COUNT_URL); + + verifyQueryParameterInvocations(); + verify(historicDecisionInstanceReport).count(); + } + + @Test + public void testOrderByFinishedDecisionInstanceAsc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicDecisionInstanceReport).orderByFinished(); + verify(historicDecisionInstanceReport).asc(); + verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testOrderByFinishedDecisionInstanceDesc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "desc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicDecisionInstanceReport).orderByFinished(); + verify(historicDecisionInstanceReport).desc(); + verify(historicDecisionInstanceReport).list(); + verifyNoMoreInteractions(historicDecisionInstanceReport); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_REPORT_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("finished", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + } + + protected Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("decisionDefinitionIdIn", EXAMPLE_DD_ID + "," + ANOTHER_EXAMPLE_DD_ID); + parameters.put("decisionDefinitionKeyIn", EXAMPLE_DD_KEY + "," + ANOTHER_EXAMPLE_DD_KEY); + parameters.put("tenantIdIn", EXAMPLE_TENANT_ID + "," + ANOTHER_EXAMPLE_TENANT_ID); + parameters.put("withoutTenantId", true); + parameters.put("compact", true); + + return parameters; + } + + protected void verifyQueryParameterInvocations() { + verify(historicDecisionInstanceReport).decisionDefinitionIdIn(EXAMPLE_DD_ID, ANOTHER_EXAMPLE_DD_ID); + verify(historicDecisionInstanceReport).decisionDefinitionKeyIn(EXAMPLE_DD_KEY, ANOTHER_EXAMPLE_DD_KEY); + verify(historicDecisionInstanceReport).tenantIdIn(EXAMPLE_TENANT_ID, ANOTHER_EXAMPLE_TENANT_ID); + verify(historicDecisionInstanceReport).withoutTenantId(); + verify(historicDecisionInstanceReport).compact(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricProcessInstanceReportServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricProcessInstanceReportServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..962eac7c5bb46724302aeff1c70d0dd9c07bffda --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/CleanableHistoricProcessInstanceReportServiceTest.java @@ -0,0 +1,386 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReport; +import org.camunda.bpm.engine.history.CleanableHistoricProcessInstanceReportResult; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class CleanableHistoricProcessInstanceReportServiceTest extends AbstractRestServiceTest { + + private static final String EXAMPLE_PD_NAME = "aName"; + private static final String EXAMPLE_PD_KEY = "aKey"; + private static final int EXAMPLE_PD_VERSION = 42; + private static final int EXAMPLE_TTL = 5; + private static final long EXAMPLE_FINISHED_PI_COUNT = 10l; + private static final long EXAMPLE_CLEANABLE_PI_COUNT = 5l; + private static final String EXAMPLE_TENANT_ID = "aTenantId"; + + protected static final String ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID = "anotherDefId"; + protected static final String ANOTHER_EXAMPLE_PD_KEY = "anotherDefKey"; + protected static final String ANOTHER_EXAMPLE_TENANT_ID = "anotherTenantId"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_URL = TEST_RESOURCE_ROOT_PATH + "/history/process-definition"; + protected static final String HISTORIC_REPORT_URL = HISTORY_URL + "/cleanable-process-instance-report"; + protected static final String HISTORIC_REPORT_COUNT_URL = HISTORIC_REPORT_URL + "/count"; + + private CleanableHistoricProcessInstanceReport historicProcessInstanceReport; + + @Before + public void setUpRuntimeData() { + setupHistoryReportMock(); + } + + private void setupHistoryReportMock() { + CleanableHistoricProcessInstanceReport report = mock(CleanableHistoricProcessInstanceReport.class); + + when(report.processDefinitionIdIn(anyString())).thenReturn(report); + when(report.processDefinitionKeyIn(anyString())).thenReturn(report); + + CleanableHistoricProcessInstanceReportResult reportResult = mock(CleanableHistoricProcessInstanceReportResult.class); + + when(reportResult.getProcessDefinitionId()).thenReturn(EXAMPLE_PROCESS_DEFINITION_ID); + when(reportResult.getProcessDefinitionKey()).thenReturn(EXAMPLE_PD_KEY); + when(reportResult.getProcessDefinitionName()).thenReturn(EXAMPLE_PD_NAME); + when(reportResult.getProcessDefinitionVersion()).thenReturn(EXAMPLE_PD_VERSION); + when(reportResult.getHistoryTimeToLive()).thenReturn(EXAMPLE_TTL); + when(reportResult.getFinishedProcessInstanceCount()).thenReturn(EXAMPLE_FINISHED_PI_COUNT); + when(reportResult.getCleanableProcessInstanceCount()).thenReturn(EXAMPLE_CLEANABLE_PI_COUNT); + when(reportResult.getTenantId()).thenReturn(EXAMPLE_TENANT_ID); + + CleanableHistoricProcessInstanceReportResult anotherReportResult = mock(CleanableHistoricProcessInstanceReportResult.class); + + when(anotherReportResult.getProcessDefinitionId()).thenReturn(ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + when(anotherReportResult.getProcessDefinitionKey()).thenReturn(ANOTHER_EXAMPLE_PD_KEY); + when(anotherReportResult.getProcessDefinitionName()).thenReturn("pdName"); + when(anotherReportResult.getProcessDefinitionVersion()).thenReturn(33); + when(anotherReportResult.getHistoryTimeToLive()).thenReturn(null); + when(anotherReportResult.getFinishedProcessInstanceCount()).thenReturn(13l); + when(anotherReportResult.getCleanableProcessInstanceCount()).thenReturn(0l); + when(anotherReportResult.getTenantId()).thenReturn(ANOTHER_EXAMPLE_TENANT_ID); + + List mocks = new ArrayList(); + mocks.add(reportResult); + mocks.add(anotherReportResult); + + when(report.list()).thenReturn(mocks); + when(report.count()).thenReturn((long) mocks.size()); + + historicProcessInstanceReport = report; + when(processEngine.getHistoryService().createCleanableHistoricProcessInstanceReport()).thenReturn(historicProcessInstanceReport); + } + + @Test + public void testGetReport() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + InOrder inOrder = Mockito.inOrder(historicProcessInstanceReport); + inOrder.verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testReportRetrieval() { + Response response = given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when().get(HISTORIC_REPORT_URL); + + // assert query invocation + InOrder inOrder = Mockito.inOrder(historicProcessInstanceReport); + inOrder.verify(historicProcessInstanceReport).list(); + + String content = response.asString(); + List reportResults = from(content).getList(""); + Assert.assertEquals("There should be two report results returned.", 2, reportResults.size()); + Assert.assertNotNull(reportResults.get(0)); + + String returnedDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedDefinitionName = from(content).getString("[0].processDefinitionName"); + int returnedDefinitionVersion = from(content).getInt("[0].processDefinitionVersion"); + int returnedTTL = from(content).getInt("[0].historyTimeToLive"); + long returnedFinishedCount= from(content).getLong("[0].finishedProcessInstanceCount"); + long returnedCleanableCount = from(content).getLong("[0].cleanableProcessInstanceCount"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(EXAMPLE_PROCESS_DEFINITION_ID, returnedDefinitionId); + Assert.assertEquals(EXAMPLE_PD_KEY, returnedDefinitionKey); + Assert.assertEquals(EXAMPLE_PD_NAME, returnedDefinitionName); + Assert.assertEquals(EXAMPLE_PD_VERSION, returnedDefinitionVersion); + Assert.assertEquals(EXAMPLE_TTL, returnedTTL); + Assert.assertEquals(EXAMPLE_FINISHED_PI_COUNT, returnedFinishedCount); + Assert.assertEquals(EXAMPLE_CLEANABLE_PI_COUNT, returnedCleanableCount); + Assert.assertEquals(EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testMissingAuthorization() { + String message = "not authorized"; + when(historicProcessInstanceReport.list()).thenThrow(new AuthorizationException(message)); + + given() + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when().get(HISTORIC_REPORT_URL); + } + + @Test + public void testQueryByDefinitionId() { + given() + .queryParam("processDefinitionIdIn", EXAMPLE_PROCESS_DEFINITION_ID + "," + ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicProcessInstanceReport).processDefinitionIdIn(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testQueryByDefinitionKey() { + given() + .queryParam("processDefinitionKeyIn", EXAMPLE_PD_KEY + "," + ANOTHER_EXAMPLE_PD_KEY) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicProcessInstanceReport).processDefinitionKeyIn(EXAMPLE_PD_KEY, ANOTHER_EXAMPLE_PD_KEY); + verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testQueryByTenantId() { + given() + .queryParam("tenantIdIn", EXAMPLE_TENANT_ID + "," + ANOTHER_EXAMPLE_TENANT_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicProcessInstanceReport).tenantIdIn(EXAMPLE_TENANT_ID, ANOTHER_EXAMPLE_TENANT_ID); + verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testQueryWithoutTenantId() { + given() + .queryParam("withoutTenantId", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicProcessInstanceReport).withoutTenantId(); + verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testQueryCompact() { + given() + .queryParam("compact", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicProcessInstanceReport).compact(); + verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testFullQuery() { + given() + .params(getCompleteQueryParameters()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_REPORT_URL); + + verifyQueryParameterInvocations(); + verify(historicProcessInstanceReport).list(); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_REPORT_COUNT_URL); + + verify(historicProcessInstanceReport).count(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testFullQueryCount() { + given() + .params(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_REPORT_COUNT_URL); + + verifyQueryParameterInvocations(); + verify(historicProcessInstanceReport).count(); + } + + @Test + public void testOrderByFinishedProcessInstanceAsc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicProcessInstanceReport).orderByFinished(); + verify(historicProcessInstanceReport).asc(); + verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testOrderByFinishedProcessInstanceDesc() { + given() + .queryParam("sortBy", "finished") + .queryParam("sortOrder", "desc") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + + verify(historicProcessInstanceReport).orderByFinished(); + verify(historicProcessInstanceReport).desc(); + verify(historicProcessInstanceReport).list(); + verifyNoMoreInteractions(historicProcessInstanceReport); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_REPORT_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("finished", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_REPORT_URL); + } + + protected Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("processDefinitionIdIn", EXAMPLE_PROCESS_DEFINITION_ID + "," + ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + parameters.put("processDefinitionKeyIn", EXAMPLE_PD_KEY + "," + ANOTHER_EXAMPLE_PD_KEY); + parameters.put("tenantIdIn", EXAMPLE_TENANT_ID + "," + ANOTHER_EXAMPLE_TENANT_ID); + parameters.put("withoutTenantId", true); + parameters.put("compact", true); + + return parameters; + } + + protected void verifyQueryParameterInvocations() { + verify(historicProcessInstanceReport).processDefinitionIdIn(EXAMPLE_PROCESS_DEFINITION_ID, ANOTHER_EXAMPLE_PROCESS_DEFINITION_ID); + verify(historicProcessInstanceReport).processDefinitionKeyIn(EXAMPLE_PD_KEY, ANOTHER_EXAMPLE_PD_KEY); + verify(historicProcessInstanceReport).tenantIdIn(EXAMPLE_TENANT_ID, ANOTHER_EXAMPLE_TENANT_ID); + verify(historicProcessInstanceReport).withoutTenantId(); + verify(historicProcessInstanceReport).compact(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..bfde8db61c8b42d65c2e403074ba36d933a7ffbf --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestServiceInteractionTest.java @@ -0,0 +1,141 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricActivityInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_ACTIVITY_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/activity-instance"; + protected static final String HISTORIC_SINGLE_ACTIVITY_INSTANCE_URL = HISTORIC_ACTIVITY_INSTANCE_URL + "/{id}"; + + protected HistoryService historyServiceMock; + protected HistoricActivityInstance historicInstanceMock; + protected HistoricActivityInstanceQuery historicQueryMock; + + @Before + public void setUpRuntimeData() { + historyServiceMock = mock(HistoryService.class); + + // runtime service + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + historicInstanceMock = MockProvider.createMockHistoricActivityInstance(); + historicQueryMock = mock(HistoricActivityInstanceQuery.class); + + when(historyServiceMock.createHistoricActivityInstanceQuery()).thenReturn(historicQueryMock); + when(historicQueryMock.activityInstanceId(anyString())).thenReturn(historicQueryMock); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + } + + @Test + public void testGetSingleHistoricActivityInstance() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_ACTIVITY_INSTANCE_URL); + + String content = response.asString(); + + String returnedId = from(content).getString("id"); + String returnedParentActivityInstanceId = from(content).getString("parentActivityInstanceId"); + String returnedActivityId = from(content).getString("activityId"); + String returnedActivityName = from(content).getString("activityName"); + String returnedActivityType = from(content).getString("activityType"); + String returnedProcessDefinitionKey = from(content).getString("processDefinitionKey"); + String returnedProcessDefinitionId = from(content).getString("processDefinitionId"); + String returnedProcessInstanceId = from(content).getString("processInstanceId"); + String returnedExecutionId = from(content).getString("executionId"); + String returnedTaskId = from(content).getString("taskId"); + String returnedCalledProcessInstanceId = from(content).getString("calledProcessInstanceId"); + String returnedCalledCaseInstanceId = from(content).getString("calledCaseInstanceId"); + String returnedAssignee = from(content).getString("assignee"); + String returnedStartTime = from(content).getString("startTime"); + String returnedEndTime = from(content).getString("endTime"); + long returnedDurationInMillis = from(content).getLong("durationInMillis"); + boolean canceled = from(content).getBoolean("canceled"); + boolean completeScope = from(content).getBoolean("completeScope"); + String returnedTenantId = from(content).getString("tenantId"); + String returnedRemovalTime = from(content).getString("removalTime"); + String returnedRootProcessInstanceId= from(content).getString("rootProcessInstanceId"); + + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_PARENT_ACTIVITY_INSTANCE_ID, returnedParentActivityInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_ID, returnedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_NAME, returnedActivityName); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_TYPE, returnedActivityType); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ID, returnedTaskId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID, returnedCalledProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID, returnedCalledCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME, returnedAssignee); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_START_TIME, returnedStartTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_END_TIME, returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_DURATION, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_CANCELED, canceled); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_COMPLETE_SCOPE, completeScope); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_START_TIME, returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_ROOT_PROCESS_INSTANCE_ID, returnedRootProcessInstanceId); + } + + @Test + public void testGetNonExistingHistoricCaseInstance() { + when(historicQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic activity instance with id '" + MockProvider.NON_EXISTING_ID + "' does not exist")) + .when() + .get(HISTORIC_SINGLE_ACTIVITY_INSTANCE_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..31c26304b8ab477d09b8da09af7c54fc22c858df --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityInstanceRestServiceQueryTest.java @@ -0,0 +1,891 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricActivityInstance; +import org.camunda.bpm.engine.history.HistoricActivityInstanceQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricActivityInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/activity-instance"; + + protected static final String HISTORIC_ACTIVITY_INSTANCE_COUNT_RESOURCE_URL = HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL + "/count"; + + protected HistoricActivityInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricActivityInstanceQuery(MockProvider.createMockHistoricActivityInstances()); + } + + private HistoricActivityInstanceQuery setUpMockHistoricActivityInstanceQuery(List mockedHistoricActivityInstances) { + HistoricActivityInstanceQuery mockedhistoricActivityInstanceQuery = mock(HistoricActivityInstanceQuery.class); + when(mockedhistoricActivityInstanceQuery.list()).thenReturn(mockedHistoricActivityInstances); + when(mockedhistoricActivityInstanceQuery.count()).thenReturn((long) mockedHistoricActivityInstances.size()); + + when(processEngine.getHistoryService().createHistoricActivityInstanceQuery()).thenReturn(mockedhistoricActivityInstanceQuery); + + return mockedhistoricActivityInstanceQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processInstanceId", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("instanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "instanceId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityName", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityName", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityType", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityType(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("startTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceStartTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("startTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceStartTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceEndTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceEndTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceDuration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceDuration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("occurrence", "asc", Status.OK); + inOrder.verify(mockedQuery).orderPartiallyByOccurrence(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("occurrence", "desc", Status.OK); + inOrder.verify(mockedQuery).orderPartiallyByOccurrence(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("definitionId").desc() + .orderBy("instanceId").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricActivityQuery() { + String processInstanceId = MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + Response response = given() + .queryParam("processInstanceId", processInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processInstanceId(processInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one activity instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned activity instance should not be null.", instances.get(0)); + + String returnedId = from(content).getString("[0].id"); + String returnedParentActivityInstanceId = from(content).getString("[0].parentActivityInstanceId"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedActivityName = from(content).getString("[0].activityName"); + String returnedActivityType = from(content).getString("[0].activityType"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedTaskId = from(content).getString("[0].taskId"); + String returnedCalledProcessInstanceId = from(content).getString("[0].calledProcessInstanceId"); + String returnedCalledCaseInstanceId = from(content).getString("[0].calledCaseInstanceId"); + String returnedAssignee = from(content).getString("[0].assignee"); + Date returnedStartTime = DateTimeUtil.parseDate(from(content).getString("[0].startTime")); + Date returnedEndTime = DateTimeUtil.parseDate(from(content).getString("[0].endTime")); + long returnedDurationInMillis = from(content).getLong("[0].durationInMillis"); + boolean canceled = from(content).getBoolean("[0].canceled"); + boolean completeScope = from(content).getBoolean("[0].completeScope"); + String returnedTenantId = from(content).getString("[0].tenantId"); + + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_PARENT_ACTIVITY_INSTANCE_ID, returnedParentActivityInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_ID, returnedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_NAME, returnedActivityName); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_TYPE, returnedActivityType); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ID, returnedTaskId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID, returnedCalledProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID, returnedCalledCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME, returnedAssignee); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_START_TIME), returnedStartTime); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_END_TIME), returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_DURATION, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_CANCELED, canceled); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_COMPLETE_SCOPE, completeScope); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + } + + @Test + public void testAdditionalParameters() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testAdditionalParametersAsPost() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testBooleanParameters() { + Map params = getCompleteBooleanQueryParameters(); + + given() + .queryParams(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyBooleanParameterQueryInvocations(); + } + + @Test + public void testBooleanParametersAsPost() { + Map params = getCompleteBooleanQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyBooleanParameterQueryInvocations(); + } + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("activityInstanceId", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_ID); + parameters.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + parameters.put("executionId", MockProvider.EXAMPLE_EXECUTION_ID); + parameters.put("activityId", MockProvider.EXAMPLE_ACTIVITY_ID); + parameters.put("activityName", MockProvider.EXAMPLE_ACTIVITY_NAME); + parameters.put("activityNameLike", MockProvider.EXAMPLE_ACTIVITY_NAME); + parameters.put("activityType", MockProvider.EXAMPLE_ACTIVITY_TYPE); + parameters.put("taskAssignee", MockProvider.EXAMPLE_TASK_ASSIGNEE_NAME); + + return parameters; + } + + private Map getCompleteBooleanQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("canceled", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_CANCELED); + parameters.put("completeScope", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_IS_COMPLETE_SCOPE); + + return parameters; + } + + private void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockedQuery).activityInstanceId(stringQueryParameters.get("activityInstanceId")); + verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); + verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); + verify(mockedQuery).executionId(stringQueryParameters.get("executionId")); + verify(mockedQuery).activityId(stringQueryParameters.get("activityId")); + verify(mockedQuery).activityName(stringQueryParameters.get("activityName")); + verify(mockedQuery).activityNameLike(stringQueryParameters.get("activityNameLike")); + verify(mockedQuery).activityType(stringQueryParameters.get("activityType")); + verify(mockedQuery).taskAssignee(stringQueryParameters.get("taskAssignee")); + + verify(mockedQuery).list(); + } + + private void verifyBooleanParameterQueryInvocations() { + Map booleanParams = getCompleteBooleanQueryParameters(); + Boolean canceled = booleanParams.get("canceled"); + Boolean completeScope = booleanParams.get("completeScope"); + + if (canceled != null && canceled) { + verify(mockedQuery).canceled(); + } + if (completeScope != null && completeScope) { + verify(mockedQuery).completeScope(); + } + + verify(mockedQuery).list(); + } + + @Test + public void testFinishedHistoricActivityQuery() { + Response response = given() + .queryParam("finished", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).finished(); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one activity instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned activity instance should not be null.", instances.get(0)); + + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedActivityEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_END_TIME, returnedActivityEndTime); + } + + @Test + public void testFinishedHistoricActivityQueryAsPost() { + Map body = new HashMap(); + body.put("finished", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).finished(); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one activity instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned activity instance should not be null.", instances.get(0)); + + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedActivityEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_END_TIME, returnedActivityEndTime); + } + + @Test + public void testUnfinishedHistoricActivityQuery() { + List mockedHistoricActivityInstances = MockProvider.createMockRunningHistoricActivityInstances(); + HistoricActivityInstanceQuery mockedhistoricActivityInstanceQuery = mock(HistoricActivityInstanceQuery.class); + when(mockedhistoricActivityInstanceQuery.list()).thenReturn(mockedHistoricActivityInstances); + when(processEngine.getHistoryService().createHistoricActivityInstanceQuery()).thenReturn(mockedhistoricActivityInstanceQuery); + + Response response = given() + .queryParam("unfinished", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedhistoricActivityInstanceQuery); + inOrder.verify(mockedhistoricActivityInstanceQuery).unfinished(); + inOrder.verify(mockedhistoricActivityInstanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one activity instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned activity instance should not be null.", instances.get(0)); + + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedActivityEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertNull(returnedActivityEndTime); + } + + @Test + public void testUnfinishedHistoricActivityQueryAsPost() { + List mockedHistoricActivityInstances = MockProvider.createMockRunningHistoricActivityInstances(); + HistoricActivityInstanceQuery mockedhistoricActivityInstanceQuery = mock(HistoricActivityInstanceQuery.class); + when(mockedhistoricActivityInstanceQuery.list()).thenReturn(mockedHistoricActivityInstances); + when(processEngine.getHistoryService().createHistoricActivityInstanceQuery()).thenReturn(mockedhistoricActivityInstanceQuery); + + Map body = new HashMap(); + body.put("unfinished", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedhistoricActivityInstanceQuery); + inOrder.verify(mockedhistoricActivityInstanceQuery).unfinished(); + inOrder.verify(mockedhistoricActivityInstanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one activity instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned activity instance should not be null.", instances.get(0)); + + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedActivityEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertNull(returnedActivityEndTime); + } + + @Test + public void testHistoricBeforeAndAfterStartTimeQuery() { + given() + .queryParam("startedBefore", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_STARTED_BEFORE) + .queryParam("startedAfter", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_STARTED_AFTER) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyStartParameterQueryInvocations(); + } + + @Test + public void testHistoricBeforeAndAfterStartTimeQueryAsPost() { + Map parameters = getCompleteStartDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyStartParameterQueryInvocations(); + } + + private Map getCompleteStartDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("startedAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_STARTED_AFTER)); + parameters.put("startedBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_STARTED_BEFORE)); + + return parameters; + } + + private void verifyStartParameterQueryInvocations() { + Map startDateParameters = getCompleteStartDateQueryParameters(); + + verify(mockedQuery).startedBefore(startDateParameters.get("startedBefore")); + verify(mockedQuery).startedAfter(startDateParameters.get("startedAfter")); + + verify(mockedQuery).list(); + } + + @Test + public void testHistoricAfterAndBeforeFinishTimeQuery() { + given() + .queryParam("finishedAfter", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_FINISHED_AFTER) + .queryParam("finishedBefore", MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_FINISHED_BEFORE) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyFinishedParameterQueryInvocations(); + } + + @Test + public void testHistoricAfterAndBeforeFinishTimeQueryAsPost() { + Map parameters = getCompleteFinishedDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyFinishedParameterQueryInvocations(); + } + + private Map getCompleteFinishedDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("finishedAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_FINISHED_AFTER)); + parameters.put("finishedBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_ACTIVITY_INSTANCE_FINISHED_BEFORE)); + + return parameters; + } + + private void verifyFinishedParameterQueryInvocations() { + Map finishedDateParameters = getCompleteFinishedDateQueryParameters(); + + verify(mockedQuery).finishedAfter(finishedDateParameters.get("finishedAfter")); + verify(mockedQuery).finishedBefore(finishedDateParameters.get("finishedBefore")); + + verify(mockedQuery).list(); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricActivityInstanceQuery(createMockHistoricActivityInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockHistoricActivityInstanceQuery(createMockHistoricActivityInstancesTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryFilterWithoutTenantIdParameter() { + // given + HistoricActivityInstance activityInstance = MockProvider.createMockHistoricActivityInstance(null); + mockedQuery = setUpMockHistoricActivityInstanceQuery(Collections.singletonList(activityInstance)); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryFilterWithoutTenantIdPostParameter() { + // given + HistoricActivityInstance activityInstance = MockProvider.createMockHistoricActivityInstance(null); + mockedQuery = setUpMockHistoricActivityInstanceQuery(Collections.singletonList(activityInstance)); + Map queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); + + // when + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_ACTIVITY_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + private List createMockHistoricActivityInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricActivityInstance(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricActivityInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityStatisticsRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityStatisticsRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..530d05b9d284f84dcdc54f63f0ab3656eead2711 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricActivityStatisticsRestServiceQueryTest.java @@ -0,0 +1,444 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.util.DateTimeUtils.DATE_FORMAT_WITH_TIMEZONE; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Date; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricActivityStatistics; +import org.camunda.bpm.engine.history.HistoricActivityStatisticsQuery; +import org.camunda.bpm.engine.impl.HistoricActivityStatisticsQueryImpl; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * + * @author Roman Smirnov + * + */ +public class HistoricActivityStatisticsRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_URL = TEST_RESOURCE_ROOT_PATH + "/history"; + protected static final String HISTORIC_ACTIVITY_STATISTICS_URL = HISTORY_URL + "/process-definition/{id}/statistics"; + + private HistoricActivityStatisticsQuery historicActivityStatisticsQuery; + + @Before + public void setUpRuntimeData() { + setupHistoricActivityStatisticsMock(); + } + + private void setupHistoricActivityStatisticsMock() { + List mocks = MockProvider.createMockHistoricActivityStatistics(); + + historicActivityStatisticsQuery = mock(HistoricActivityStatisticsQueryImpl.class); + when(processEngine.getHistoryService().createHistoricActivityStatisticsQuery(eq(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID))).thenReturn(historicActivityStatisticsQuery); + when(historicActivityStatisticsQuery.unlimitedList()).thenReturn(mocks); + } + + @Test + public void testHistoricActivityStatisticsRetrieval() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("id", hasItems(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID)) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + } + + @Test + public void testAdditionalCanceledOption() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("canceled", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).includeCanceled(); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testAdditionalFinishedOption() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("finished", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).includeFinished(); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testAdditionalCompleteScopeOption() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + . queryParam("completeScope", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).includeCompleteScope(); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testAdditionalStartedAfterOption() { + final Date testDate = new Date(0); + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("startedAfter", DATE_FORMAT_WITH_TIMEZONE.format(testDate)) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).startedAfter(testDate); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testAdditionalStartedBeforeOption() { + final Date testDate = new Date(0); + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("startedBefore", DATE_FORMAT_WITH_TIMEZONE.format(testDate)) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).startedBefore(testDate); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testAdditionalFinishedAfterOption() { + final Date testDate = new Date(0); + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("finishedAfter", DATE_FORMAT_WITH_TIMEZONE.format(testDate)) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).finishedAfter(testDate); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testAdditionalFinishedBeforeOption() { + final Date testDate = new Date(0); + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("finishedBefore", DATE_FORMAT_WITH_TIMEZONE.format(testDate)) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).finishedBefore(testDate); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testAdditionalCompleteScopeAndCanceledOption() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("completeScope", "true") + .queryParam("canceled", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + verify(historicActivityStatisticsQuery).includeCompleteScope(); + verify(historicActivityStatisticsQuery).includeCanceled(); + verify(historicActivityStatisticsQuery).unlimitedList(); + verifyNoMoreInteractions(historicActivityStatisticsQuery); + } + + @Test + public void testAdditionalCompleteScopeAndFinishedOption() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("completeScope", "true") + .queryParam("finished", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + verify(historicActivityStatisticsQuery).includeCompleteScope(); + verify(historicActivityStatisticsQuery).includeFinished(); + verify(historicActivityStatisticsQuery).unlimitedList(); + verifyNoMoreInteractions(historicActivityStatisticsQuery); + } + + @Test + public void testAdditionalCanceledAndFinishedOption() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("canceled", "true") + .queryParam("finished", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + verify(historicActivityStatisticsQuery).includeCanceled(); + verify(historicActivityStatisticsQuery).includeFinished(); + verify(historicActivityStatisticsQuery).unlimitedList(); + verifyNoMoreInteractions(historicActivityStatisticsQuery); + } + + @Test + public void testAdditionalCompleteScopeAndFinishedAndCanceledOption() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("completeScope", "true") + .queryParam("finished", "true") + .queryParam("canceled", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + verify(historicActivityStatisticsQuery).includeCompleteScope(); + verify(historicActivityStatisticsQuery).includeFinished(); + verify(historicActivityStatisticsQuery).includeCanceled(); + verify(historicActivityStatisticsQuery).unlimitedList(); + verifyNoMoreInteractions(historicActivityStatisticsQuery); + } + + @Test + public void testAdditionalCompleteScopeAndFinishedAndCanceledOptionFalse() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("completeScope", "false") + .queryParam("finished", "false") + .queryParam("canceled", "false") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + verify(historicActivityStatisticsQuery).unlimitedList(); + verifyNoMoreInteractions(historicActivityStatisticsQuery); + } + + + @Test + public void testProcessInstanceIdInFilter() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("processInstanceIdIn", "foo,bar") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).processInstanceIdIn(new String[] {"foo", "bar"}); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testIncidentsFilter() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("incidents", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).includeIncidents(); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + + @Test + public void testSimpleTaskQuery() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + + String content = response.asString(); + List result = from(content).getList(""); + Assert.assertEquals(2, result.size()); + + Assert.assertNotNull(result.get(0)); + Assert.assertNotNull(result.get(1)); + + String id = from(content).getString("[0].id"); + long instances = from(content).getLong("[0].instances"); + long canceled = from(content).getLong("[0].canceled"); + long finished = from(content).getLong("[0].finished"); + long completeScope = from(content).getLong("[0].completeScope"); + long openIncidents = from(content).getLong("[0].openIncidents"); + long resolvedIncidents = from(content).getLong("[0].resolvedIncidents"); + long deletedIncidents = from(content).getLong("[0].deletedIncidents"); + + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_ID, id); + Assert.assertEquals(MockProvider.EXAMPLE_INSTANCES_LONG, instances); + Assert.assertEquals(MockProvider.EXAMPLE_CANCELED_LONG, canceled); + Assert.assertEquals(MockProvider.EXAMPLE_FINISHED_LONG, finished); + Assert.assertEquals(MockProvider.EXAMPLE_COMPLETE_SCOPE_LONG, completeScope); + Assert.assertEquals(MockProvider.EXAMPLE_OPEN_INCIDENTS_LONG, openIncidents); + Assert.assertEquals(MockProvider.EXAMPLE_RESOLVED_INCIDENTS_LONG, resolvedIncidents); + Assert.assertEquals(MockProvider.EXAMPLE_DELETED_INCIDENTS_LONG, deletedIncidents); + + id = from(content).getString("[1].id"); + instances = from(content).getLong("[1].instances"); + canceled = from(content).getLong("[1].canceled"); + finished = from(content).getLong("[1].finished"); + completeScope = from(content).getLong("[1].completeScope"); + openIncidents = from(content).getLong("[1].openIncidents"); + resolvedIncidents = from(content).getLong("[1].resolvedIncidents"); + deletedIncidents = from(content).getLong("[1].deletedIncidents"); + + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID, id); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_INSTANCES_LONG, instances); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_CANCELED_LONG, canceled); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_FINISHED_LONG, finished); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_COMPLETE_SCOPE_LONG, completeScope); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_OPEN_INCIDENTS_LONG, openIncidents); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_RESOLVED_INCIDENTS_LONG, resolvedIncidents); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_DELETED_INCIDENTS_LONG, deletedIncidents); + + } + + @Test + public void testSortByParameterOnly() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("sortBy", "activityId") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("sortOrder", "asc") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + } + + @Test + public void testInvalidSortOrder() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("sortOrder", "invalid") + .queryParam("sortBy", "activityId") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'sortOrder' to value 'invalid'")) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + } + + @Test + public void testInvalidSortByParameterOnly() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("sortOrder", "asc") + .queryParam("sortBy", "invalid") + .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Cannot set query parameter 'sortBy' to value 'invalid'")) + .when().get(HISTORIC_ACTIVITY_STATISTICS_URL); + } + + @Test + public void testValidSortingParameters() { + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("sortOrder", "asc") + .queryParam("sortBy", "activityId") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_STATISTICS_URL); + + InOrder inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).orderByActivityId(); + inOrder.verify(historicActivityStatisticsQuery).asc(); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .queryParam("sortOrder", "desc") + .queryParam("sortBy", "activityId") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_ACTIVITY_STATISTICS_URL); + + inOrder = Mockito.inOrder(historicActivityStatisticsQuery); + inOrder.verify(historicActivityStatisticsQuery).orderByActivityId(); + inOrder.verify(historicActivityStatisticsQuery).desc(); + inOrder.verify(historicActivityStatisticsQuery).unlimitedList(); + inOrder.verifyNoMoreInteractions(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..388b73d37969e7710a1db7868b931654e3ae6641 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestServiceInteractionTest.java @@ -0,0 +1,376 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_BATCH_ID; +import static org.camunda.bpm.engine.rest.util.JsonPathUtil.from; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import io.restassured.http.ContentType; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.batch.history.HistoricBatch; +import org.camunda.bpm.engine.batch.history.HistoricBatchQuery; +import org.camunda.bpm.engine.history.SetRemovalTimeSelectModeForHistoricBatchesBuilder; +import org.camunda.bpm.engine.history.SetRemovalTimeToHistoricBatchesBuilder; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.JsonPathUtil; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import io.restassured.response.Response; + +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +public class HistoricBatchRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_BATCH_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/batch"; + protected static final String HISTORIC_SINGLE_BATCH_RESOURCE_URL = HISTORIC_BATCH_RESOURCE_URL + "/{id}"; + protected static final String SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL = HISTORIC_BATCH_RESOURCE_URL + "/set-removal-time"; + + protected HistoryService historyServiceMock; + protected HistoricBatchQuery queryMock; + + @Before + public void setUpHistoricBatchQueryMock() { + HistoricBatch historicBatchMock = MockProvider.createMockHistoricBatch(); + + queryMock = mock(HistoricBatchQuery.class); + when(queryMock.batchId(eq(MockProvider.EXAMPLE_BATCH_ID))).thenReturn(queryMock); + when(queryMock.singleResult()).thenReturn(historicBatchMock); + + historyServiceMock = mock(HistoryService.class); + when(historyServiceMock.createHistoricBatchQuery()).thenReturn(queryMock); + + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + } + + @Test + public void testGetHistoricBatch() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_BATCH_RESOURCE_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + inOrder.verify(queryMock).singleResult(); + inOrder.verifyNoMoreInteractions(); + + verifyHistoricBatchJson(response.asString()); + } + + @Test + public void testGetNonExistingHistoricBatch() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + HistoricBatchQuery historicBatchQuery = mock(HistoricBatchQuery.class); + when(historicBatchQuery.batchId(nonExistingId)).thenReturn(historicBatchQuery); + when(historicBatchQuery.singleResult()).thenReturn(null); + when(historyServiceMock.createHistoricBatchQuery()).thenReturn(historicBatchQuery); + + given() + .pathParam("id", nonExistingId) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic batch with id '" + nonExistingId + "' does not exist")) + .when() + .get(HISTORIC_SINGLE_BATCH_RESOURCE_URL); + } + + @Test + public void deleteHistoricBatch() { + given() + .pathParam("id", MockProvider.EXAMPLE_BATCH_ID) + .then().expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(HISTORIC_SINGLE_BATCH_RESOURCE_URL); + + verify(historyServiceMock).deleteHistoricBatch(eq(MockProvider.EXAMPLE_BATCH_ID)); + verifyNoMoreInteractions(historyServiceMock); + } + + @Test + public void deleteNonExistingHistoricBatch() { + String nonExistingId = MockProvider.NON_EXISTING_ID; + + doThrow(new BadUserRequestException("Historic batch for id '" + nonExistingId + "' cannot be found")) + .when(historyServiceMock).deleteHistoricBatch(eq(nonExistingId)); + + given() + .pathParam("id", nonExistingId) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Unable to delete historic batch with id '" + nonExistingId + "'")) + .when() + .delete(HISTORIC_SINGLE_BATCH_RESOURCE_URL); + } + + @Test + public void shouldSetRemovalTime_ByIds() { + SetRemovalTimeSelectModeForHistoricBatchesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricBatchesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricBatches()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicBatchIds", Collections.singletonList(EXAMPLE_BATCH_ID)); + payload.put("calculatedRemovalTime", true); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricBatchesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricBatches(); + + verify(builder).calculatedRemovalTime(); + verify(builder).byIds(EXAMPLE_BATCH_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_ByQuery() { + SetRemovalTimeSelectModeForHistoricBatchesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricBatchesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricBatches()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("calculatedRemovalTime", true); + payload.put("historicBatchQuery", Collections.singletonMap("batchId", EXAMPLE_BATCH_ID)); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricBatchesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricBatches(); + + verify(queryMock).batchId(EXAMPLE_BATCH_ID); + + verify(builder).calculatedRemovalTime(); + verify(builder).byIds(null); + verify(builder).byQuery(queryMock); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_Absolute() { + Date removalTime = new Date(); + + SetRemovalTimeSelectModeForHistoricBatchesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricBatchesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricBatches()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicBatchIds", Collections.singletonList(EXAMPLE_BATCH_ID)); + payload.put("absoluteRemovalTime", removalTime); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricBatchesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricBatches(); + + verify(builder).absoluteRemovalTime(removalTime); + verify(builder).byIds(EXAMPLE_BATCH_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldNotSetRemovalTime_Absolute() { + SetRemovalTimeSelectModeForHistoricBatchesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricBatchesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricBatches()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicBatchIds", Collections.singletonList(EXAMPLE_BATCH_ID)); + payload.put("absoluteRemovalTime", null); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL); + + SetRemovalTimeToHistoricBatchesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricBatches(); + + verify(builder).byIds(EXAMPLE_BATCH_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldClearRemovalTime() { + SetRemovalTimeSelectModeForHistoricBatchesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricBatchesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricBatches()) + .thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicBatchIds", Collections.singletonList(EXAMPLE_BATCH_ID)); + payload.put("clearedRemovalTime", true); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricBatchesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricBatches(); + + verify(builder).clearedRemovalTime(); + verify(builder).byIds(EXAMPLE_BATCH_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_Response() { + SetRemovalTimeSelectModeForHistoricBatchesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricBatchesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricBatches()).thenReturn(builderMock); + + Batch batchEntity = MockProvider.createMockBatch(); + when(builderMock.executeAsync()).thenReturn(batchEntity); + + Response response = given() + .contentType(ContentType.JSON) + .body(Collections.emptyMap()) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldSetRemovalTime_ThrowBadUserException() { + SetRemovalTimeSelectModeForHistoricBatchesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricBatchesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricBatches()).thenReturn(builderMock); + + doThrow(BadUserRequestException.class).when(builderMock).executeAsync(); + + given() + .contentType(ContentType.JSON) + .body(Collections.emptyMap()) + .then() + .expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_BATCHES_ASYNC_URL); + } + + protected void verifyBatchJson(String batchJson) { + BatchDto batch = JsonPathUtil.from(batchJson).getObject("", BatchDto.class); + assertNotNull("The returned batch should not be null.", batch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId()); + } + + protected void verifyHistoricBatchJson(String historicBatchJson) { + HistoricBatchDto historicBatch = from(historicBatchJson).getObject("", HistoricBatchDto.class); + assertNotNull("The returned historic batch should not be null.", historicBatch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, historicBatch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, historicBatch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, historicBatch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, historicBatch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, historicBatch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, historicBatch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, historicBatch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, historicBatch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, historicBatch.getTenantId()); + assertEquals(MockProvider.EXAMPLE_USER_ID, historicBatch.getCreateUserId()); + assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME), historicBatch.getStartTime()); + assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME), historicBatch.getExecutionStartTime()); + assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_END_TIME), historicBatch.getEndTime()); + assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_REMOVAL_TIME), historicBatch.getRemovalTime()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..328cb0f435c6c5684e927c206ebeaa1f99b7a2a5 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricBatchRestServiceQueryTest.java @@ -0,0 +1,322 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.rest.util.JsonPathUtil.from; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.batch.history.HistoricBatch; +import org.camunda.bpm.engine.batch.history.HistoricBatchQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.history.batch.HistoricBatchDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricBatchRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_BATCH_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/batch"; + protected static final String HISTORIC_BATCH_QUERY_COUNT_URL = HISTORIC_BATCH_RESOURCE_URL + "/count"; + + protected HistoricBatchQuery queryMock; + + @Before + public void setUpHistoricBatchQueryMock() { + List mockHistoricBatches = MockProvider.createMockHistoricBatches(); + queryMock = mock(HistoricBatchQuery.class); + + when(queryMock.list()).thenReturn(mockHistoricBatches); + when(queryMock.count()).thenReturn((long) mockHistoricBatches.size()); + + when(processEngine.getHistoryService().createHistoricBatchQuery()).thenReturn(queryMock); + } + + @Test + public void testNoParametersQuery() { + Response response = given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + + verify(queryMock).list(); + verifyNoMoreInteractions(queryMock); + + verifyHistoricBatchListJson(response.asString()); + } + + @Test + public void testUnknownQueryParameter() { + Response response = given() + .queryParam("unknown", "unknown") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + + verify(queryMock, never()).batchId(anyString()); + verify(queryMock).list(); + + verifyHistoricBatchListJson(response.asString()); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "batchId") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", + equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", + equalTo("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + } + + @Test + public void testHistoricBatchQueryByBatchId() { + Response response = given() + .queryParam("batchId", MockProvider.EXAMPLE_BATCH_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + inOrder.verify(queryMock).list(); + inOrder.verifyNoMoreInteractions(); + + verifyHistoricBatchListJson(response.asString()); + } + + @Test + public void testHistoricBatchQueryByCompleted() { + Response response = given() + .queryParam("completed", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).completed(true); + inOrder.verify(queryMock).list(); + inOrder.verifyNoMoreInteractions(); + + verifyHistoricBatchListJson(response.asString()); + } + + @Test + public void testHistoricBatchQueryByNotCompleted() { + Response response = given() + .queryParam("completed", false) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + + InOrder inOrder = inOrder(queryMock); + inOrder.verify(queryMock).completed(false); + inOrder.verify(queryMock).list(); + inOrder.verifyNoMoreInteractions(); + + verifyHistoricBatchListJson(response.asString()); + } + + @Test + public void testFullHistoricBatchQuery() { + Response response = given() + .queryParams(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + + verifyQueryParameterInvocations(); + verify(queryMock).list(); + verifyNoMoreInteractions(queryMock); + + verifyHistoricBatchListJson(response.asString()); + } + + @Test + public void testQueryCount() { + given() + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_BATCH_QUERY_COUNT_URL); + + verify(queryMock).count(); + verifyNoMoreInteractions(queryMock); + } + + @Test + public void testFullQueryCount() { + given() + .params(getCompleteQueryParameters()) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_BATCH_QUERY_COUNT_URL); + + verifyQueryParameterInvocations(); + verify(queryMock).count(); + verifyNoMoreInteractions(queryMock); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("batchId", "desc", Status.OK); + inOrder.verify(queryMock).orderById(); + inOrder.verify(queryMock).desc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("batchId", "asc", Status.OK); + inOrder.verify(queryMock).orderById(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("startTime", "desc", Status.OK); + inOrder.verify(queryMock).orderByStartTime(); + inOrder.verify(queryMock).desc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("startTime", "asc", Status.OK); + inOrder.verify(queryMock).orderByStartTime(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("endTime", "desc", Status.OK); + inOrder.verify(queryMock).orderByEndTime(); + inOrder.verify(queryMock).desc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("endTime", "asc", Status.OK); + inOrder.verify(queryMock).orderByEndTime(); + inOrder.verify(queryMock).asc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(queryMock).orderByTenantId(); + inOrder.verify(queryMock).desc(); + + inOrder = Mockito.inOrder(queryMock); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(queryMock).orderByTenantId(); + inOrder.verify(queryMock).asc(); + } + + private void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_BATCH_RESOURCE_URL); + } + + protected Map getCompleteQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("batchId", MockProvider.EXAMPLE_BATCH_ID); + parameters.put("type", MockProvider.EXAMPLE_BATCH_TYPE); + parameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID + "," + MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + parameters.put("withoutTenantId", true); + + return parameters; + } + + protected void verifyQueryParameterInvocations() { + verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + verify(queryMock).type(MockProvider.EXAMPLE_BATCH_TYPE); + verify(queryMock).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(queryMock).withoutTenantId(); + } + + protected void verifyHistoricBatchListJson(String historicBatchListJson) { + List batches = from(historicBatchListJson).get(); + assertEquals("There should be one historic batch returned.", 1, batches.size()); + + HistoricBatchDto historicBatch = from(historicBatchListJson).getObject("[0]", HistoricBatchDto.class); + assertNotNull("The returned historic batch should not be null.", historicBatch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, historicBatch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, historicBatch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, historicBatch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, historicBatch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, historicBatch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, historicBatch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, historicBatch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, historicBatch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, historicBatch.getTenantId()); + assertEquals(MockProvider.EXAMPLE_USER_ID, historicBatch.getCreateUserId()); + assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_START_TIME), historicBatch.getStartTime()); + assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_END_TIME), historicBatch.getEndTime()); + assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_BATCH_REMOVAL_TIME), historicBatch.getRemovalTime()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..e365d2485573b751699604b6ed737204f3b35bbb --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestServiceInteractionTest.java @@ -0,0 +1,143 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstance; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstanceQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricCaseActivityInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_CASE_ACTIVITY_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/case-activity-instance"; + protected static final String HISTORIC_SINGLE_CASE_ACTIVITY_INSTANCE_URL = HISTORIC_CASE_ACTIVITY_INSTANCE_URL + "/{id}"; + + protected HistoryService historyServiceMock; + protected HistoricCaseActivityInstance historicInstanceMock; + protected HistoricCaseActivityInstanceQuery historicQueryMock; + + @Before + public void setUpRuntimeData() { + historyServiceMock = mock(HistoryService.class); + + // runtime service + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + historicInstanceMock = MockProvider.createMockHistoricCaseActivityInstance(); + historicQueryMock = mock(HistoricCaseActivityInstanceQuery.class); + + when(historyServiceMock.createHistoricCaseActivityInstanceQuery()).thenReturn(historicQueryMock); + when(historicQueryMock.caseActivityInstanceId(anyString())).thenReturn(historicQueryMock); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + } + + @Test + public void testGetSingleHistoricCaseInstance() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_CASE_ACTIVITY_INSTANCE_URL); + + String content = response.asString(); + + String returnedCaseActivityInstanceId = from(content).getString("id"); + String returnedParentCaseActivityInstanceId = from(content).getString("parentCaseActivityInstanceId"); + String returnedCaseActivityId = from(content).getString("caseActivityId"); + String returnedCaseActivityName = from(content).getString("caseActivityName"); + String returnedCaseActivityType = from(content).getString("caseActivityType"); + String returnedCaseDefinitionId = from(content).getString("caseDefinitionId"); + String returnedCaseInstanceId = from(content).getString("caseInstanceId"); + String returnedCaseExecutionId = from(content).getString("caseExecutionId"); + String returnedTaskId = from(content).getString("taskId"); + String returnedCalledProcessInstanceId = from(content).getString("calledProcessInstanceId"); + String returnedCalledCaseInstanceId = from(content).getString("calledCaseInstanceId"); + String returnedCreateTime = from(content).getString("createTime"); + String returnedEndTime = from(content).getString("endTime"); + String returnedTenantId = from(content).getString("tenantId"); + long returnedDurationInMillis = from(content).getLong("durationInMillis"); + boolean required = from(content).getBoolean("required"); + boolean available = from(content).getBoolean("available"); + boolean enabled = from(content).getBoolean("enabled"); + boolean disabled = from(content).getBoolean("disabled"); + boolean active = from(content).getBoolean("active"); + boolean completed = from(content).getBoolean("completed"); + boolean terminated = from(content).getBoolean("terminated"); + + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID, returnedCaseActivityInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_PARENT_CASE_ACTIVITY_INSTANCE_ID, returnedParentCaseActivityInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_ID, returnedCaseActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_NAME, returnedCaseActivityName); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_TYPE, returnedCaseActivityType); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_EXECUTION_ID, returnedCaseExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ID, returnedTaskId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID, returnedCalledProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID, returnedCalledCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATE_TIME, returnedCreateTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME, returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_DURATION, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_REQUIRED, required); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_AVAILABLE, available); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ENABLED, enabled); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_DISABLED, disabled); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ACTIVE, active); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_COMPLETED, completed); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_TERMINATED, terminated); + } + + @Test + public void testGetNonExistingHistoricCaseInstance() { + when(historicQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic case activity instance with id '" + MockProvider.NON_EXISTING_ID + "' does not exist")) + .when() + .get(HISTORIC_SINGLE_CASE_ACTIVITY_INSTANCE_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cf79a249a9d2c8103bf49ff5a2983b2c62f6e00e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityInstanceRestServiceQueryTest.java @@ -0,0 +1,699 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstance; +import org.camunda.bpm.engine.history.HistoricCaseActivityInstanceQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +public class HistoricCaseActivityInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/case-activity-instance"; + + protected static final String HISTORIC_CASE_ACTIVITY_INSTANCE_COUNT_RESOURCE_URL = HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL + "/count"; + + protected HistoricCaseActivityInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricCaseActivityInstanceQuery(MockProvider.createMockHistoricCaseActivityInstances()); + } + + protected HistoricCaseActivityInstanceQuery setUpMockHistoricCaseActivityInstanceQuery(List mockedHistoricCaseActivityInstances) { + HistoricCaseActivityInstanceQuery mockedHistoricCaseActivityInstanceQuery = mock(HistoricCaseActivityInstanceQuery.class); + when(mockedHistoricCaseActivityInstanceQuery.list()).thenReturn(mockedHistoricCaseActivityInstances); + when(mockedHistoricCaseActivityInstanceQuery.count()).thenReturn((long) mockedHistoricCaseActivityInstances.size()); + + when(processEngine.getHistoryService().createHistoricCaseActivityInstanceQuery()).thenReturn(mockedHistoricCaseActivityInstanceQuery); + + return mockedHistoricCaseActivityInstanceQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("caseInstanceId", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("instanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "caseInstanceId") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseActivityInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseActivityInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseExecutionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseExecutionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseActivityId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseActivityId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseActivityId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseActivityId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseActivityName", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseActivityName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseActivityName", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseActivityName(); + inOrder.verify(mockedQuery).desc(); + + executeAndVerifySorting("caseActivityType", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseActivityType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseActivityType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseActivityType(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("createTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceCreateTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("createTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceCreateTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceEndTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceEndTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceDuration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricCaseActivityInstanceDuration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricActivityQuery() { + String caseInstanceId = MockProvider.EXAMPLE_CASE_INSTANCE_ID; + + Response response = given() + .queryParam("caseInstanceId", caseInstanceId) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).caseInstanceId(caseInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + String returnedId = from(content).getString("[0].id"); + String returnedParentCaseActivityInstanceId = from(content).getString("[0].parentCaseActivityInstanceId"); + String returnedCaseActivityId = from(content).getString("[0].caseActivityId"); + String returnedCaseActivityName = from(content).getString("[0].caseActivityName"); + String returnedCaseActivityType = from(content).getString("[0].caseActivityType"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedCaseExecutionId = from(content).getString("[0].caseExecutionId"); + String returnedTaskId = from(content).getString("[0].taskId"); + String returnedCalledProcessInstanceId = from(content).getString("[0].calledProcessInstanceId"); + String returnedCalledCaseInstanceId = from(content).getString("[0].calledCaseInstanceId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + Date returnedCreateTime = DateTimeUtil.parseDate(from(content).getString("[0].createTime")); + Date returnedEndTime = DateTimeUtil.parseDate(from(content).getString("[0].endTime")); + long returnedDurationInMillis = from(content).getLong("[0].durationInMillis"); + boolean required = from(content).getBoolean("[0].required"); + boolean available = from(content).getBoolean("[0].available"); + boolean enabled = from(content).getBoolean("[0].enabled"); + boolean disabled = from(content).getBoolean("[0].disabled"); + boolean active = from(content).getBoolean("[0].active"); + boolean completed = from(content).getBoolean("[0].completed"); + boolean terminated = from(content).getBoolean("[0].terminated"); + + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_PARENT_CASE_ACTIVITY_INSTANCE_ID, returnedParentCaseActivityInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_ID, returnedCaseActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_NAME, returnedCaseActivityName); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_TYPE, returnedCaseActivityType); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_EXECUTION_ID, returnedCaseExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_TASK_ID, returnedTaskId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_PROCESS_INSTANCE_ID, returnedCalledProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CALLED_CASE_INSTANCE_ID, returnedCalledCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATE_TIME), returnedCreateTime); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME), returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_DURATION, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_REQUIRED, required); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_AVAILABLE, available); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ENABLED, enabled); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_DISABLED, disabled); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ACTIVE, active); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_COMPLETED, completed); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_TERMINATED, terminated); + } + + @Test + public void testAdditionalParameters() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testBooleanParameters() { + Map params = getCompleteBooleanQueryParameters(); + + given() + .queryParams(params) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyBooleanParameterQueryInvocations(); + } + + protected Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("caseActivityInstanceId", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID); + parameters.put("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID); + parameters.put("caseDefinitionId", MockProvider.EXAMPLE_CASE_DEFINITION_ID); + parameters.put("caseExecutionId", MockProvider.EXAMPLE_CASE_EXECUTION_ID); + parameters.put("caseActivityId", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_ID); + parameters.put("caseActivityName", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_NAME); + parameters.put("caseActivityType", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_TYPE); + + return parameters; + } + + protected void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockedQuery).caseActivityInstanceId(stringQueryParameters.get("caseActivityInstanceId")); + verify(mockedQuery).caseInstanceId(stringQueryParameters.get("caseInstanceId")); + verify(mockedQuery).caseDefinitionId(stringQueryParameters.get("caseDefinitionId")); + verify(mockedQuery).caseExecutionId(stringQueryParameters.get("caseExecutionId")); + verify(mockedQuery).caseActivityId(stringQueryParameters.get("caseActivityId")); + verify(mockedQuery).caseActivityName(stringQueryParameters.get("caseActivityName")); + verify(mockedQuery).caseActivityType(stringQueryParameters.get("caseActivityType")); + + verify(mockedQuery).list(); + } + + protected Map getCompleteBooleanQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("required", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_REQUIRED); + parameters.put("finished", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_FINISHED); + parameters.put("unfinished", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_UNFINISHED); + parameters.put("available", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_AVAILABLE); + parameters.put("enabled", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ENABLED); + parameters.put("disabled", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_DISABLED); + parameters.put("active", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_ACTIVE); + parameters.put("completed", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_COMPLETED); + parameters.put("terminated", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_IS_TERMINATED); + + return parameters; + } + + protected void verifyBooleanParameterQueryInvocations() { + Map booleanParams = getCompleteBooleanQueryParameters(); + Boolean required = booleanParams.get("required"); + Boolean finished = booleanParams.get("finished"); + Boolean unfinished = booleanParams.get("unfinished"); + Boolean available = booleanParams.get("available"); + Boolean enabled = booleanParams.get("enabled"); + Boolean disabled = booleanParams.get("disabled"); + Boolean active = booleanParams.get("active"); + Boolean completed = booleanParams.get("completed"); + Boolean terminated = booleanParams.get("terminated"); + + if (required != null && required) { + verify(mockedQuery).required(); + } + if (finished != null && finished) { + verify(mockedQuery).ended(); + } + if (unfinished != null && unfinished) { + verify(mockedQuery).notEnded(); + } + if (available != null && available) { + verify(mockedQuery).available(); + } + if (enabled != null && enabled) { + verify(mockedQuery).enabled(); + } + if (disabled != null && disabled) { + verify(mockedQuery).disabled(); + } + if (active != null && active) { + verify(mockedQuery).active(); + } + if (completed != null && completed) { + verify(mockedQuery).completed(); + } + if (terminated != null && terminated) { + verify(mockedQuery).terminated(); + } + + verify(mockedQuery).list(); + } + + @Test + public void testFinishedHistoricCaseActivityQuery() { + Response response = given() + .queryParam("finished", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).ended(); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedActivityEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_END_TIME, returnedActivityEndTime); + } + + @Test + public void testUnfinishedHistoricCaseActivityQuery() { + List mockedHistoricCaseActivityInstances = MockProvider.createMockRunningHistoricCaseActivityInstances(); + HistoricCaseActivityInstanceQuery mockedHistoricCaseActivityInstanceQuery = mock(HistoricCaseActivityInstanceQuery.class); + when(mockedHistoricCaseActivityInstanceQuery.list()).thenReturn(mockedHistoricCaseActivityInstances); + when(processEngine.getHistoryService().createHistoricCaseActivityInstanceQuery()).thenReturn(mockedHistoricCaseActivityInstanceQuery); + + Response response = given() + .queryParam("unfinished", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedHistoricCaseActivityInstanceQuery); + inOrder.verify(mockedHistoricCaseActivityInstanceQuery).notEnded(); + inOrder.verify(mockedHistoricCaseActivityInstanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedActivityEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); + Assert.assertNull(returnedActivityEndTime); + } + + @Test + public void testHistoricAfterAndBeforeCreateTimeQuery() { + given() + .queryParam("createdAfter", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATED_AFTER) + .queryParam("createdBefore", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATED_BEFORE) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyCreateParameterQueryInvocations(); + } + + protected Map getCompleteCreateDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("createdAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATED_AFTER)); + parameters.put("createdBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_CREATED_BEFORE)); + + return parameters; + } + + protected void verifyCreateParameterQueryInvocations() { + Map startDateParameters = getCompleteCreateDateQueryParameters(); + + verify(mockedQuery).createdAfter(startDateParameters.get("createdAfter")); + verify(mockedQuery).createdBefore(startDateParameters.get("createdBefore")); + + verify(mockedQuery).list(); + } + + @Test + public void testHistoricAfterAndBeforeEndTimeQuery() { + given() + .queryParam("endedAfter", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ENDED_AFTER) + .queryParam("endedBefore", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ENDED_BEFORE) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verifyEndedParameterQueryInvocations(); + } + + protected Map getCompleteEndedDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("endedAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ENDED_AFTER)); + parameters.put("endedBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ENDED_BEFORE)); + + return parameters; + } + + protected void verifyEndedParameterQueryInvocations() { + Map finishedDateParameters = getCompleteEndedDateQueryParameters(); + + verify(mockedQuery).endedAfter(finishedDateParameters.get("endedAfter")); + verify(mockedQuery).endedBefore(finishedDateParameters.get("endedBefore")); + + verify(mockedQuery).list(); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricCaseActivityInstanceQuery(createMockHistoricCaseActivityInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List historicCaseActivityInstances = from(content).getList(""); + assertThat(historicCaseActivityInstances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryWithoutTenantIdQueryParameter() { + // given + HistoricCaseActivityInstance caseInstance = MockProvider.createMockHistoricCaseActivityInstance(null); + mockedQuery = setUpMockHistoricCaseActivityInstanceQuery(Collections.singletonList(caseInstance)); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testCaseActivityInstanceIdListParameter() { + + given() + .queryParam("caseActivityInstanceIdIn", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID + "," + MockProvider.EXAMPLE_HISTORIC_ANOTHER_CASE_ACTIVITY_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseActivityInstanceIdIn(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_INSTANCE_ID, MockProvider.EXAMPLE_HISTORIC_ANOTHER_CASE_ACTIVITY_INSTANCE_ID); + verify(mockedQuery).list(); + } + + @Test + public void testCaseActivityIdListParameter() { + + given() + .queryParam("caseActivityIdIn", MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_ID + "," + MockProvider.EXAMPLE_HISTORIC_ANOTHER_CASE_ACTIVITY_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_ACTIVITY_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseActivityIdIn(MockProvider.EXAMPLE_HISTORIC_CASE_ACTIVITY_ID, MockProvider.EXAMPLE_HISTORIC_ANOTHER_CASE_ACTIVITY_ID); + verify(mockedQuery).list(); + } + + private List createMockHistoricCaseActivityInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricCaseActivityInstance(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricCaseActivityInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityStatisticsRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityStatisticsRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..1c97278073e758809e65cefa1d8e6db9015864ad --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseActivityStatisticsRestServiceQueryTest.java @@ -0,0 +1,126 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricCaseActivityStatistics; +import org.camunda.bpm.engine.history.HistoricCaseActivityStatisticsQuery; +import org.camunda.bpm.engine.impl.HistoricCaseActivityStatisticsQueryImpl; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.response.Response; + +/** + * @author Roman Smirnov + * + */ +public class HistoricCaseActivityStatisticsRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_URL = TEST_RESOURCE_ROOT_PATH + "/history"; + protected static final String HISTORIC_CASE_ACTIVITY_STATISTICS_URL = HISTORY_URL + "/case-definition/{id}/statistics"; + + protected static HistoricCaseActivityStatisticsQuery historicCaseActivityStatisticsQuery; + + @Before + public void setUpRuntimeData() { + List mocks = MockProvider.createMockHistoricCaseActivityStatistics(); + + historicCaseActivityStatisticsQuery = mock(HistoricCaseActivityStatisticsQueryImpl.class); + when(processEngine.getHistoryService().createHistoricCaseActivityStatisticsQuery(eq(MockProvider.EXAMPLE_CASE_DEFINITION_ID))).thenReturn(historicCaseActivityStatisticsQuery); + when(historicCaseActivityStatisticsQuery.unlimitedList()).thenReturn(mocks); + } + + @Test + public void testHistoricCaseActivityStatisticsRetrieval() { + given().pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("id", hasItems(MockProvider.EXAMPLE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID)) + .when().get(HISTORIC_CASE_ACTIVITY_STATISTICS_URL); + } + + @Test + public void testSimpleTaskQuery() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_CASE_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_ACTIVITY_STATISTICS_URL); + + String content = response.asString(); + List result = from(content).getList(""); + Assert.assertEquals(2, result.size()); + + Assert.assertNotNull(result.get(0)); + Assert.assertNotNull(result.get(1)); + + String id = from(content).getString("[0].id"); + long available = from(content).getLong("[0].available"); + long active = from(content).getLong("[0].active"); + long completed = from(content).getLong("[0].completed"); + long disabled = from(content).getLong("[0].disabled"); + long enabled = from(content).getLong("[0].enabled"); + long terminated = from(content).getLong("[0].terminated"); + + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVITY_ID, id); + Assert.assertEquals(MockProvider.EXAMPLE_AVAILABLE_LONG, available); + Assert.assertEquals(MockProvider.EXAMPLE_ACTIVE_LONG, active); + Assert.assertEquals(MockProvider.EXAMPLE_COMPLETED_LONG, completed); + Assert.assertEquals(MockProvider.EXAMPLE_DISABLED_LONG, disabled); + Assert.assertEquals(MockProvider.EXAMPLE_ENABLED_LONG, enabled); + Assert.assertEquals(MockProvider.EXAMPLE_TERMINATED_LONG, terminated); + + id = from(content).getString("[1].id"); + available = from(content).getLong("[1].available"); + active = from(content).getLong("[1].active"); + completed = from(content).getLong("[1].completed"); + disabled = from(content).getLong("[1].disabled"); + enabled = from(content).getLong("[1].enabled"); + terminated = from(content).getLong("[1].terminated"); + + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_ACTIVITY_ID, id); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_AVAILABLE_LONG, available); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_ACTIVE_LONG, active); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_COMPLETED_LONG, completed); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_DISABLED_LONG, disabled); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_ENABLED_LONG, enabled); + Assert.assertEquals(MockProvider.ANOTHER_EXAMPLE_TERMINATED_LONG, terminated); + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ffb97000c476abcce2830460df0dee354bbf3247 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestServiceInteractionTest.java @@ -0,0 +1,127 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.history.HistoricCaseInstance; +import org.camunda.bpm.engine.history.HistoricCaseInstanceQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricCaseInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_CASE_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/case-instance"; + protected static final String HISTORIC_SINGLE_CASE_INSTANCE_URL = HISTORIC_CASE_INSTANCE_URL + "/{id}"; + + protected HistoryService historyServiceMock; + protected HistoricCaseInstance historicInstanceMock; + protected HistoricCaseInstanceQuery historicQueryMock; + + @Before + public void setUpRuntimeData() { + historyServiceMock = mock(HistoryService.class); + + // runtime service + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + historicInstanceMock = MockProvider.createMockHistoricCaseInstance(); + historicQueryMock = mock(HistoricCaseInstanceQuery.class); + + when(historyServiceMock.createHistoricCaseInstanceQuery()).thenReturn(historicQueryMock); + when(historicQueryMock.caseInstanceId(anyString())).thenReturn(historicQueryMock); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + } + + @Test + public void testGetSingleHistoricCaseInstance() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_CASE_INSTANCE_URL); + + String content = response.asString(); + + String returnedCaseInstanceId = from(content).getString("id"); + String returnedCaseInstanceBusinessKey = from(content).getString("businessKey"); + String returnedCaseDefinitionId = from(content).getString("caseDefinitionId"); + String returnedCreateTime = from(content).getString("createTime"); + String returnedCloseTime = from(content).getString("closeTime"); + long returnedDurationInMillis = from(content).getLong("durationInMillis"); + String returnedCreateUserId = from(content).getString("createUserId"); + String returnedSuperCaseInstanceId = from(content).getString("superCaseInstanceId"); + String returnedSuperProcessInstanceId = from(content).getString("superProcessInstanceId"); + String returnedTenantId = from(content).getString("tenantId"); + boolean active = from(content).getBoolean("active"); + boolean completed = from(content).getBoolean("completed"); + boolean terminated = from(content).getBoolean("terminated"); + boolean closed = from(content).getBoolean("closed"); + + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY, returnedCaseInstanceBusinessKey); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_TIME, returnedCreateTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSE_TIME, returnedCloseTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_DURATION_MILLIS, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_USER_ID, returnedCreateUserId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_CASE_INSTANCE_ID, returnedSuperCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_PROCESS_INSTANCE_ID, returnedSuperProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_ACTIVE, active); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_COMPLETED, completed); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_TERMINATED, terminated); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_CLOSED, closed); + } + + @Test + public void testGetNonExistingHistoricCaseInstance() { + when(historicQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic case instance with id '" + MockProvider.NON_EXISTING_ID + "' does not exist")) + .when() + .get(HISTORIC_SINGLE_CASE_INSTANCE_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..a175b6ce5d5dfffcea81e7175ee65c997a7ba3e3 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricCaseInstanceRestServiceQueryTest.java @@ -0,0 +1,1548 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricCaseInstance; +import org.camunda.bpm.engine.history.HistoricCaseInstanceQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricCaseInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_CASE_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/case-instance"; + protected static final String HISTORIC_CASE_INSTANCE_COUNT_RESOURCE_URL = HISTORIC_CASE_INSTANCE_RESOURCE_URL + "/count"; + + protected HistoricCaseInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricCaseInstanceQuery(MockProvider.createMockHistoricCaseInstances()); + } + + protected HistoricCaseInstanceQuery setUpMockHistoricCaseInstanceQuery(List mockedHistoricCaseInstances) { + HistoricCaseInstanceQuery mockedHistoricCaseInstanceQuery = mock(HistoricCaseInstanceQuery.class); + when(mockedHistoricCaseInstanceQuery.list()).thenReturn(mockedHistoricCaseInstances); + when(mockedHistoricCaseInstanceQuery.count()).thenReturn((long) mockedHistoricCaseInstances.size()); + + when(processEngine.getHistoryService().createHistoricCaseInstanceQuery()).thenReturn(mockedHistoricCaseInstanceQuery); + + return mockedHistoricCaseInstanceQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("caseDefinitionKey", queryKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "definitionId") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("businessKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceBusinessKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("businessKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceBusinessKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("createTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceCreateTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("createTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceCreateTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("closeTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceCloseTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("closeTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceCloseTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceDuration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceDuration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("businessKey").desc() + .orderBy("closeTime").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + inOrder.verify(mockedQuery).orderByCaseInstanceBusinessKey(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByCaseInstanceCloseTime(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_CASE_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then().expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_CASE_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricCaseQuery() { + String caseInstanceId = MockProvider.EXAMPLE_CASE_INSTANCE_ID; + + Response response = given() + .queryParam("caseInstanceId", caseInstanceId) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).caseInstanceId(caseInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + String returnedCaseInstanceId = from(content).getString("[0].id"); + String returnedCaseInstanceBusinessKey = from(content).getString("[0].businessKey"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedCaseDefinitionKey = from(content).getString("[0].caseDefinitionKey"); + String returnedCaseDefinitionName = from(content).getString("[0].caseDefinitionName"); + String returnedCreateTime = from(content).getString("[0].createTime"); + String returnedCloseTime = from(content).getString("[0].closeTime"); + long returnedDurationInMillis = from(content).getLong("[0].durationInMillis"); + String returnedCreateUserId = from(content).getString("[0].createUserId"); + String returnedSuperCaseInstanceId = from(content).getString("[0].superCaseInstanceId"); + String returnedSuperProcessInstanceId = from(content).getString("[0].superProcessInstanceId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + boolean active = from(content).getBoolean("[0].active"); + boolean completed = from(content).getBoolean("[0].completed"); + boolean terminated = from(content).getBoolean("[0].terminated"); + boolean closed = from(content).getBoolean("[0].closed"); + + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY, returnedCaseInstanceBusinessKey); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, returnedCaseDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_KEY, returnedCaseDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_NAME, returnedCaseDefinitionName); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_TIME, returnedCreateTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSE_TIME, returnedCloseTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_DURATION_MILLIS, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATE_USER_ID, returnedCreateUserId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_CASE_INSTANCE_ID, returnedSuperCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_PROCESS_INSTANCE_ID, returnedSuperProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_ACTIVE, active); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_COMPLETED, completed); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_TERMINATED, terminated); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_IS_CLOSED, closed); + } + + @Test + public void testAdditionalParametersExcludingCases() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testAdditionalParametersExcludingCasesAsPost() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(stringQueryParameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testHistoricBeforeAndAfterCreateTimeQuery() { + given() + .queryParam("createdBefore", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_BEFORE) + .queryParam("createdAfter", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_AFTER) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyCreateParameterQueryInvocations(); + } + + @Test + public void testHistoricBeforeAndAfterCreateTimeQueryAsPost() { + Map parameters = getCompleteCreateDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyCreateParameterQueryInvocations(); + } + + @Test + public void testHistoricBeforeAndAfterCreateTimeAsStringQueryAsPost() { + Map parameters = getCompleteCreateDateAsStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyStringCreateParameterQueryInvocations(); + } + + @Test + public void testHistoricAfterAndBeforeCloseTimeQuery() { + given() + .queryParam("closedAfter", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_AFTER) + .queryParam("closedBefore", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_BEFORE) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyClosedParameterQueryInvocations(); + } + + @Test + public void testHistoricAfterAndBeforeCloseTimeQueryAsPost() { + Map parameters = getCompleteClosedDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyClosedParameterQueryInvocations(); + } + + @Test + public void testHistoricAfterAndBeforeCloseTimeAsStringQueryAsPost() { + Map parameters = getCompleteClosedDateAsStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyStringClosedParameterQueryInvocations(); + } + + @Test + public void testCaseActiveClosed() { + given() + .queryParam("active", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).active(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryActiveAsPost() { + Map body = new HashMap(); + body.put("active", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).active(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryCompleted() { + given() + .queryParam("completed", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).completed(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryCompletedAsPost() { + Map body = new HashMap(); + body.put("completed", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).completed(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryTerminated() { + given() + .queryParam("terminated", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).terminated(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryTerminatedAsPost() { + Map body = new HashMap(); + body.put("terminated", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).terminated(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryClosed() { + given() + .queryParam("closed", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).closed(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryClosedAsPost() { + Map body = new HashMap(); + body.put("closed", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).closed(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testCaseQueryNotClosed() { + List mockedHistoricCaseInstances = MockProvider.createMockRunningHistoricCaseInstances(); + HistoricCaseInstanceQuery mockedHistoricCaseInstanceQuery = mock(HistoricCaseInstanceQuery.class); + when(mockedHistoricCaseInstanceQuery.list()).thenReturn(mockedHistoricCaseInstances); + when(processEngine.getHistoryService().createHistoricCaseInstanceQuery()).thenReturn(mockedHistoricCaseInstanceQuery); + + Response response = given() + .queryParam("notClosed", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedHistoricCaseInstanceQuery); + inOrder.verify(mockedHistoricCaseInstanceQuery).notClosed(); + inOrder.verify(mockedHistoricCaseInstanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + String returnedCaseInstanceId = from(content).getString("[0].id"); + String returnedCloseTime = from(content).getString("[0].closeTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(null, returnedCloseTime); + } + + @Test + public void testCaseQueryNotClosedAsPost() { + List mockedHistoricCaseInstances = MockProvider.createMockRunningHistoricCaseInstances(); + HistoricCaseInstanceQuery mockedHistoricCaseInstanceQuery = mock(HistoricCaseInstanceQuery.class); + when(mockedHistoricCaseInstanceQuery.list()).thenReturn(mockedHistoricCaseInstances); + when(processEngine.getHistoryService().createHistoricCaseInstanceQuery()).thenReturn(mockedHistoricCaseInstanceQuery); + + Map body = new HashMap(); + body.put("notClosed", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedHistoricCaseInstanceQuery); + inOrder.verify(mockedHistoricCaseInstanceQuery).notClosed(); + inOrder.verify(mockedHistoricCaseInstanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + String returnedCaseInstanceId = from(content).getString("[0].id"); + String returnedCloseTime = from(content).getString("[0].closeTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(null, returnedCloseTime); + } + + @Test + public void testQueryByCaseInstanceIds() { + given() + .queryParam("caseInstanceIds", "firstCaseInstanceId,secondCaseInstanceId") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyCaseInstanceIdSetInvocation(); + } + + @Test + public void testQueryByCaseInstanceIdsAsPost() { + Map> parameters = getCompleteCaseInstanceIdSetQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyCaseInstanceIdSetInvocation(); + } + + @Test + public void testQueryByCaseDefinitionKeyNotIn() { + given() + .queryParam("caseDefinitionKeyNotIn", "firstCaseInstanceKey,secondCaseInstanceKey") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyCaseDefinitionKeyNotInListInvocation(); + } + + @Test + public void testQueryByCaseDefinitionKeyNotInAsPost() { + Map> parameters = getCompleteCaseDefinitionKeyNotInListQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verifyCaseDefinitionKeyNotInListInvocation(); + } + + @Test + public void testVariableValueEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gt_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueGreaterThan(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gteq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueGreaterThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lt_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLessThan(variableName, variableValue); + } + + @Test + public void testVariableValueLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lteq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLessThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + + @Test + public void testVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableValueEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueGreaterThan("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueLessThan("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueLessThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLikeAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + @Test + public void testVariableValueNotEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + + @Test + public void testVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given() + .queryParam("variables", queryValue) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueEquals(variableName1, variableValue1); + verify(mockedQuery).variableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).variableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricCaseInstanceQuery(createMockHistoricCaseInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List historicCaseInstances = from(content).getList(""); + assertThat(historicCaseInstances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockHistoricCaseInstanceQuery(createMockHistoricCaseInstancesTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List historicCaseInstances = from(content).getList(""); + assertThat(historicCaseInstances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdParameter() { + mockedQuery = setUpMockHistoricCaseInstanceQuery(Arrays.asList(MockProvider.createMockHistoricCaseInstance(null))); + + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testWithoutTenantIdPostParameter() { + mockedQuery = setUpMockHistoricCaseInstanceQuery(Arrays.asList(MockProvider.createMockHistoricCaseInstance(null))); + + Map queryParameters = new HashMap(); + queryParameters.put("withoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + private List createMockHistoricCaseInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricCaseInstance(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricCaseInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + + @Test + public void testCaseActivityIdListParameter() { + + Response response = given() + .queryParam("caseActivityIdIn", MockProvider.EXAMPLE_CASE_ACTIVITY_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseActivityIdIn(MockProvider.EXAMPLE_CASE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_CASE_ACTIVITY_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List historicCaseInstances = from(content).getList(""); + assertThat(historicCaseInstances).hasSize(1); + } + + @Test + public void testCaseActivityIdListPostParameter() { + + Map queryParameters = new HashMap(); + queryParameters.put("caseActivityIdIn", MockProvider.EXAMPLE_CASE_ACTIVITY_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseActivityIdIn(MockProvider.EXAMPLE_CASE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_CASE_ACTIVITY_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List historicCaseInstances = from(content).getList(""); + assertThat(historicCaseInstances).hasSize(1); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_CASE_INSTANCE_RESOURCE_URL); + } + + protected Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID); + parameters.put("caseInstanceBusinessKey", MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY); + parameters.put("caseInstanceBusinessKeyLike", MockProvider.EXAMPLE_CASE_INSTANCE_BUSINESS_KEY_LIKE); + parameters.put("caseDefinitionId", MockProvider.EXAMPLE_CASE_DEFINITION_ID); + parameters.put("caseDefinitionKey", MockProvider.EXAMPLE_CASE_DEFINITION_KEY); + parameters.put("caseDefinitionName", MockProvider.EXAMPLE_CASE_DEFINITION_NAME); + parameters.put("caseDefinitionNameLike", MockProvider.EXAMPLE_CASE_DEFINITION_NAME_LIKE); + parameters.put("createdBy", "createdBySomeone"); + parameters.put("superCaseInstanceId", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_CASE_INSTANCE_ID); + parameters.put("subCaseInstanceId", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUB_CASE_INSTANCE_ID); + parameters.put("superProcessInstanceId", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUPER_PROCESS_INSTANCE_ID); + parameters.put("subProcessInstanceId", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_SUB_PROCESS_INSTANCE_ID); + + return parameters; + } + + protected void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockedQuery).caseInstanceId(stringQueryParameters.get("caseInstanceId")); + verify(mockedQuery).caseInstanceBusinessKey(stringQueryParameters.get("caseInstanceBusinessKey")); + verify(mockedQuery).caseInstanceBusinessKeyLike(stringQueryParameters.get("caseInstanceBusinessKeyLike")); + verify(mockedQuery).caseDefinitionId(stringQueryParameters.get("caseDefinitionId")); + verify(mockedQuery).caseDefinitionKey(stringQueryParameters.get("caseDefinitionKey")); + verify(mockedQuery).caseDefinitionName(stringQueryParameters.get("caseDefinitionName")); + verify(mockedQuery).caseDefinitionNameLike(stringQueryParameters.get("caseDefinitionNameLike")); + verify(mockedQuery).createdBy(stringQueryParameters.get("createdBy")); + verify(mockedQuery).superCaseInstanceId(stringQueryParameters.get("superCaseInstanceId")); + verify(mockedQuery).subCaseInstanceId(stringQueryParameters.get("subCaseInstanceId")); + verify(mockedQuery).superProcessInstanceId(stringQueryParameters.get("superProcessInstanceId")); + verify(mockedQuery).subProcessInstanceId(stringQueryParameters.get("subProcessInstanceId")); + verify(mockedQuery).caseInstanceId(stringQueryParameters.get("caseInstanceId")); + + verify(mockedQuery).list(); + } + + protected Map getCompleteCreateDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("createdAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_AFTER)); + parameters.put("createdBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_BEFORE)); + + return parameters; + } + + protected void verifyCreateParameterQueryInvocations() { + Map createDateParameters = getCompleteCreateDateQueryParameters(); + + verify(mockedQuery).createdBefore(createDateParameters.get("createdBefore")); + verify(mockedQuery).createdAfter(createDateParameters.get("createdAfter")); + + verify(mockedQuery).list(); + } + + protected Map getCompleteCreateDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("createdAfter", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_AFTER); + parameters.put("createdBefore", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CREATED_BEFORE); + + return parameters; + } + + protected void verifyStringCreateParameterQueryInvocations() { + Map createDateParameters = getCompleteCreateDateAsStringQueryParameters(); + + verify(mockedQuery).createdBefore(DateTimeUtil.parseDate(createDateParameters.get("createdBefore"))); + verify(mockedQuery).createdAfter(DateTimeUtil.parseDate(createDateParameters.get("createdAfter"))); + + verify(mockedQuery).list(); + } + + protected Map getCompleteClosedDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("closedAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_AFTER)); + parameters.put("closedBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_BEFORE)); + + return parameters; + } + + protected void verifyClosedParameterQueryInvocations() { + Map closedDateParameters = getCompleteClosedDateQueryParameters(); + + verify(mockedQuery).closedAfter(closedDateParameters.get("closedAfter")); + verify(mockedQuery).closedBefore(closedDateParameters.get("closedBefore")); + + verify(mockedQuery).list(); + } + + protected Map getCompleteClosedDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("closedAfter", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_AFTER); + parameters.put("closedBefore", MockProvider.EXAMPLE_HISTORIC_CASE_INSTANCE_CLOSED_BEFORE); + + return parameters; + } + + protected void verifyStringClosedParameterQueryInvocations() { + Map closedDateParameters = getCompleteClosedDateAsStringQueryParameters(); + + verify(mockedQuery).closedAfter(DateTimeUtil.parseDate(closedDateParameters.get("closedAfter"))); + verify(mockedQuery).closedBefore(DateTimeUtil.parseDate(closedDateParameters.get("closedBefore"))); + + verify(mockedQuery).list(); + } + + protected Map> getCompleteCaseInstanceIdSetQueryParameters() { + Map> parameters = new HashMap>(); + + Set caseInstanceIds = new HashSet(); + caseInstanceIds.add("firstCaseInstanceId"); + caseInstanceIds.add("secondCaseInstanceId"); + + parameters.put("caseInstanceIds", caseInstanceIds); + + return parameters; + } + + protected void verifyCaseInstanceIdSetInvocation() { + Map> parameters = getCompleteCaseInstanceIdSetQueryParameters(); + + verify(mockedQuery).caseInstanceIds(parameters.get("caseInstanceIds")); + verify(mockedQuery).list(); + } + + protected Map> getCompleteCaseDefinitionKeyNotInListQueryParameters() { + Map> parameters = new HashMap>(); + + List caseInstanceIds = new ArrayList(); + caseInstanceIds.add("firstCaseInstanceKey"); + caseInstanceIds.add("secondCaseInstanceKey"); + + parameters.put("caseDefinitionKeyNotIn", caseInstanceIds); + + return parameters; + } + + protected void verifyCaseDefinitionKeyNotInListInvocation() { + Map> parameters = getCompleteCaseDefinitionKeyNotInListQueryParameters(); + + verify(mockedQuery).caseDefinitionKeyNotIn(parameters.get("caseDefinitionKeyNotIn")); + verify(mockedQuery).list(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ff916c4323bfb3c4623a437d871e422d37f813a0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestServiceInteractionTest.java @@ -0,0 +1,594 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_DECISION_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_DECISION_INSTANCE_ID; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceQuery; +import org.camunda.bpm.engine.history.SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder; +import org.camunda.bpm.engine.history.SetRemovalTimeToHistoricDecisionInstancesBuilder; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.JsonPathUtil; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import javax.ws.rs.core.Response.Status; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricDecisionInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_DECISION_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/decision-instance"; + protected static final String HISTORIC_SINGLE_DECISION_INSTANCE_URL = HISTORIC_DECISION_INSTANCE_URL + "/{id}"; + protected static final String HISTORIC_DECISION_INSTANCES_DELETE_ASYNC_URL = HISTORIC_DECISION_INSTANCE_URL + "/delete"; + protected static final String SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL = HISTORIC_DECISION_INSTANCE_URL + "/set-removal-time"; + + protected HistoryService historyServiceMock; + protected HistoricDecisionInstance historicInstanceMock; + protected HistoricDecisionInstanceQuery historicQueryMock; + + @Before + public void setUpRuntimeData() { + historyServiceMock = mock(HistoryService.class); + + // runtime service + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + + historicInstanceMock = MockProvider.createMockHistoricDecisionInstance(); + historicQueryMock = mock(HistoricDecisionInstanceQuery.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.createHistoricDecisionInstanceQuery()).thenReturn(historicQueryMock); + when(historicQueryMock.decisionInstanceId(anyString())).thenReturn(historicQueryMock); + when((Object) historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + } + + @Test + public void testGetSingleHistoricDecisionInstance() { + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_DECISION_INSTANCE_URL); + + InOrder inOrder = inOrder(historicQueryMock); + inOrder.verify(historicQueryMock).decisionInstanceId(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + inOrder.verify(historicQueryMock).singleResult(); + + String content = response.asString(); + + String returnedHistoricDecisionInstanceId = from(content).getString("id"); + String returnedDecisionDefinitionId = from(content).getString("decisionDefinitionId"); + String returnedDecisionDefinitionKey = from(content).getString("decisionDefinitionKey"); + String returnedDecisionDefinitionName = from(content).getString("decisionDefinitionName"); + String returnedEvaluationTime = from(content).getString("evaluationTime"); + String returnedProcessDefinitionId = from(content).getString("processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("processDefinitionKey"); + String returnedProcessInstanceId = from(content).getString("processInstanceId"); + String returnedCaseDefinitionId = from(content).getString("caseDefinitionId"); + String returnedCaseDefinitionKey = from(content).getString("caseDefinitionKey"); + String returnedCaseInstanceId = from(content).getString("caseInstanceId"); + String returnedActivityId = from(content).getString("activityId"); + String returnedActivityInstanceId = from(content).getString("activityInstanceId"); + String returnedUserId = from(content).getString("userId"); + List> returnedInputs = from(content).getList("inputs"); + List> returnedOutputs = from(content).getList("outputs"); + Double returnedCollectResultValue = from(content).getDouble("collectResultValue"); + String returnedTenantId = from(content).getString("tenantId"); + String returnedRootDecisionInstanceId = from(content).getString("rootDecisionInstanceId"); + String returnedDecisionRequirementsDefinitionId = from(content).getString("decisionRequirementsDefinitionId"); + String returnedDecisionRequirementsDefinitionKey = from(content).getString("decisionRequirementsDefinitionKey"); + + assertThat(returnedHistoricDecisionInstanceId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID)); + assertThat(returnedDecisionDefinitionId, is(EXAMPLE_DECISION_DEFINITION_ID)); + assertThat(returnedDecisionDefinitionKey, is(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY)); + assertThat(returnedDecisionDefinitionName, is(MockProvider.EXAMPLE_DECISION_DEFINITION_NAME)); + assertThat(returnedEvaluationTime, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATION_TIME)); + assertThat(returnedProcessDefinitionId, is(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + assertThat(returnedProcessDefinitionKey, is(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)); + assertThat(returnedProcessInstanceId, is(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + assertThat(returnedCaseDefinitionId, is(MockProvider.EXAMPLE_CASE_DEFINITION_ID)); + assertThat(returnedCaseDefinitionKey, is(MockProvider.EXAMPLE_CASE_DEFINITION_KEY)); + assertThat(returnedCaseInstanceId, is(MockProvider.EXAMPLE_CASE_INSTANCE_ID)); + assertThat(returnedActivityId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_ID)); + assertThat(returnedActivityInstanceId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_INSTANCE_ID)); + assertThat(returnedUserId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_USER_ID)); + assertThat(returnedInputs, is(nullValue())); + assertThat(returnedOutputs, is(nullValue())); + assertThat(returnedCollectResultValue, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_COLLECT_RESULT_VALUE)); + assertThat(returnedTenantId, is(MockProvider.EXAMPLE_TENANT_ID)); + assertThat(returnedRootDecisionInstanceId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID)); + assertThat(returnedDecisionRequirementsDefinitionId, is(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)); + assertThat(returnedDecisionRequirementsDefinitionKey, is(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY)); + } + + @Test + public void testGetSingleHistoricDecisionInstanceWithInputs() { + historicInstanceMock = MockProvider.createMockHistoricDecisionInstanceWithInputs(); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID) + .queryParam("includeInputs", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_DECISION_INSTANCE_URL); + + InOrder inOrder = inOrder(historicQueryMock); + inOrder.verify(historicQueryMock).decisionInstanceId(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + inOrder.verify(historicQueryMock).includeInputs(); + inOrder.verify(historicQueryMock, never()).includeOutputs(); + inOrder.verify(historicQueryMock).singleResult(); + + String content = response.asString(); + + List> returnedInputs = from(content).getList("inputs"); + List> returnedOutputs = from(content).getList("outputs"); + assertThat(returnedInputs, is(notNullValue())); + assertThat(returnedInputs, hasSize(3)); + assertThat(returnedOutputs, is(nullValue())); + } + + @Test + public void testGetSingleHistoricDecisionInstanceWithOutputs() { + historicInstanceMock = MockProvider.createMockHistoricDecisionInstanceWithOutputs(); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID) + .queryParam("includeOutputs", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_DECISION_INSTANCE_URL); + + InOrder inOrder = inOrder(historicQueryMock); + inOrder.verify(historicQueryMock).decisionInstanceId(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + inOrder.verify(historicQueryMock, never()).includeInputs(); + inOrder.verify(historicQueryMock).includeOutputs(); + inOrder.verify(historicQueryMock).singleResult(); + + String content = response.asString(); + + List> returnedInputs = from(content).getList("inputs"); + List> returnedOutputs = from(content).getList("outputs"); + assertThat(returnedInputs, is(nullValue())); + assertThat(returnedOutputs, is(notNullValue())); + assertThat(returnedOutputs, hasSize(3)); + } + + @Test + public void testGetSingleHistoricDecisionInstanceWithInputsAndOutputs() { + historicInstanceMock = MockProvider.createMockHistoricDecisionInstanceWithInputsAndOutputs(); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID) + .queryParam("includeInputs", true) + .queryParam("includeOutputs", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_DECISION_INSTANCE_URL); + + InOrder inOrder = inOrder(historicQueryMock); + inOrder.verify(historicQueryMock).decisionInstanceId(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + inOrder.verify(historicQueryMock).includeInputs(); + inOrder.verify(historicQueryMock).includeOutputs(); + inOrder.verify(historicQueryMock).singleResult(); + + String content = response.asString(); + + List> returnedInputs = from(content).getList("inputs"); + List> returnedOutputs = from(content).getList("outputs"); + assertThat(returnedInputs, is(notNullValue())); + assertThat(returnedInputs, hasSize(3)); + assertThat(returnedOutputs, is(notNullValue())); + assertThat(returnedOutputs, hasSize(3)); + } + + @Test + public void testGetSingleHistoricDecisionInstanceWithDisabledBinaryFetching() { + historicInstanceMock = MockProvider.createMockHistoricDecisionInstanceWithInputsAndOutputs(); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID) + .queryParam("disableBinaryFetching", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_DECISION_INSTANCE_URL); + + InOrder inOrder = inOrder(historicQueryMock); + inOrder.verify(historicQueryMock).decisionInstanceId(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + inOrder.verify(historicQueryMock).disableBinaryFetching(); + inOrder.verify(historicQueryMock).singleResult(); + } + + @Test + public void testGetSingleHistoricDecisionInstanceWithDisabledCustomObjectDeserialization() { + historicInstanceMock = MockProvider.createMockHistoricDecisionInstanceWithInputsAndOutputs(); + when(historicQueryMock.singleResult()).thenReturn(historicInstanceMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID) + .queryParam("disableCustomObjectDeserialization", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_SINGLE_DECISION_INSTANCE_URL); + + InOrder inOrder = inOrder(historicQueryMock); + inOrder.verify(historicQueryMock).decisionInstanceId(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + inOrder.verify(historicQueryMock).disableCustomObjectDeserialization(); + inOrder.verify(historicQueryMock).singleResult(); + } + + @Test + public void testGetNonExistingHistoricCaseInstance() { + when(historicQueryMock.singleResult()).thenReturn(null); + + given() + .pathParam("id", MockProvider.NON_EXISTING_ID) + .then().expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic decision instance with id '" + MockProvider.NON_EXISTING_ID + "' does not exist")) + .when() + .get(HISTORIC_SINGLE_DECISION_INSTANCE_URL); + } + + @Test + public void testDeleteAsync() { + List ids = Arrays.asList(EXAMPLE_DECISION_INSTANCE_ID); + + Batch batchEntity = MockProvider.createMockBatch(); + + when(historyServiceMock.deleteHistoricDecisionInstancesAsync(any(), any(), any())).thenReturn(batchEntity); + + Map messageBodyJson = new HashMap(); + messageBodyJson.put("historicDecisionInstanceIds", ids); + messageBodyJson.put("deleteReason", "a-delete-reason"); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_DECISION_INSTANCES_DELETE_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(historyServiceMock, times(1)).deleteHistoricDecisionInstancesAsync(eq(ids), eq((HistoricDecisionInstanceQuery) null), eq("a-delete-reason")); + } + + @Test + public void testDeleteAsyncWithQuery() { + Batch batchEntity = MockProvider.createMockBatch(); + + when(historyServiceMock.deleteHistoricDecisionInstancesAsync(any(), any(), any())).thenReturn(batchEntity); + + Map messageBodyJson = new HashMap(); + HistoricDecisionInstanceQueryDto query = new HistoricDecisionInstanceQueryDto(); + query.setDecisionDefinitionKey("decision"); + messageBodyJson.put("historicDecisionInstanceQuery", query); + messageBodyJson.put("deleteReason", "a-delete-reason"); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_DECISION_INSTANCES_DELETE_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(historyServiceMock, times(1)).deleteHistoricDecisionInstancesAsync(eq((List) null), any(HistoricDecisionInstanceQuery.class), eq("a-delete-reason")); + } + + @Test + public void testDeleteAsyncWithIdsAndQuery() { + Batch batchEntity = MockProvider.createMockBatch(); + + when(historyServiceMock.deleteHistoricDecisionInstancesAsync( + anyList(), + any(HistoricDecisionInstanceQuery.class), + anyString() + )).thenReturn(batchEntity); + + Map messageBodyJson = new HashMap(); + HistoricDecisionInstanceQueryDto query = new HistoricDecisionInstanceQueryDto(); + query.setDecisionDefinitionKey("decision"); + messageBodyJson.put("historicDecisionInstanceQuery", query); + + List ids = Arrays.asList(EXAMPLE_DECISION_INSTANCE_ID); + messageBodyJson.put("historicDecisionInstanceIds", ids); + messageBodyJson.put("deleteReason", "a-delete-reason"); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_DECISION_INSTANCES_DELETE_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(historyServiceMock, times(1)).deleteHistoricDecisionInstancesAsync(eq(ids), any(HistoricDecisionInstanceQuery.class), eq("a-delete-reason")); + } + + @Test + public void testDeleteAsyncWithBadRequestQuery() { + doThrow(new BadUserRequestException("process instance ids are empty")) + .when(historyServiceMock).deleteHistoricDecisionInstancesAsync(eq((List) null), eq((HistoricDecisionInstanceQuery) null), any()); + + given() + .contentType(ContentType.JSON).body(EMPTY_JSON_OBJECT) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(HISTORIC_DECISION_INSTANCES_DELETE_ASYNC_URL); + } + + @Test + public void shouldSetRemovalTime_ByIds() { + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricDecisionInstances()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicDecisionInstanceIds", Collections.singletonList(EXAMPLE_DECISION_INSTANCE_ID)); + payload.put("calculatedRemovalTime", true); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricDecisionInstances(); + + verify(builder).calculatedRemovalTime(); + verify(builder).byIds(EXAMPLE_DECISION_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_ByQuery() { + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricDecisionInstances()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("calculatedRemovalTime", true); + payload.put("historicDecisionInstanceQuery", Collections.singletonMap("decisionInstanceId", EXAMPLE_DECISION_INSTANCE_ID)); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricDecisionInstances(); + + verify(historicQueryMock).decisionInstanceId(EXAMPLE_DECISION_INSTANCE_ID); + + verify(builder).calculatedRemovalTime(); + verify(builder).byIds(null); + verify(builder).byQuery(historicQueryMock); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_Absolute() { + Date removalTime = new Date(); + + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricDecisionInstances()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicDecisionInstanceIds", Collections.singletonList(EXAMPLE_DECISION_INSTANCE_ID)); + payload.put("absoluteRemovalTime", removalTime); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricDecisionInstances(); + + verify(builder).absoluteRemovalTime(removalTime); + verify(builder).byIds(EXAMPLE_DECISION_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldNotSetRemovalTime_Absolute() { + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricDecisionInstances()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicDecisionInstanceIds", Collections.singletonList(EXAMPLE_DECISION_INSTANCE_ID)); + payload.put("absoluteRemovalTime", null); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL); + + SetRemovalTimeToHistoricDecisionInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricDecisionInstances(); + + verify(builder).byIds(EXAMPLE_DECISION_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldClearRemovalTime() { + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricDecisionInstances()) + .thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicDecisionInstanceIds", Collections.singletonList(EXAMPLE_DECISION_INSTANCE_ID)); + payload.put("clearedRemovalTime", true); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricDecisionInstances(); + + verify(builder).clearedRemovalTime(); + verify(builder).byIds(EXAMPLE_DECISION_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_Response() { + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricDecisionInstances()).thenReturn(builderMock); + + Batch batchEntity = MockProvider.createMockBatch(); + when(builderMock.executeAsync()).thenReturn(batchEntity); + + Response response = given() + .contentType(ContentType.JSON) + .body(Collections.emptyMap()) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldSetRemovalTime_ThrowBadUserException() { + SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricDecisionInstances()).thenReturn(builderMock); + + doThrow(BadUserRequestException.class).when(builderMock).executeAsync(); + + given() + .contentType(ContentType.JSON) + .body(Collections.emptyMap()) + .then() + .expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_DECISION_INSTANCES_ASYNC_URL); + } + + protected void verifyBatchJson(String batchJson) { + BatchDto batch = JsonPathUtil.from(batchJson).getObject("", BatchDto.class); + assertNotNull("The returned batch should not be null.", batch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId()); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..39521dcfaacdbd152d153c9f5915f60945ba955e --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionInstanceRestServiceQueryTest.java @@ -0,0 +1,693 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasEntry; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricDecisionInstance; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.impl.digest._apacheCommonsCodec.Base64; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.VariableValueDto; +import org.camunda.bpm.engine.rest.dto.converter.StringArrayConverter; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionInputInstanceDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricDecisionOutputInstanceDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.value.BytesValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.camunda.bpm.engine.variable.value.StringValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricDecisionInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_DECISION_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/decision-instance"; + protected static final String HISTORIC_DECISION_INSTANCE_COUNT_RESOURCE_URL = HISTORIC_DECISION_INSTANCE_RESOURCE_URL + "/count"; + + protected HistoricDecisionInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricDecisionInstanceQuery(MockProvider.createMockHistoricDecisionInstances()); + } + + protected HistoricDecisionInstanceQuery setUpMockHistoricDecisionInstanceQuery(List mockedHistoricDecisionInstances) { + HistoricDecisionInstanceQuery mockedHistoricDecisionInstanceQuery = mock(HistoricDecisionInstanceQuery.class); + when(mockedHistoricDecisionInstanceQuery.list()).thenReturn(mockedHistoricDecisionInstances); + when(mockedHistoricDecisionInstanceQuery.count()).thenReturn((long) mockedHistoricDecisionInstances.size()); + + when(processEngine.getHistoryService().createHistoricDecisionInstanceQuery()).thenReturn(mockedHistoricDecisionInstanceQuery); + + return mockedHistoricDecisionInstanceQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("caseDefinitionKey", queryKey) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "evaluationTime") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("evaluationTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByEvaluationTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("evaluationTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByEvaluationTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_DECISION_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricDecisionInstanceQuery() { + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + Response response = given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + String returnedHistoricDecisionInstanceId = from(content).getString("[0].id"); + String returnedDecisionDefinitionId = from(content).getString("[0].decisionDefinitionId"); + String returnedDecisionDefinitionKey = from(content).getString("[0].decisionDefinitionKey"); + String returnedDecisionDefinitionName = from(content).getString("[0].decisionDefinitionName"); + String returnedEvaluationTime = from(content).getString("[0].evaluationTime"); + String returnedRemovalTime = from(content).getString("[0].removalTime"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedCaseDefinitionKey = from(content).getString("[0].caseDefinitionKey"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedActivityInstanceId = from(content).getString("[0].activityInstanceId"); + List returnedInputs = from(content).getList("[0].inputs"); + List returnedOutputs = from(content).getList("[0].outputs"); + Double returnedCollectResultValue = from(content).getDouble("[0].collectResultValue"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedRootDecisionInstanceId = from(content).getString("[0].rootDecisionInstanceId"); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + String returnedDecisionRequirementsDefinitionId = from(content).getString("[0].decisionRequirementsDefinitionId"); + String returnedDecisionRequirementsDefinitionKey = from(content).getString("[0].decisionRequirementsDefinitionKey"); + + assertThat(returnedHistoricDecisionInstanceId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID)); + assertThat(returnedDecisionDefinitionId, is(MockProvider.EXAMPLE_DECISION_DEFINITION_ID)); + assertThat(returnedDecisionDefinitionKey, is(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY)); + assertThat(returnedDecisionDefinitionName, is(MockProvider.EXAMPLE_DECISION_DEFINITION_NAME)); + assertThat(returnedEvaluationTime, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATION_TIME)); + assertThat(returnedRemovalTime, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_REMOVAL_TIME)); + assertThat(returnedProcessDefinitionId, is(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)); + assertThat(returnedProcessDefinitionKey, is(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)); + assertThat(returnedProcessInstanceId, is(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)); + assertThat(returnedCaseDefinitionId, is(MockProvider.EXAMPLE_CASE_DEFINITION_ID)); + assertThat(returnedCaseDefinitionKey, is(MockProvider.EXAMPLE_CASE_DEFINITION_KEY)); + assertThat(returnedCaseInstanceId, is(MockProvider.EXAMPLE_CASE_INSTANCE_ID)); + assertThat(returnedActivityId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_ID)); + assertThat(returnedActivityInstanceId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_INSTANCE_ID)); + assertThat(returnedInputs, is(nullValue())); + assertThat(returnedOutputs, is(nullValue())); + assertThat(returnedCollectResultValue, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_COLLECT_RESULT_VALUE)); + assertThat(returnedTenantId, is(MockProvider.EXAMPLE_TENANT_ID)); + assertThat(returnedRootDecisionInstanceId, is(MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID)); + assertThat(returnedRootProcessInstanceId, is(MockProvider.EXAMPLE_ROOT_HISTORIC_PROCESS_INSTANCE_ID)); + assertThat(returnedDecisionRequirementsDefinitionId, is(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID)); + assertThat(returnedDecisionRequirementsDefinitionKey, is(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY)); + } + + @Test + public void testAdditionalParameters() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testIncludeInputs() { + mockedQuery = setUpMockHistoricDecisionInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricDecisionInstanceWithInputs())); + + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + Response response = given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .queryParam("includeInputs", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery).includeInputs(); + inOrder.verify(mockedQuery, never()).includeOutputs(); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + List> returnedInputs = from(content).getList("[0].inputs"); + List> returnedOutputs = from(content).getList("[0].outputs"); + + assertThat(returnedInputs, is(notNullValue())); + assertThat(returnedOutputs, is(nullValue())); + + verifyHistoricDecisionInputInstances(returnedInputs); + } + + @Test + public void testIncludeOutputs() { + mockedQuery = setUpMockHistoricDecisionInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricDecisionInstanceWithOutputs())); + + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + Response response = given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .queryParam("includeOutputs", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery, never()).includeInputs(); + inOrder.verify(mockedQuery).includeOutputs(); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + List> returnedInputs = from(content).getList("[0].inputs"); + List> returnedOutputs = from(content).getList("[0].outputs"); + + assertThat(returnedInputs, is(nullValue())); + assertThat(returnedOutputs, is(notNullValue())); + + verifyHistoricDecisionOutputInstances(returnedOutputs); + } + + @Test + public void testIncludeInputsAndOutputs() { + mockedQuery = setUpMockHistoricDecisionInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricDecisionInstanceWithInputsAndOutputs())); + + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + Response response = given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .queryParam("includeInputs", true) + .queryParam("includeOutputs", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery).includeInputs(); + inOrder.verify(mockedQuery).includeOutputs(); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertEquals(1, instances.size()); + Assert.assertNotNull(instances.get(0)); + + List> returnedInputs = from(content).getList("[0].inputs"); + List> returnedOutputs = from(content).getList("[0].outputs"); + + assertThat(returnedInputs, is(notNullValue())); + assertThat(returnedOutputs, is(notNullValue())); + + verifyHistoricDecisionInputInstances(returnedInputs); + verifyHistoricDecisionOutputInstances(returnedOutputs); + } + + @Test + public void testDefaultBinaryFetching() { + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery, never()).disableBinaryFetching(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testDisableBinaryFetching() { + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .queryParam("disableBinaryFetching", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery).disableBinaryFetching(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testDefaultCustomObjectDeserialization() { + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery, never()).disableCustomObjectDeserialization(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testDisableCustomObjectDeserialization() { + String decisionDefinitionId = MockProvider.EXAMPLE_DECISION_DEFINITION_ID; + + given() + .queryParam("decisionDefinitionId", decisionDefinitionId) + .queryParam("disableCustomObjectDeserialization", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).decisionDefinitionId(decisionDefinitionId); + inOrder.verify(mockedQuery).disableCustomObjectDeserialization(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testRootDecisionInstancesOnly() { + + given() + .queryParam("rootDecisionInstancesOnly", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).rootDecisionInstancesOnly(); + verify(mockedQuery).list(); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricDecisionInstanceQuery(createMockHistoricDecisionInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List historicDecisionInstances = from(content).getList(""); + assertThat(historicDecisionInstances).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdQueryParameter() { + // given + mockedQuery = setUpMockHistoricDecisionInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricDecisionInstanceBase(null))); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + private List createMockHistoricDecisionInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricDecisionInstanceBase(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricDecisionInstanceBase(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + + protected Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("decisionInstanceId", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + parameters.put("decisionInstanceIdIn", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID_IN); + parameters.put("decisionDefinitionId", MockProvider.EXAMPLE_DECISION_DEFINITION_ID); + parameters.put("decisionDefinitionIdIn", MockProvider.EXAMPLE_DECISION_DEFINITION_ID_IN); + parameters.put("decisionDefinitionKey", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY); + parameters.put("decisionDefinitionKeyIn", MockProvider.EXAMPLE_DECISION_DEFINITION_KEY_IN); + parameters.put("decisionDefinitionName", MockProvider.EXAMPLE_DECISION_DEFINITION_NAME); + parameters.put("decisionDefinitionNameLike", MockProvider.EXAMPLE_DECISION_DEFINITION_NAME_LIKE); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + parameters.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + parameters.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + parameters.put("caseDefinitionId", MockProvider.EXAMPLE_CASE_DEFINITION_ID); + parameters.put("caseDefinitionKey", MockProvider.EXAMPLE_CASE_DEFINITION_KEY); + parameters.put("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID); + parameters.put("activityIdIn", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_ID_IN); + parameters.put("activityInstanceIdIn", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ACTIVITY_INSTANCE_ID_IN); + parameters.put("evaluatedBefore", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATED_BEFORE); + parameters.put("evaluatedAfter", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_EVALUATED_AFTER); + parameters.put("userId", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_USER_ID); + parameters.put("rootDecisionInstanceId", MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID); + parameters.put("decisionRequirementsDefinitionId", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + parameters.put("decisionRequirementsDefinitionKey", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_KEY); + + return parameters; + } + + protected void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + StringArrayConverter stringArrayConverter = new StringArrayConverter(); + + verify(mockedQuery).decisionInstanceId(stringQueryParameters.get("decisionInstanceId")); + verify(mockedQuery).decisionInstanceIdIn(stringArrayConverter.convertQueryParameterToType(stringQueryParameters.get("decisionInstanceIdIn"))); + verify(mockedQuery).decisionDefinitionId(stringQueryParameters.get("decisionDefinitionId")); + verify(mockedQuery).decisionDefinitionIdIn(stringArrayConverter.convertQueryParameterToType(stringQueryParameters.get("decisionDefinitionIdIn"))); + verify(mockedQuery).decisionDefinitionKey(stringQueryParameters.get("decisionDefinitionKey")); + verify(mockedQuery).decisionDefinitionKeyIn(stringArrayConverter.convertQueryParameterToType(stringQueryParameters.get("decisionDefinitionKeyIn"))); + verify(mockedQuery).decisionDefinitionName(stringQueryParameters.get("decisionDefinitionName")); + verify(mockedQuery).decisionDefinitionNameLike(stringQueryParameters.get("decisionDefinitionNameLike")); + verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); + verify(mockedQuery).processDefinitionKey(stringQueryParameters.get("processDefinitionKey")); + verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); + verify(mockedQuery).caseDefinitionId(stringQueryParameters.get("caseDefinitionId")); + verify(mockedQuery).caseDefinitionKey(stringQueryParameters.get("caseDefinitionKey")); + verify(mockedQuery).caseInstanceId(stringQueryParameters.get("caseInstanceId")); + verify(mockedQuery).activityIdIn(stringArrayConverter.convertQueryParameterToType(stringQueryParameters.get("activityIdIn"))); + verify(mockedQuery).activityInstanceIdIn(stringArrayConverter.convertQueryParameterToType(stringQueryParameters.get("activityInstanceIdIn"))); + verify(mockedQuery).evaluatedBefore(DateTimeUtil.parseDate(stringQueryParameters.get("evaluatedBefore"))); + verify(mockedQuery).evaluatedAfter(DateTimeUtil.parseDate(stringQueryParameters.get("evaluatedAfter"))); + verify(mockedQuery).userId(stringQueryParameters.get("userId")); + verify(mockedQuery).rootDecisionInstanceId(stringQueryParameters.get("rootDecisionInstanceId")); + verify(mockedQuery).decisionRequirementsDefinitionId(stringQueryParameters.get("decisionRequirementsDefinitionId")); + verify(mockedQuery).decisionRequirementsDefinitionKey(stringQueryParameters.get("decisionRequirementsDefinitionKey")); + + verify(mockedQuery).list(); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then().expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_DECISION_INSTANCE_RESOURCE_URL); + } + + protected void verifyHistoricDecisionInputInstances(List> returnedInputs) { + assertThat(returnedInputs, hasSize(3)); + + // verify common properties + for (Map returnedInput : returnedInputs) { + assertThat(returnedInput, hasEntry("id", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_ID)); + assertThat(returnedInput, hasEntry("decisionInstanceId", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID)); + assertThat(returnedInput, hasEntry("clauseId", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CLAUSE_ID)); + assertThat(returnedInput, hasEntry("clauseName", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CLAUSE_NAME)); + assertThat(returnedInput, hasEntry("errorMessage", null)); + assertThat(returnedInput, hasEntry("createTime", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_CREATE_TIME)); + assertThat(returnedInput, hasEntry("removalTime", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INPUT_INSTANCE_REMOVAL_TIME)); + assertThat(returnedInput, hasEntry("rootProcessInstanceId", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INPUT_ROOT_PROCESS_INSTANCE_ID)); + } + + verifyStringValue(returnedInputs.get(0)); + verifyByteArrayValue(returnedInputs.get(1)); + verifySerializedValue(returnedInputs.get(2)); + + } + + protected void verifyHistoricDecisionOutputInstances(List> returnedOutputs) { + assertThat(returnedOutputs, hasSize(3)); + + // verify common properties + for (Map returnedOutput : returnedOutputs) { + assertThat(returnedOutput, hasEntry("id", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_ID)); + assertThat(returnedOutput, hasEntry("decisionInstanceId", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_INSTANCE_ID)); + assertThat(returnedOutput, hasEntry("clauseId", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CLAUSE_ID)); + assertThat(returnedOutput, hasEntry("clauseName", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CLAUSE_NAME)); + assertThat(returnedOutput, hasEntry("ruleId", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_RULE_ID)); + assertThat(returnedOutput, hasEntry("ruleOrder", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_RULE_ORDER)); + assertThat(returnedOutput, hasEntry("variableName", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_VARIABLE_NAME)); + assertThat(returnedOutput, hasEntry("errorMessage", null)); + assertThat(returnedOutput, hasEntry("createTime", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_CREATE_TIME)); + assertThat(returnedOutput, hasEntry("removalTime", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_INSTANCE_REMOVAL_TIME)); + assertThat(returnedOutput, hasEntry("rootProcessInstanceId", (Object) MockProvider.EXAMPLE_HISTORIC_DECISION_OUTPUT_ROOT_PROCESS_INSTANCE_ID)); + } + + verifyStringValue(returnedOutputs.get(0)); + verifyByteArrayValue(returnedOutputs.get(1)); + verifySerializedValue(returnedOutputs.get(2)); + } + + protected void verifyStringValue(Map stringValue) { + StringValue exampleValue = MockProvider.EXAMPLE_HISTORIC_DECISION_STRING_VALUE; + assertThat(stringValue, hasEntry("type", (Object) VariableValueDto.toRestApiTypeName(exampleValue.getType().getName()))); + assertThat(stringValue, hasEntry("value", (Object) exampleValue.getValue())); + assertThat(stringValue, hasEntry("valueInfo", (Object) Collections.emptyMap())); + } + + protected void verifyByteArrayValue(Map byteArrayValue) { + BytesValue exampleValue = MockProvider.EXAMPLE_HISTORIC_DECISION_BYTE_ARRAY_VALUE; + assertThat(byteArrayValue, hasEntry("type", (Object) VariableValueDto.toRestApiTypeName(exampleValue.getType().getName()))); + String byteString = Base64.encodeBase64String(exampleValue.getValue()).trim(); + assertThat(byteArrayValue, hasEntry("value", (Object) byteString)); + assertThat(byteArrayValue, hasEntry("valueInfo", (Object) Collections.emptyMap())); + } + + @SuppressWarnings("unchecked") + protected void verifySerializedValue(Map serializedValue) { + ObjectValue exampleValue = MockProvider.EXAMPLE_HISTORIC_DECISION_SERIALIZED_VALUE; + assertThat(serializedValue, hasEntry("type", (Object) VariableValueDto.toRestApiTypeName(exampleValue.getType().getName()))); + assertThat(serializedValue, hasEntry("value", exampleValue.getValue())); + Map valueInfo = (Map) serializedValue.get("valueInfo"); + assertThat(valueInfo, hasEntry("serializationDataFormat", exampleValue.getSerializationDataFormat())); + assertThat(valueInfo, hasEntry("objectTypeName", exampleValue.getObjectTypeName())); + + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionStatisticsRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionStatisticsRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..711bdf9c257203b280c0aac5b5456c75904b0287 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDecisionStatisticsRestServiceQueryTest.java @@ -0,0 +1,105 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import org.camunda.bpm.engine.history.HistoricDecisionInstanceStatistics; +import org.camunda.bpm.engine.history.HistoricDecisionInstanceStatisticsQuery; +import org.camunda.bpm.engine.impl.HistoricDecisionInstanceStatisticsQueryImpl; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.After; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.Mockito; + +import javax.ws.rs.core.Response; +import java.util.List; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * @author Askar Akhmerov + */ +public class HistoricDecisionStatisticsRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_URL = TEST_RESOURCE_ROOT_PATH + "/history"; + protected static final String HISTORIC_DECISION_STATISTICS_URL = HISTORY_URL + "/decision-requirements-definition/{id}/statistics"; + + private HistoricDecisionInstanceStatisticsQuery historicDecisionInstanceStatisticsQuery; + + @Before + public void setUpRuntimeData() { + setupHistoricDecisionStatisticsMock(); + } + + @After + public void tearDown() { + Mockito.reset(processEngine.getHistoryService(), historicDecisionInstanceStatisticsQuery); + } + + private void setupHistoricDecisionStatisticsMock() { + List mocks = MockProvider.createMockHistoricDecisionStatistics(); + + historicDecisionInstanceStatisticsQuery = + mock(HistoricDecisionInstanceStatisticsQueryImpl.class); + when(processEngine.getHistoryService() + .createHistoricDecisionInstanceStatisticsQuery(eq(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID))) + .thenReturn(historicDecisionInstanceStatisticsQuery); + + when(historicDecisionInstanceStatisticsQuery.decisionInstanceId(MockProvider.EXAMPLE_DECISION_INSTANCE_ID)).thenReturn(historicDecisionInstanceStatisticsQuery); + when(historicDecisionInstanceStatisticsQuery.unlimitedList()).thenReturn(mocks); + } + + @Test + public void testHistoricDefinitionInstanceStatisticsRetrieval() { + given().pathParam("id", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID) + .then().expect() + .statusCode(Response.Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("decisionDefinitionKey", hasItems(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY, MockProvider.ANOTHER_DECISION_DEFINITION_KEY)) + .body("evaluations", hasItems(1, 2)) + .when().get(HISTORIC_DECISION_STATISTICS_URL); + + verify(processEngine.getHistoryService()).createHistoricDecisionInstanceStatisticsQuery(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + } + + @Test + public void testHistoricDefinitionInstanceStatisticsRetrievalWithDefinitionInstance() { + given().pathParam("id", MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID) + .queryParam("decisionInstanceId", MockProvider.EXAMPLE_DECISION_INSTANCE_ID) + .then().expect() + .statusCode(Response.Status.OK.getStatusCode()) + .body("$.size()", is(2)) + .body("decisionDefinitionKey", hasItems(MockProvider.EXAMPLE_DECISION_DEFINITION_KEY, MockProvider.ANOTHER_DECISION_DEFINITION_KEY)) + .body("evaluations", hasItems(1, 2)) + .when().get(HISTORIC_DECISION_STATISTICS_URL); + + verify(processEngine.getHistoryService()).createHistoricDecisionInstanceStatisticsQuery(MockProvider.EXAMPLE_DECISION_REQUIREMENTS_DEFINITION_ID); + verify(historicDecisionInstanceStatisticsQuery).decisionInstanceId(MockProvider.EXAMPLE_DECISION_INSTANCE_ID); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..15aae2ed26d8433f44986324507b526af3393ab1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestServiceInteractionTest.java @@ -0,0 +1,392 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.either; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.history.HistoricDetailQuery; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.helper.MockHistoricVariableUpdateBuilder; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Daniel Meyer + * + */ +public class HistoricDetailRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_DETAIL_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/detail"; + protected static final String HISTORIC_DETAIL_URL = HISTORIC_DETAIL_RESOURCE_URL + "/{id}"; + protected static final String VARIABLE_INSTANCE_BINARY_DATA_URL = HISTORIC_DETAIL_URL + "/data"; + + protected HistoryService historyServiceMock; + + protected HistoricDetailQuery historicDetailQueryMock; + + @Before + public void setupTestData() { + historyServiceMock = mock(HistoryService.class); + historicDetailQueryMock = mock(HistoricDetailQuery.class); + + // mock engine service. + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + when(historyServiceMock.createHistoricDetailQuery()).thenReturn(historicDetailQueryMock); + } + + @Test + public void testGetSingleDetail() { + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate(); + + HistoricVariableUpdate detailMock = builder.build(); + + when(historicDetailQueryMock.detailId(detailMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableBinaryFetching()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(detailMock); + + given().pathParam("id", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("variableName", equalTo(builder.getName())) + .body("variableInstanceId", equalTo(builder.getVariableInstanceId())) + .body("variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo(builder.getValue())) + .body("processDefinitionKey", equalTo(builder.getProcessDefinitionKey())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("revision", equalTo(builder.getRevision())) + .body("time", equalTo(builder.getTime())) + .body("taskId", equalTo(builder.getTaskId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("caseDefinitionKey", equalTo(builder.getCaseDefinitionKey())) + .body("caseDefinitionId", equalTo(builder.getCaseDefinitionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("tenantId", equalTo(builder.getTenantId())) + .when().get(HISTORIC_DETAIL_URL); + + verify(historicDetailQueryMock, times(1)).disableBinaryFetching(); + } + + @Test + public void testGetSingleVariableUpdateDeserialized() { + ObjectValue serializedValue = MockObjectValue.fromObjectValue( + Variables.objectValue("a value").serializationDataFormat("aDataFormat").create()) + .objectTypeName("aTypeName"); + + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate().typedValue(serializedValue); + HistoricVariableUpdate variableInstanceMock = builder.build(); + + when(historicDetailQueryMock.detailId(variableInstanceMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableBinaryFetching()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given() + .pathParam("id", builder.getId()) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("variableName", equalTo(builder.getName())) + .body("variableInstanceId", equalTo(builder.getVariableInstanceId())) + .body("variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo("a value")) + .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) + .body("valueInfo.objectTypeName", equalTo("aTypeName")) + .body("initial", equalTo(false)) + .body("processDefinitionKey", equalTo(builder.getProcessDefinitionKey())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("revision", equalTo(builder.getRevision())) + .body("time", equalTo(builder.getTime())) + .body("taskId", equalTo(builder.getTaskId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("caseDefinitionKey", equalTo(builder.getCaseDefinitionKey())) + .body("caseDefinitionId", equalTo(builder.getCaseDefinitionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("tenantId", equalTo(builder.getTenantId())) + .when().get(HISTORIC_DETAIL_URL); + + verify(historicDetailQueryMock, times(1)).disableBinaryFetching(); + verify(historicDetailQueryMock, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testGetSingleVariableUpdateSerialized() { + ObjectValue serializedValue = Variables.serializedObjectValue("a serialized value") + .serializationDataFormat("aDataFormat").objectTypeName("aTypeName").create(); + + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate().typedValue(serializedValue); + HistoricVariableUpdate variableInstanceMock = builder.build(); + + when(historicDetailQueryMock.detailId(variableInstanceMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableBinaryFetching()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given() + .pathParam("id", builder.getId()) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("variableName", equalTo(builder.getName())) + .body("variableInstanceId", equalTo(builder.getVariableInstanceId())) + .body("variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo("a serialized value")) + .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) + .body("valueInfo.objectTypeName", equalTo("aTypeName")) + .body("initial", equalTo(false)) + .body("processDefinitionKey", equalTo(builder.getProcessDefinitionKey())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("revision", equalTo(builder.getRevision())) + .body("time", equalTo(builder.getTime())) + .body("taskId", equalTo(builder.getTaskId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("caseDefinitionKey", equalTo(builder.getCaseDefinitionKey())) + .body("caseDefinitionId", equalTo(builder.getCaseDefinitionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("tenantId", equalTo(builder.getTenantId())) + .when().get(HISTORIC_DETAIL_URL); + + verify(historicDetailQueryMock, times(1)).disableBinaryFetching(); + verify(historicDetailQueryMock, times(1)).disableCustomObjectDeserialization(); + } + + @Test + public void testGetSingleVariableInstanceForBinaryVariable() { + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate(); + + HistoricVariableUpdate detailMock = builder + .typedValue(Variables.byteArrayValue(null)) + .build(); + + when(historicDetailQueryMock.detailId(detailMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableBinaryFetching()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(detailMock); + + given().pathParam("id", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("variableName", equalTo(builder.getName())) + .body("variableInstanceId", equalTo(builder.getVariableInstanceId())) + .body("variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo(builder.getValue())) + .body("processDefinitionKey", equalTo(builder.getProcessDefinitionKey())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("revision", equalTo(builder.getRevision())) + .body("time", equalTo(builder.getTime())) + .body("taskId", equalTo(builder.getTaskId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("caseDefinitionKey", equalTo(builder.getCaseDefinitionKey())) + .body("caseDefinitionId", equalTo(builder.getCaseDefinitionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("tenantId", equalTo(builder.getTenantId())) + .when().get(HISTORIC_DETAIL_URL); + + verify(historicDetailQueryMock, times(1)).disableBinaryFetching(); + + } + + @Test + public void testGetNonExistingVariableInstance() { + + String nonExistingId = "nonExistingId"; + + when(historicDetailQueryMock.detailId(nonExistingId)).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableBinaryFetching()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", nonExistingId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Historic detail with Id 'nonExistingId' does not exist.")) + .when().get(HISTORIC_DETAIL_URL); + + verify(historicDetailQueryMock, times(1)).disableBinaryFetching(); + + } + + @Test + public void testBinaryDataForBinaryVariable() { + final byte[] byteContent = "some bytes".getBytes(); + + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate(); + + HistoricVariableUpdate detailMock = builder + .typedValue(Variables.byteArrayValue(byteContent)) + .build(); + + when(historicDetailQueryMock.detailId(detailMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(detailMock); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.BINARY.toString()) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + byte[] responseBytes = response.getBody().asByteArray(); + Assert.assertEquals(new String(byteContent), new String(responseBytes)); + verify(historicDetailQueryMock, never()).disableBinaryFetching(); + + } + + @Test + public void testBinaryDataForFileVariable() { + String filename = "test.txt"; + byte[] byteContent = "test".getBytes(); + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate(); + + HistoricVariableUpdate detailMock = builder + .typedValue(variableValue) + .build(); + + when(historicDetailQueryMock.detailId(detailMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(detailMock); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + . body(is(equalTo(new String(byteContent)))) + .and() + .header("Content-Disposition", "attachment; " + + "filename=\"" + filename + "\"; " + + "filename*=UTF-8''" + filename) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + //due to some problems with wildfly we gotta check this separately + String contentType = response.getContentType(); + assertThat(contentType, is(either(CoreMatchers.equalTo(ContentType.TEXT.toString() + "; charset=UTF-8")).or(CoreMatchers.equalTo(ContentType.TEXT.toString() + ";charset=UTF-8")))); + + verify(historicDetailQueryMock, never()).disableBinaryFetching(); + + } + + @Test + public void testBinaryDataForNonBinaryVariable() { + HistoricVariableUpdate detailMock = MockProvider.createMockHistoricVariableUpdate(); + + when(historicDetailQueryMock.detailId(detailMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(detailMock); + + given().pathParam("id", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Value of variable with id aHistoricVariableUpdateId is not a binary value")) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + verify(historicDetailQueryMock, never()).disableBinaryFetching(); + + } + + @Test + public void testGetBinaryDataForNonExistingVariableInstance() { + + String nonExistingId = "nonExistingId"; + + when(historicDetailQueryMock.detailId(nonExistingId)).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", nonExistingId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Historic detail with Id '"+nonExistingId+"' does not exist")) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + verify(historicDetailQueryMock, never()).disableBinaryFetching(); + + } + + @Test + public void testGetBinaryDataForNullFileVariable() { + String filename = "test.txt"; + byte[] byteContent = null; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate(); + + HistoricVariableUpdate detailMock = builder + .typedValue(variableValue) + .build(); + + when(historicDetailQueryMock.detailId(detailMock.getId())).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.disableCustomObjectDeserialization()).thenReturn(historicDetailQueryMock); + when(historicDetailQueryMock.singleResult()).thenReturn(detailMock); + + given().pathParam("id", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .contentType(ContentType.TEXT) + .and() + .body(is(equalTo(new String()))) + .when() + .get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..32898312d3ff4aa410c0674cada9dcd08c87e134 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricDetailRestServiceQueryTest.java @@ -0,0 +1,1426 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.history.HistoricDetail; +import org.camunda.bpm.engine.history.HistoricDetailQuery; +import org.camunda.bpm.engine.history.HistoricFormField; +import org.camunda.bpm.engine.history.HistoricVariableUpdate; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockHistoricVariableUpdateBuilder; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +/** + * @author Roman Smirnov + * @author Nikola Koevski + */ +public class HistoricDetailRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_DETAIL_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/detail"; + + protected static final String HISTORIC_DETAIL_COUNT_RESOURCE_URL = HISTORIC_DETAIL_RESOURCE_URL + "/count"; + + protected HistoricDetailQuery mockedQuery; + + protected HistoricVariableUpdate historicUpdateMock; + protected MockHistoricVariableUpdateBuilder historicUpdateBuilder; + + protected HistoricFormField historicFormFieldMock; + + @Before + public void setUpRuntimeData() { + List details = new ArrayList<>(); + + historicUpdateBuilder = MockProvider.mockHistoricVariableUpdate(); + historicUpdateMock = historicUpdateBuilder.build(); + historicFormFieldMock = MockProvider.createMockHistoricFormField(); + + details.add(historicUpdateMock); + details.add(historicFormFieldMock); + + mockedQuery = setUpMockedDetailsQuery(details); + } + + protected HistoricDetailQuery setUpMockedDetailsQuery(List detailMocks) { + HistoricDetailQuery mock = mock(HistoricDetailQuery.class); + when(mock.list()).thenReturn(detailMocks); + when(mock.count()).thenReturn((long) detailMocks.size()); + + when(processEngine.getHistoryService().createHistoricDetailQuery()).thenReturn(mock); + return mock; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processInstanceId", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + // GET + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verifyNoMoreInteractions(mockedQuery); + + reset(mockedQuery); + + // POST + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(Collections.emptyMap()) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryDisableObjectDeserialization() { + // GET + given() + .queryParam("deserializeValues", false) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + + reset(mockedQuery); + + // POST + given() + .queryParam("deserializeValues", false) + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(Collections.emptyMap()) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySortingAsPost( + OrderingBuilder.create() + .orderBy("processInstanceId").desc() + .orderBy("variableName").asc() + .orderBy("variableType").desc() + .orderBy("variableRevision").asc() + .orderBy("formPropertyId").desc() + .orderBy("time").asc() + .orderBy("occurrence").desc() + .orderBy("tenantId").asc() + .getJson(), + Status.OK); + + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByVariableName(); + inOrder.verify(mockedQuery).asc(); + inOrder.verify(mockedQuery).orderByVariableType(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByVariableRevision(); + inOrder.verify(mockedQuery).asc(); + inOrder.verify(mockedQuery).orderByFormPropertyId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByTime(); + inOrder.verify(mockedQuery).asc(); + inOrder.verify(mockedQuery).orderPartiallyByOccurrence(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("processInstanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testInvalidSecondarySortingOptions() { + executeAndVerifySortingAsPost( + OrderingBuilder.create() + .orderBy("processInstanceId").desc() + .orderBy("invalidParameter").asc() + .getJson(), + Status.BAD_REQUEST + ); + } + + @Test + public void testMissingSecondarySortingOptions() { + executeAndVerifySortingAsPost( + OrderingBuilder.create() + .orderBy("processInstanceId").desc() + .orderBy("variableName") + .getJson(), + Status.BAD_REQUEST + ); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + } + + protected void executeAndVerifySortingAsPost(List> sortingJson, Status expectedStatus) { + Map json = new HashMap<>(); + json.put("sorting", sortingJson); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(json) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableName", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableName", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("formPropertyId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByFormPropertyId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("formPropertyId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByFormPropertyId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableType", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableType(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableRevision", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableRevision(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("variableRevision", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByVariableRevision(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("time", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("time", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("occurrence", "asc", Status.OK); + inOrder.verify(mockedQuery).orderPartiallyByOccurrence(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("occurrence", "desc", Status.OK); + inOrder.verify(mockedQuery).orderPartiallyByOccurrence(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + // GET + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + + reset(mockedQuery); + + // POST + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .body(Collections.emptyMap()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + // GET + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + + reset(mockedQuery); + + // POST + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .queryParam("maxResults", maxResults) + .body(Collections.emptyMap()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + // GET + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + + reset(mockedQuery); + + // POST + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .queryParam("firstResult", firstResult) + .body(Collections.emptyMap()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(2)) + .when() + .get(HISTORIC_DETAIL_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricActivityQuery() { + // GET + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("[0].id", equalTo(historicUpdateBuilder.getId())) + .body("[0].variableName", equalTo(historicUpdateBuilder.getName())) + .body("[0].variableInstanceId", equalTo(historicUpdateBuilder.getVariableInstanceId())) + .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(historicUpdateBuilder.getTypedValue().getType()))) + .body("[0].value", equalTo(historicUpdateBuilder.getTypedValue().getValue())) + .body("[0].processDefinitionKey", equalTo(historicUpdateBuilder.getProcessDefinitionKey())) + .body("[0].processDefinitionId", equalTo(historicUpdateBuilder.getProcessDefinitionId())) + .body("[0].processInstanceId", equalTo(historicUpdateBuilder.getProcessInstanceId())) + .body("[0].errorMessage", equalTo(historicUpdateBuilder.getErrorMessage())) + .body("[0].activityInstanceId", equalTo(historicUpdateBuilder.getActivityInstanceId())) + .body("[0].revision", equalTo(historicUpdateBuilder.getRevision())) + .body("[0].time", equalTo(historicUpdateBuilder.getTime())) + .body("[0].taskId", equalTo(historicUpdateBuilder.getTaskId())) + .body("[0].executionId", equalTo(historicUpdateBuilder.getExecutionId())) + .body("[0].type", equalTo("variableUpdate")) + .body("[0].caseDefinitionKey", equalTo(historicUpdateBuilder.getCaseDefinitionKey())) + .body("[0].caseDefinitionId", equalTo(historicUpdateBuilder.getCaseDefinitionId())) + .body("[0].caseInstanceId", equalTo(historicUpdateBuilder.getCaseInstanceId())) + .body("[0].caseExecutionId", equalTo(historicUpdateBuilder.getCaseExecutionId())) + .body("[0].tenantId", equalTo(historicUpdateBuilder.getTenantId())) + .body("[0].userOperationId", equalTo(historicUpdateBuilder.getUserOperationId())) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + verifySimpleHistoricActivityQueryResponse(response); + } + + @Test + public void testSimpleHistoricActivityQueryPost() { + // POST + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(Collections.emptyMap()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("[0].id", equalTo(historicUpdateBuilder.getId())) + .body("[0].variableName", equalTo(historicUpdateBuilder.getName())) + .body("[0].variableInstanceId", equalTo(historicUpdateBuilder.getVariableInstanceId())) + .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName( + historicUpdateBuilder.getTypedValue().getType()))) + .body("[0].value", equalTo(historicUpdateBuilder.getTypedValue().getValue())) + .body("[0].processDefinitionKey", equalTo(historicUpdateBuilder.getProcessDefinitionKey())) + .body("[0].processDefinitionId", equalTo(historicUpdateBuilder.getProcessDefinitionId())) + .body("[0].processInstanceId", equalTo(historicUpdateBuilder.getProcessInstanceId())) + .body("[0].errorMessage", equalTo(historicUpdateBuilder.getErrorMessage())) + .body("[0].activityInstanceId", equalTo(historicUpdateBuilder.getActivityInstanceId())) + .body("[0].revision", equalTo(historicUpdateBuilder.getRevision())) + .body("[0].time", equalTo(historicUpdateBuilder.getTime())) + .body("[0].taskId", equalTo(historicUpdateBuilder.getTaskId())) + .body("[0].executionId", equalTo(historicUpdateBuilder.getExecutionId())) + .body("[0].type", equalTo("variableUpdate")) + .body("[0].caseDefinitionKey", equalTo(historicUpdateBuilder.getCaseDefinitionKey())) + .body("[0].caseDefinitionId", equalTo(historicUpdateBuilder.getCaseDefinitionId())) + .body("[0].caseInstanceId", equalTo(historicUpdateBuilder.getCaseInstanceId())) + .body("[0].caseExecutionId", equalTo(historicUpdateBuilder.getCaseExecutionId())) + .body("[0].tenantId", equalTo(historicUpdateBuilder.getTenantId())) + .body("[0].userOperationId", equalTo(historicUpdateBuilder.getUserOperationId())) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + verifySimpleHistoricActivityQueryResponse(response); + } + + private void verifySimpleHistoricActivityQueryResponse(Response response) { + String content = response.asString(); + List details = from(content).getList(""); + Assert.assertEquals("There should be two activity instance returned.", 2, details.size()); + Assert.assertNotNull("The returned details should not be null.", details.get(0)); + Assert.assertNotNull("The returned details should not be null.", details.get(1)); + + // note: element [0] is asserted as part of the fluent rest-assured invocation + + String returnedId2 = from(content).getString("[1].id"); + String returnedProcessDefinitionKey2 = from(content).getString("[1].processDefinitionKey"); + String returnedProcessDefinitionId2 = from(content).getString("[1].processDefinitionId"); + String returnedProcessInstanceId2 = from(content).getString("[1].processInstanceId"); + String returnedActivityInstanceId2 = from(content).getString("[1].activityInstanceId"); + String returnedExecutionId2 = from(content).getString("[1].executionId"); + String returnedTaskId2 = from(content).getString("[1].taskId"); + Date returnedTime2 = DateTimeUtil.parseDate(from(content).getString("[1].time")); + Date returnedRemovalTime = DateTimeUtil.parseDate(from(content).getString("[1].removalTime")); + String returnedFieldId = from(content).getString("[1].fieldId"); + String returnedFieldValue = from(content).getString("[1].fieldValue"); + String returnedType = from(content).getString("[1].type"); + String returnedCaseDefinitionKey2 = from(content).getString("[1].caseDefinitionKey"); + String returnedCaseDefinitionId2 = from(content).getString("[1].caseDefinitionId"); + String returnedCaseInstanceId2 = from(content).getString("[1].caseInstanceId"); + String returnedCaseExecutionId2 = from(content).getString("[1].caseExecutionId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + String returnedOperationId2 = from(content).getString("[1].userOperationId"); + String returnedRootProcessInstanceId = from(content).getString("[1].rootProcessInstanceId"); + + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_ID, returnedId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_KEY, returnedProcessDefinitionKey2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_PROC_DEF_ID, returnedProcessDefinitionId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_PROC_INST_ID, returnedProcessInstanceId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_ACT_INST_ID, returnedActivityInstanceId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_EXEC_ID, returnedExecutionId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_TASK_ID, returnedTaskId2); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_TIME), returnedTime2); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_TIME), returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_FIELD_ID, returnedFieldId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_VALUE, returnedFieldValue); + Assert.assertEquals("formField", returnedType); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_ID, returnedCaseDefinitionId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_DEF_KEY, returnedCaseDefinitionKey2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_INST_ID, returnedCaseInstanceId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_CASE_EXEC_ID, returnedCaseExecutionId2); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_EXEC_ID, returnedExecutionId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_FIELD_OPERATION_ID, returnedOperationId2); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_FORM_ROOT_PROCESS_INSTANCE_ID, returnedRootProcessInstanceId); + } + + @Test + public void testSerializableVariableInstanceRetrieval() { + ObjectValue serializedValue = Variables.serializedObjectValue("a serialized value").create(); + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate() + .typedValue(serializedValue); + + List details = new ArrayList<>(); + details.add(builder.build()); + + // GET + mockedQuery = setUpMockedDetailsQuery(details); + + given() + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("[0].value", equalTo("a serialized value")) + .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(serializedValue.getType()))) + .body("[0].errorMessage", nullValue()) + .when().get(HISTORIC_DETAIL_RESOURCE_URL); + + // should not resolve custom objects but existing API requires it +// verify(mockedQuery).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + + // POST + mockedQuery = setUpMockedDetailsQuery(details); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(Collections.emptyMap()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("[0].value", equalTo("a serialized value")) + .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(serializedValue.getType()))) + .body("[0].errorMessage", nullValue()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + // should not resolve custom objects but existing API requires it + // verify(mockedQuery).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testSpinVariableInstanceRetrieval() { + MockHistoricVariableUpdateBuilder builder = MockProvider.mockHistoricVariableUpdate() + .typedValue(Variables + .serializedObjectValue("aSerializedValue") + .serializationDataFormat("aDataFormat") + .objectTypeName("aRootType") + .create()); + + List details = new ArrayList<>(); + details.add(builder.build()); + + // GET + mockedQuery = setUpMockedDetailsQuery(details); + + given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT))) + .body("[0].errorMessage", nullValue()) + .body("[0].value", equalTo("aSerializedValue")) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, + equalTo("aRootType")) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, + equalTo("aDataFormat")) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + // POST + mockedQuery = setUpMockedDetailsQuery(details); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(Collections.emptyMap()) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("[0].variableType", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT))) + .body("[0].errorMessage", nullValue()) + .body("[0].value", equalTo("aSerializedValue")) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, + equalTo("aRootType")) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, + equalTo("aDataFormat")) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + } + + @Test + public void testQueryByProcessInstanceId() { + String processInstanceId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_PROC_INST_ID; + + // GET + given() + .queryParam("processInstanceId", processInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).processInstanceId(processInstanceId); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("processInstanceId", processInstanceId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).processInstanceId(processInstanceId); + } + + @Test + public void testQueryByExecutionId() { + String executionId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_EXEC_ID; + + // GET + given() + .queryParam("executionId", executionId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).executionId(executionId); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("executionId", executionId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).executionId(executionId); + } + + @Test + public void testQueryByOperationId() { + String operationId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_OPERATION_ID; + + // GET + given() + .queryParam("userOperationId", operationId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).userOperationId(operationId); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("userOperationId", operationId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).userOperationId(operationId); + } + + @Test + public void testQueryByActivityInstanceId() { + String activityInstanceId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ACT_INST_ID; + + // GET + given() + .queryParam("activityInstanceId", activityInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).activityInstanceId(activityInstanceId); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("activityInstanceId", activityInstanceId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).activityInstanceId(activityInstanceId); + } + + @Test + public void testQueryByTaskId() { + String taskId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TASK_ID; + + // GET + given() + .queryParam("taskId", taskId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).taskId(taskId); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("taskId", taskId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).taskId(taskId); + } + + @Test + public void testQueryByVariableInstanceId() { + String variableInstanceId = MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_ID; + + // GET + given() + .queryParam("variableInstanceId", variableInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableInstanceId(variableInstanceId); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("variableInstanceId", variableInstanceId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableInstanceId(variableInstanceId); + } + + @Test + public void testQueryByVariableTypeIn() { + String aVariableType = "string"; + String anotherVariableType = "integer"; + + // GET + given() + .queryParam("variableTypeIn", aVariableType + "," + anotherVariableType) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableTypeIn(aVariableType, anotherVariableType); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + String[] variableTypeIn = { aVariableType, anotherVariableType}; + jsonBody.put("variableTypeIn", variableTypeIn); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableTypeIn(aVariableType, anotherVariableType); + } + + @Test + public void shouldQueryByVariableNameLike_GET() { + String variableNameLike = "foo%"; + + // GET + given() + .queryParam("variableNameLike", variableNameLike) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableNameLike(variableNameLike); + } + + @Test + public void shouldQueryByVariableNameLike_POST() { + String variableNameLike = "foo%"; + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("variableNameLike", variableNameLike); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableNameLike(variableNameLike); + } + + @Test + public void testQueryByFormFields() { + // GET + given() + .queryParam("formFields", "true") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).formFields(); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("formFields", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).formFields(); + } + + @Test + public void testQueryByVariableUpdates() { + // GET + given() + .queryParam("variableUpdates", "true") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableUpdates(); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("variableUpdates", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).variableUpdates(); + } + + @Test + public void testQueryByExcludeTaskDetails() { + // GET + given() + .queryParam("excludeTaskDetails", "true") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).excludeTaskDetails(); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("excludeTaskDetails", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).excludeTaskDetails(); + } + + @Test + public void testQueryByCaseInstanceId() { + // GET + given() + .queryParam("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).caseInstanceId(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).caseInstanceId(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + } + + @Test + public void testQueryByCaseExecutionId() { + // GET + given() + .queryParam("caseExecutionId", MockProvider.EXAMPLE_CASE_EXECUTION_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).caseExecutionId(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("caseExecutionId", MockProvider.EXAMPLE_CASE_EXECUTION_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).caseExecutionId(MockProvider.EXAMPLE_CASE_EXECUTION_ID); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockedDetailsQuery(createMockHistoricDetailsTwoTenants()); + + // GET + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .queryParam("variableUpdates", "true") + .queryParam("formFields", "true") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).variableUpdates(); + verify(mockedQuery).formFields(); + verify(mockedQuery).list(); + + verifyTenantIdListParameterResponse(response); + + mockedQuery = setUpMockedDetailsQuery(createMockHistoricDetailsTwoTenants()); + + // POST + Map jsonBody = new HashMap<>(); + String[] exampleTenantIdList = {MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID}; + jsonBody.put("tenantIdIn", exampleTenantIdList); + jsonBody.put("variableUpdates", true); + jsonBody.put("formFields", true); + + response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).variableUpdates(); + verify(mockedQuery).formFields(); + verify(mockedQuery).list(); + + verifyTenantIdListParameterResponse(response); + } + + @Test + public void testQueryWithoutTenantIdQueryParameter() { + // given + List details = new ArrayList<>(); + + historicUpdateBuilder = MockProvider.mockHistoricVariableUpdate(null); + historicUpdateMock = historicUpdateBuilder.build(); + historicFormFieldMock = MockProvider.createMockHistoricFormField(null); + + details.add(historicUpdateMock); + details.add(historicFormFieldMock); + + mockedQuery = setUpMockedDetailsQuery(details); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryWithoutTenantIdPostParameter() { + // given + List details = new ArrayList<>(); + + historicUpdateBuilder = MockProvider.mockHistoricVariableUpdate(null); + historicUpdateMock = historicUpdateBuilder.build(); + historicFormFieldMock = MockProvider.createMockHistoricFormField(null); + + details.add(historicUpdateMock); + details.add(historicFormFieldMock); + + mockedQuery = setUpMockedDetailsQuery(details); + Map queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); + + // when + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(2); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + private void verifyTenantIdListParameterResponse(Response response) { + String content = response.asString(); + List historicDetails = from(content).getList(""); + assertThat(historicDetails).hasSize(4); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + String returnedTenantId3 = from(content).getString("[2].tenantId"); + String returnedTenantId4 = from(content).getString("[3].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId3).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + assertThat(returnedTenantId4).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testByProcessInstanceIdIn () { + String aProcessInstanceId = "aProcessInstanceId"; + String anotherProcessInstanceId = "anotherProcessInstanceId"; + + // GET + given() + .queryParam("processInstanceIdIn", aProcessInstanceId + "," + anotherProcessInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery) + .processInstanceIdIn(aProcessInstanceId, anotherProcessInstanceId); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + String[] processInstanceIdIn = {aProcessInstanceId, anotherProcessInstanceId}; + jsonBody.put("processInstanceIdIn", processInstanceIdIn); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery) + .processInstanceIdIn(aProcessInstanceId, anotherProcessInstanceId); + } + + @Test + public void testByOccurredBefore () { + // GET + given() + .queryParam("occurredBefore", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery) + .occurredBefore(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME)); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("occurredBefore", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery) + .occurredBefore(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME)); + } + + @Test + public void testByOccurredAfter () { + // GET + given() + .queryParam("occurredAfter", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery) + .occurredAfter(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME)); + + reset(mockedQuery); + + // POST + Map jsonBody = new HashMap<>(); + jsonBody.put("occurredAfter", MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(jsonBody) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery) + .occurredAfter(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_VAR_UPDATE_TIME)); + } + + @Test + public void testGetQueryWhereFileWasDeleted() { + doThrow(new IllegalArgumentException("Parameter 'filename' is null")).when(historicUpdateMock).getTypedValue(); + + // GET + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testPostQueryWhereFileWasDeleted() { + doThrow(new IllegalArgumentException("Parameter 'filename' is null")).when(historicUpdateMock).getTypedValue(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header("accept", MediaType.APPLICATION_JSON) + .body(Collections.emptyMap()) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_DETAIL_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verifyNoMoreInteractions(mockedQuery); + } + + private List createMockHistoricDetailsTwoTenants() { + List mockHistoricDetails = MockProvider.createMockHistoricDetails(MockProvider.EXAMPLE_TENANT_ID); + List mockHistoricDetails2 = MockProvider.createMockHistoricDetails(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + mockHistoricDetails.addAll(mockHistoricDetails2); + return mockHistoricDetails; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..18d2a3106655b670b6536dd215fb9bdae250173b --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestServiceInteractionTest.java @@ -0,0 +1,178 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.history.HistoricExternalTaskLog; +import org.camunda.bpm.engine.history.HistoricExternalTaskLogQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import javax.ws.rs.core.Response.Status; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +public class HistoricExternalTaskLogRestServiceInteractionTest extends AbstractRestServiceTest { + + protected static final String HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/external-task-log"; + protected static final String SINGLE_HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL = HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL + "/{id}"; + protected static final String HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_GET_ERROR_DETAILS_URL = SINGLE_HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL + "/error-details"; + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + protected ProcessEngine namedProcessEngine; + protected HistoryService mockHistoryService; + + protected HistoricExternalTaskLogQuery mockQuery; + + @Before + public void setUpRuntimeData() { + mockQuery = mock(HistoricExternalTaskLogQuery.class); + + HistoricExternalTaskLog mockedHistoricExternalTaskLog = MockProvider.createMockHistoricExternalTaskLog(); + + when(mockQuery.singleResult()).thenReturn(mockedHistoricExternalTaskLog); + when(mockQuery.logId(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID)).thenReturn(mockQuery); + + mockHistoryService = mock(HistoryService.class); + when(mockHistoryService.createHistoricExternalTaskLogQuery()).thenReturn(mockQuery); + + namedProcessEngine = getProcessEngine(MockProvider.EXAMPLE_PROCESS_ENGINE_NAME); + when(namedProcessEngine.getHistoryService()).thenReturn(mockHistoryService); + } + + @Test + public void testSimpleHistoricExternalTaskLogGet() { + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID)) + .body("timestamp", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TIMESTAMP)) + .body("removalTime", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_REMOVAL_TIME)) + .body("externalTaskId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXTERNAL_TASK_ID)) + .body("topicName", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TOPIC_NAME)) + .body("workerId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_WORKER_ID)) + .body("retries", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_RETRIES)) + .body("priority", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PRIORITY)) + .body("errorMessage", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ERROR_MSG)) + .body("activityId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_ID)) + .body("activityInstanceId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_INSTANCE_ID)) + .body("executionId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXECUTION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_INST_ID)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_ID)) + .body("processDefinitionKey", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_KEY)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("rootProcessInstanceId", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ROOT_PROC_INST_ID)) + .body("creationLog", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_CREATION_LOG)) + .body("failureLog", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_FAILURE_LOG)) + .body("successLog", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_SUCCESS_LOG)) + .body("deletionLog", equalTo(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_DELETION_LOG)) + .when() + .get(SINGLE_HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).logId(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID); + inOrder.verify(mockQuery).singleResult(); + } + + @Test + public void testHistoricExternalTaskLogGetIdDoesntExist() { + String id = "nonExistingId"; + + HistoricExternalTaskLogQuery invalidQueryNonExistingHistoricExternalTaskLog = mock(HistoricExternalTaskLogQuery.class); + when(mockHistoryService.createHistoricExternalTaskLogQuery().logId(id)).thenReturn(invalidQueryNonExistingHistoricExternalTaskLog); + when(invalidQueryNonExistingHistoricExternalTaskLog.singleResult()).thenReturn(null); + + given() + .pathParam("id", id) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic external task log with id " + id + " does not exist")) + .when() + .get(SINGLE_HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + } + + @Test + public void testGetErrorDetails() { + String errorDetails = "someErrorDetails"; + when(mockHistoryService.getHistoricExternalTaskLogErrorDetails(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID)).thenReturn(errorDetails); + + Response response = + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_GET_ERROR_DETAILS_URL); + + String content = response.asString(); + assertEquals(errorDetails, content); + } + + @Test + public void testGetErrorDetailsExternalTaskNotFound() { + String exceptionMessage = "historic external task log not found"; + doThrow(new ProcessEngineException(exceptionMessage)).when(mockHistoryService).getHistoricExternalTaskLogErrorDetails(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_GET_ERROR_DETAILS_URL); + } + + @Test + public void testGetErrorDetailsThrowsAuthorizationException() { + String exceptionMessage = "expected exception"; + doThrow(new AuthorizationException(exceptionMessage)).when(mockHistoryService).getHistoricExternalTaskLogErrorDetails(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_GET_ERROR_DETAILS_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..16ecf8be4a85b3e32ec62f203f80a049bd8d53d0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricExternalTaskLogRestServiceQueryTest.java @@ -0,0 +1,853 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.camunda.bpm.engine.history.HistoricExternalTaskLog; +import org.camunda.bpm.engine.history.HistoricExternalTaskLogQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static junit.framework.TestCase.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + +public class HistoricExternalTaskLogRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/external-task-log"; + protected static final String HISTORIC_EXTERNAL_TASK_LOG_COUNT_RESOURCE_URL = HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL + "/count"; + + protected static final long EXTERNAL_TASK_LOG_QUERY_MAX_PRIORITY = Long.MAX_VALUE; + protected static final long EXTERNAL_TASK_LOG_QUERY_MIN_PRIORITY = Long.MIN_VALUE; + + protected HistoricExternalTaskLogQuery mockedQuery; + + @Before + public void setUpRuntimeData() throws IOException { + mockedQuery = setUpMockHistoricExternalTaskLogQuery(MockProvider.createMockHistoricExternalTaskLogs()); + } + + protected HistoricExternalTaskLogQuery setUpMockHistoricExternalTaskLogQuery(List mockedHistoricExternalTaskLogs) { + HistoricExternalTaskLogQuery mockedHistoricExternalTaskLogQuery = mock(HistoricExternalTaskLogQuery.class); + when(mockedHistoricExternalTaskLogQuery.list()).thenReturn(mockedHistoricExternalTaskLogs); + when(mockedHistoricExternalTaskLogQuery.count()).thenReturn((long) mockedHistoricExternalTaskLogs.size()); + + when(processEngine.getHistoryService().createHistoricExternalTaskLogQuery()).thenReturn(mockedHistoricExternalTaskLogQuery); + + return mockedHistoricExternalTaskLogQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processDefinitionKey", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "processDefinitionId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("timestamp", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTimestamp(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("timestamp", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTimestamp(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("externalTaskId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByExternalTaskId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("externalTaskId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByExternalTaskId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("topicName", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTopicName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("topicName", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTopicName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("workerId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByWorkerId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("workerId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByWorkerId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("retries", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByRetries(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("retries", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByRetries(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("priority", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByPriority(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("priority", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByPriority(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("processInstanceId").desc() + .orderBy("timestamp").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByTimestamp(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + + @Test + public void testQueryCountForPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricExternalTaskLogQuery() { + String processInstanceId = MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + Response response = given() + .queryParam("processInstanceId", processInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processInstanceId(processInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List logs = from(content).getList(""); + assertEquals("There should be one historic externalTask log returned.", 1, logs.size()); + assertNotNull("The returned historic externalTask log should not be null.", logs.get(0)); + + String returnedId = from(content).getString("[0].id"); + String returnedTimestamp = from(content).getString("[0].timestamp"); + String returnedExternalTaskId = from(content).getString("[0].externalTaskId"); + String returnedExternalTaskTopicName = from(content).getString("[0].topicName"); + String returnedExternalTaskWorkerId = from(content).getString("[0].workerId"); + int returnedRetries = from(content).getInt("[0].retries"); + long returnedPriority = from(content).getLong("[0].priority"); + String returnedErrorMessage = from(content).getString("[0].errorMessage"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedActivityInstanceId = from(content).getString("[0].activityInstanceId"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + boolean returnedCreationLog = from(content).getBoolean("[0].creationLog"); + boolean returnedFailureLog = from(content).getBoolean("[0].failureLog"); + boolean returnedSuccessLog = from(content).getBoolean("[0].successLog"); + boolean returnedDeletionLog = from(content).getBoolean("[0].deletionLog"); + + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID, returnedId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TIMESTAMP, returnedTimestamp); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXTERNAL_TASK_ID, returnedExternalTaskId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TOPIC_NAME, returnedExternalTaskTopicName); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_WORKER_ID, returnedExternalTaskWorkerId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_RETRIES, returnedRetries); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PRIORITY, returnedPriority); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ERROR_MSG, returnedErrorMessage); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_ID, returnedActivityId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_INSTANCE_ID, returnedActivityInstanceId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXECUTION_ID, returnedExecutionId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_INST_ID, returnedProcessInstanceId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_ID, returnedProcessDefinitionId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_KEY, returnedProcessDefinitionKey); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_CREATION_LOG, returnedCreationLog); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_FAILURE_LOG, returnedFailureLog); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_SUCCESS_LOG, returnedSuccessLog); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_DELETION_LOG, returnedDeletionLog); + } + + @Test + public void testSimpleHistoricExternalTaskLogQueryAsPost() { + String processInstanceId = MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_INST_ID; + + Map json = new HashMap(); + json.put("processInstanceId", processInstanceId); + + Response response = + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processInstanceId(processInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List logs = from(content).getList(""); + assertEquals("There should be one historic externalTask log returned.", 1, logs.size()); + assertNotNull("The returned historic externalTask log should not be null.", logs.get(0)); + + String returnedId = from(content).getString("[0].id"); + String returnedTimestamp = from(content).getString("[0].timestamp"); + String returnedRemovalTime = from(content).getString("[0].removalTime"); + String returnedExternalTaskId = from(content).getString("[0].externalTaskId"); + String returnedExternalTaskTopicName = from(content).getString("[0].topicName"); + String returnedExternalTaskWorkerId = from(content).getString("[0].workerId"); + int returnedRetries = from(content).getInt("[0].retries"); + long returnedPriority = from(content).getLong("[0].priority"); + String returnedErrorMessage = from(content).getString("[0].errorMessage"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedActivityInstanceId = from(content).getString("[0].activityInstanceId"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + boolean returnedCreationLog = from(content).getBoolean("[0].creationLog"); + boolean returnedFailureLog = from(content).getBoolean("[0].failureLog"); + boolean returnedSuccessLog = from(content).getBoolean("[0].successLog"); + boolean returnedDeletionLog = from(content).getBoolean("[0].deletionLog"); + + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID, returnedId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TIMESTAMP, returnedTimestamp); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_REMOVAL_TIME, returnedRemovalTime); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXTERNAL_TASK_ID, returnedExternalTaskId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TOPIC_NAME, returnedExternalTaskTopicName); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_WORKER_ID, returnedExternalTaskWorkerId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_RETRIES, returnedRetries); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PRIORITY, returnedPriority); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ERROR_MSG, returnedErrorMessage); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_ID, returnedActivityId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ACTIVITY_INSTANCE_ID, returnedActivityInstanceId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXECUTION_ID, returnedExecutionId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_INST_ID, returnedProcessInstanceId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_ID, returnedProcessDefinitionId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_KEY, returnedProcessDefinitionKey); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ROOT_PROC_INST_ID, returnedRootProcessInstanceId); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_CREATION_LOG, returnedCreationLog); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_FAILURE_LOG, returnedFailureLog); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_SUCCESS_LOG, returnedSuccessLog); + assertEquals(MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_DELETION_LOG, returnedDeletionLog); + } + + @Test + public void testStringParameters() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testStringParametersAsPost() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + protected Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("logId", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ID); + parameters.put("externalTaskId", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_EXTERNAL_TASK_ID); + parameters.put("topicName", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_TOPIC_NAME); + parameters.put("workerId", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_WORKER_ID); + parameters.put("errorMessage", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_ERROR_MSG); + parameters.put("processInstanceId", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_INST_ID); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_ID); + parameters.put("processDefinitionKey", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_PROC_DEF_KEY); + + return parameters; + } + + protected void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockedQuery).logId(stringQueryParameters.get("logId")); + verify(mockedQuery).externalTaskId(stringQueryParameters.get("externalTaskId")); + verify(mockedQuery).topicName(stringQueryParameters.get("topicName")); + verify(mockedQuery).workerId(stringQueryParameters.get("workerId")); + verify(mockedQuery).errorMessage(stringQueryParameters.get("errorMessage")); + verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); + verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); + verify(mockedQuery).processDefinitionKey(stringQueryParameters.get("processDefinitionKey")); + + verify(mockedQuery).list(); + } + + @Test + public void testListParameters() { + String anActId = "anActId"; + String anotherActId = "anotherActId"; + + String anActInstId = "anActInstId"; + String anotherActInstId = "anotherActInstId"; + + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + given() + .queryParam("activityIdIn", anActId + "," + anotherActId) + .queryParam("activityInstanceIdIn", anActInstId + "," + anotherActInstId) + .queryParam("executionIdIn", anExecutionId + "," + anotherExecutionId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).activityIdIn(anActId, anotherActId); + verify(mockedQuery).activityInstanceIdIn(anActInstId, anotherActInstId); + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).list(); + } + + @Test + public void testListParametersAsPost() { + String anActId = "anActId"; + String anotherActId = "anotherActId"; + + String anActInstId = "anActInstId"; + String anotherActInstId = "anotherActInstId"; + + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + Map> json = new HashMap>(); + json.put("activityIdIn", Arrays.asList(anActId, anotherActId)); + json.put("activityInstanceIdIn", Arrays.asList(anActInstId, anotherActInstId)); + json.put("executionIdIn", Arrays.asList(anExecutionId, anotherExecutionId)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).activityIdIn(anActId, anotherActId); + verify(mockedQuery).activityInstanceIdIn(anActInstId, anotherActInstId); + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).list(); + } + + @Test + public void testBooleanParameters() { + Map params = getCompleteBooleanQueryParameters(); + + given() + .queryParams(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verifyBooleanParameterQueryInvocations(); + } + + @Test + public void testBooleanParametersAsPost() { + Map params = getCompleteBooleanQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verifyBooleanParameterQueryInvocations(); + + } + + protected Map getCompleteBooleanQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("creationLog", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_CREATION_LOG); + parameters.put("failureLog", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_FAILURE_LOG); + parameters.put("successLog", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_SUCCESS_LOG); + parameters.put("deletionLog", MockProvider.EXAMPLE_HISTORIC_EXTERNAL_TASK_LOG_IS_DELETION_LOG); + + return parameters; + } + + protected void verifyBooleanParameterQueryInvocations() { + verify(mockedQuery).creationLog(); + verify(mockedQuery).failureLog(); + verify(mockedQuery).successLog(); + verify(mockedQuery).deletionLog(); + verify(mockedQuery).list(); + } + + @Test + public void testIntegerParameters() { + Map params = getCompleteIntegerQueryParameters(); + + given() + .queryParams(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verifyIntegerParameterQueryInvocations(); + } + + @Test + public void testIntegerParametersAsPost() { + Map params = getCompleteIntegerQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verifyIntegerParameterQueryInvocations(); + + } + + protected Map getCompleteIntegerQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("priorityLowerThanOrEquals", EXTERNAL_TASK_LOG_QUERY_MAX_PRIORITY); + parameters.put("priorityHigherThanOrEquals", EXTERNAL_TASK_LOG_QUERY_MIN_PRIORITY); + + return parameters; + } + + protected void verifyIntegerParameterQueryInvocations() { + verify(mockedQuery).priorityLowerThanOrEquals(EXTERNAL_TASK_LOG_QUERY_MAX_PRIORITY); + verify(mockedQuery).priorityHigherThanOrEquals(EXTERNAL_TASK_LOG_QUERY_MIN_PRIORITY); + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricExternalTaskLogQuery(createMockHistoricExternalTaskLogsTwoTenants()); + + Response response = + given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List externalTaskLogs = from(content).getList(""); + assertThat(externalTaskLogs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockHistoricExternalTaskLogQuery(createMockHistoricExternalTaskLogsTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List externalTaskLogs = from(content).getList(""); + assertThat(externalTaskLogs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryWithoutTenantIdQueryParameter() { + // given + mockedQuery = setUpMockHistoricExternalTaskLogQuery(Collections.singletonList(MockProvider.createMockHistoricExternalTaskLog(null))); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryWithoutTenantIdPostParameter() { + // given + mockedQuery = setUpMockHistoricExternalTaskLogQuery(Collections.singletonList(MockProvider.createMockHistoricExternalTaskLog(null))); + Map queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); + + // when + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_EXTERNAL_TASK_LOG_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + private List createMockHistoricExternalTaskLogsTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricExternalTaskLog(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricExternalTaskLog(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricIdentityLinkLogRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricIdentityLinkLogRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..dd79cf4926702fb6ca36949c99c5126fcf4f0338 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricIdentityLinkLogRestServiceQueryTest.java @@ -0,0 +1,493 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricIdentityLinkLog; +import org.camunda.bpm.engine.history.HistoricIdentityLinkLogQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +import static io.restassured.RestAssured.expect; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +/** + * + * @author Deivarayan Azhagappan + * + */ +public class HistoricIdentityLinkLogRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_IDENTITY_LINK_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/history/identity-link-log"; + protected static final String HISTORY_IDENTITY_LINK_COUNT_QUERY_URL = HISTORY_IDENTITY_LINK_QUERY_URL + "/count"; + + private HistoricIdentityLinkLogQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricIdentityLinkQuery(MockProvider.createMockHistoricIdentityLinks()); + } + + private HistoricIdentityLinkLogQuery setUpMockHistoricIdentityLinkQuery(List mockedHistoricIdentityLinks) { + + HistoricIdentityLinkLogQuery mockedHistoricIdentityLinkQuery = mock(HistoricIdentityLinkLogQuery.class); + when(mockedHistoricIdentityLinkQuery.list()).thenReturn(mockedHistoricIdentityLinks); + when(mockedHistoricIdentityLinkQuery.count()).thenReturn((long) mockedHistoricIdentityLinks.size()); + + when(processEngine.getHistoryService().createHistoricIdentityLinkLogQuery()).thenReturn(mockedHistoricIdentityLinkQuery); + + return mockedHistoricIdentityLinkQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given().queryParam("userId", queryKey).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + } + + @Test + public void testNoParametersQuery() { + expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("processInstanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + @Test + public void testQueryWithoutTenantIdQueryParameter() { + // given + mockedQuery = setUpMockHistoricIdentityLinkQuery(Collections.singletonList(MockProvider.createMockHistoricIdentityLink(null))); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_IDENTITY_LINK_QUERY_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given().queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder).then().expect().statusCode(expectedStatus.getStatusCode()).when() + .get(HISTORY_IDENTITY_LINK_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given().queryParam("sortOrder", "asc").then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")).when() + .get(HISTORY_IDENTITY_LINK_QUERY_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + + // assignerId + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("assignerId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByAssignerId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("assignerId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByAssignerId(); + inOrder.verify(mockedQuery).desc(); + + // userId + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("userId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByUserId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("userId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByUserId(); + inOrder.verify(mockedQuery).desc(); + + // groupId + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("groupId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByGroupId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("groupId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByGroupId(); + inOrder.verify(mockedQuery).desc(); + + // taskId + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskId(); + inOrder.verify(mockedQuery).desc(); + + // operationType + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("operationType", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByOperationType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("operationType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByOperationType(); + inOrder.verify(mockedQuery).desc(); + + // processDefinitionId + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + // processDefinitionKey + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + // type + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("type", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("type", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByType(); + inOrder.verify(mockedQuery).desc(); + + // tenantId + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSimpleHistoricIdentityLinkQuery() { + Response response = given().then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List identityLinks = from(content).getList(""); + Assert.assertEquals("There should be one incident returned.", 1, identityLinks.size()); + Assert.assertNotNull("The returned incident should not be null.", identityLinks.get(0)); + + String returnedAssignerId = from(content).getString("[0].assignerId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedUserId = from(content).getString("[0].userId"); + String returnedGroupId = from(content).getString("[0].groupId"); + String returnedTaskId = from(content).getString("[0].taskId"); + String returnedType = from(content).getString("[0].type"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedOperationType = from(content).getString("[0].operationType"); + Date loggedDate = DateTimeUtil.parseDate(from(content).getString("[0].time")); + Date returnedRemovalTime = DateTimeUtil.parseDate(from(content).getString("[0].removalTime")); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TIME), loggedDate); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_ASSIGNER_ID, returnedAssignerId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_USER_ID, returnedUserId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_GROUP_ID, returnedGroupId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TASK_ID, returnedTaskId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TYPE, returnedType); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_OPERATION_TYPE, returnedOperationType); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_REMOVAL_TIME), returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_ROOT_PROC_INST_ID, returnedRootProcessInstanceId); + } + + @Test + public void testQueryByTenantIds() { + mockedQuery = setUpMockHistoricIdentityLinkQuery(Arrays.asList( + MockProvider.createMockHistoricIdentityLink(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricIdentityLink(MockProvider.ANOTHER_EXAMPLE_TENANT_ID))); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given().queryParam("firstResult", firstResult).queryParam("maxResults", maxResults).then().expect().statusCode(Status.OK.getStatusCode()).when() + .get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given().queryParam("maxResults", maxResults).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given().queryParam("firstResult", firstResult).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()).body("count", equalTo(1)).when().get(HISTORY_IDENTITY_LINK_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryByAssignerId() { + String assignerId = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_ASSIGNER_ID; + + given().queryParam("assignerId", assignerId).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).assignerId(assignerId); + } + + @Test + public void testQueryByUserId() { + String userId = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_USER_ID; + + given().queryParam("userId", userId).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).userId(userId); + } + + @Test + public void testQueryByGroupId() { + String groupId = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_GROUP_ID; + + given().queryParam("groupId", groupId).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).groupId(groupId); + } + + @Test + public void testQueryByTaskId() { + String taskId = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TASK_ID; + + given().queryParam("taskId", taskId).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).taskId(taskId); + } + + @Test + public void testQueryByProcessDefinitionId() { + String processDefinitionId = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_ID; + + given().queryParam("processDefinitionId", processDefinitionId).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).processDefinitionId(processDefinitionId); + } + + @Test + public void testQueryByProcessDefinitionKey() { + String processDefinitionKey = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_KEY; + + given().queryParam("processDefinitionKey", processDefinitionKey).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).processDefinitionKey(processDefinitionKey); + } + + @Test + public void testQueryByType() { + String type = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TYPE; + + given().queryParam("type", type).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).type(type); + } + + @Test + public void testQueryByOperationType() { + String operationType = MockProvider.EXAMPLE_HIST_IDENTITY_LINK_OPERATION_TYPE; + + given().queryParam("operationType", operationType).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).operationType(operationType); + } + + @Test + public void testQueryByDateBefore() { + Date dateBefore = DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TIME); + given().queryParam("dateBefore", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TIME).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).dateBefore(dateBefore); + } + + @Test + public void testQueryByDateAfter() { + Date dateAfter = DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TIME); + + given().queryParam("dateAfter", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TIME).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).dateAfter(dateAfter); + } + + @Test + public void testQueryByTenantId() { + String tenantId = MockProvider.EXAMPLE_TENANT_ID; + + given().queryParam("tenantIdIn", tenantId).then().expect().statusCode(Status.OK.getStatusCode()).when().get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verify(mockedQuery).tenantIdIn(tenantId); + } + + @Test + public void testAdditionalParameters() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_IDENTITY_LINK_QUERY_URL); + + verifyStringParameterQueryInvocations(); + } + protected Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + parameters.put("assignerId", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_ASSIGNER_ID); + parameters.put("dateBefore", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_DATE_BEFORE); + parameters.put("dateAfter", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_DATE_AFTER); + parameters.put("userId", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_USER_ID); + parameters.put("groupId", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_GROUP_ID); + parameters.put("taskId", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TASK_ID); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_ID); + parameters.put("processDefinitionKey", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_PROC_DEFINITION_KEY); + parameters.put("operationType", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_OPERATION_TYPE); + parameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID); + parameters.put("type", MockProvider.EXAMPLE_HIST_IDENTITY_LINK_TYPE); + return parameters; + } + protected void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + verify(mockedQuery).assignerId(stringQueryParameters.get("assignerId")); + verify(mockedQuery).userId(stringQueryParameters.get("userId")); + verify(mockedQuery).groupId(stringQueryParameters.get("groupId")); + verify(mockedQuery).taskId(stringQueryParameters.get("taskId")); + verify(mockedQuery).dateBefore(DateTimeUtil.parseDate(stringQueryParameters.get("dateBefore"))); + verify(mockedQuery).dateAfter(DateTimeUtil.parseDate(stringQueryParameters.get("dateAfter"))); + verify(mockedQuery).type(stringQueryParameters.get("type")); + verify(mockedQuery).operationType(stringQueryParameters.get("operationType")); + verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); + verify(mockedQuery).processDefinitionKey(stringQueryParameters.get("processDefinitionKey")); + verify(mockedQuery).tenantIdIn(stringQueryParameters.get("tenantIdIn")); + verify(mockedQuery).list(); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricIncidentRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricIncidentRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..29209c8810dcc1b06fc78c97f12606e2e6b8f293 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricIncidentRestServiceQueryTest.java @@ -0,0 +1,726 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_JOB_DEFINITION_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.NON_EXISTING_JOB_DEFINITION_ID; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricIncident; +import org.camunda.bpm.engine.history.HistoricIncidentQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * + * @author Roman Smirnov + * + */ +public class HistoricIncidentRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_INCIDENT_QUERY_URL = TEST_RESOURCE_ROOT_PATH + "/history/incident"; + protected static final String HISTORY_INCIDENT_COUNT_QUERY_URL = HISTORY_INCIDENT_QUERY_URL + "/count"; + + private HistoricIncidentQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricIncidentQuery(MockProvider.createMockHistoricIncidents()); + } + + private HistoricIncidentQuery setUpMockHistoricIncidentQuery(List mockedHistoricIncidents) { + HistoricIncidentQuery mockedHistoricIncidentQuery = mock(HistoricIncidentQuery.class); + + when(mockedHistoricIncidentQuery.list()).thenReturn(mockedHistoricIncidents); + when(mockedHistoricIncidentQuery.count()).thenReturn((long) mockedHistoricIncidents.size()); + + when(processEngine.getHistoryService().createHistoricIncidentQuery()).thenReturn(mockedHistoricIncidentQuery); + + return mockedHistoricIncidentQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processInstanceId", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("processInstanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentMessage", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentMessage", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("createTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCreateTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("createTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCreateTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCreateTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByEndTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentType", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentType(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentType", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentType(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("causeIncidentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCauseIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("causeIncidentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCauseIncidentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("rootCauseIncidentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByRootCauseIncidentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("rootCauseIncidentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByRootCauseIncidentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("configuration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByConfiguration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("configuration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByConfiguration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentState", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentState(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("incidentState", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByIncidentState(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORY_INCIDENT_COUNT_QUERY_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricTaskInstanceQuery() { + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List incidents = from(content).getList(""); + Assert.assertEquals("There should be one incident returned.", 1, incidents.size()); + Assert.assertNotNull("The returned incident should not be null.", incidents.get(0)); + + String returnedId = from(content).getString("[0].id"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedExecutionId = from(content).getString("[0].executionId"); + Date returnedCreateTime = DateTimeUtil.parseDate(from(content).getString("[0].createTime")); + Date returnedEndTime = DateTimeUtil.parseDate(from(content).getString("[0].endTime")); + String returnedIncidentType = from(content).getString("[0].incidentType"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedFailedActivityId = from(content).getString("[0].failedActivityId"); + String returnedCauseIncidentId = from(content).getString("[0].causeIncidentId"); + String returnedRootCauseIncidentId = from(content).getString("[0].rootCauseIncidentId"); + String returnedConfiguration = from(content).getString("[0].configuration"); + String returnedIncidentMessage = from(content).getString("[0].incidentMessage"); + Boolean returnedIncidentOpen = from(content).getBoolean("[0].open"); + Boolean returnedIncidentDeleted = from(content).getBoolean("[0].deleted"); + Boolean returnedIncidentResolved = from(content).getBoolean("[0].resolved"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedJobDefinitionId = from(content).getString("[0].jobDefinitionId"); + Date returnedRemovalTime = DateTimeUtil.parseDate(from(content).getString("[0].removalTime")); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + String returnedAnnotation = from(content).getString("[0].annotation"); + + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_PROC_INST_ID, returnedProcessInstanceId); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_INCIDENT_CREATE_TIME), returnedCreateTime); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_INCIDENT_END_TIME), returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_PROC_DEF_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_PROC_DEF_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_TYPE, returnedIncidentType); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_ACTIVITY_ID, returnedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_FAILED_ACTIVITY_ID, returnedFailedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_CAUSE_INCIDENT_ID, returnedCauseIncidentId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_ROOT_CAUSE_INCIDENT_ID, returnedRootCauseIncidentId); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_CONFIGURATION, returnedConfiguration); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_MESSAGE, returnedIncidentMessage); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_STATE_OPEN, returnedIncidentOpen); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_STATE_DELETED, returnedIncidentDeleted); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_STATE_RESOLVED, returnedIncidentResolved); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(EXAMPLE_JOB_DEFINITION_ID, returnedJobDefinitionId); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_INCIDENT_REMOVAL_TIME), returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HIST_INCIDENT_ROOT_PROC_INST_ID, returnedRootProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_USER_OPERATION_ANNOTATION, returnedAnnotation); + + } + + @Test + public void testQueryByIncidentId() { + String incidentId = MockProvider.EXAMPLE_HIST_INCIDENT_ID; + + given() + .queryParam("incidentId", incidentId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentId(incidentId); + } + + @Test + public void testQueryByIncidentType() { + String incidentType = MockProvider.EXAMPLE_HIST_INCIDENT_TYPE; + + given() + .queryParam("incidentType", incidentType) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentType(incidentType); + } + + @Test + public void testQueryByIncidentMessage() { + String incidentMessage = MockProvider.EXAMPLE_HIST_INCIDENT_MESSAGE; + + given() + .queryParam("incidentMessage", incidentMessage) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentMessage(incidentMessage); + } + + @Test + public void testQueryByIncidentMessageLike() { + String incidentMessage = MockProvider.EXAMPLE_HIST_INCIDENT_MESSAGE; + + given() + .queryParam("incidentMessageLike", incidentMessage) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).incidentMessageLike(incidentMessage); + } + + @Test + public void testQueryByProcessDefinitionId() { + String processDefinitionId = MockProvider.EXAMPLE_HIST_INCIDENT_PROC_DEF_ID; + + given() + .queryParam("processDefinitionId", processDefinitionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).processDefinitionId(processDefinitionId); + } + + @Test + public void testQueryByProcessDefinitionKey() { + String processDefinitionKey = MockProvider.EXAMPLE_HIST_INCIDENT_PROC_DEF_KEY; + + given() + .queryParam("processDefinitionKey", processDefinitionKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).processDefinitionKey(processDefinitionKey); + } + + @Test + public void testQueryByProcessDefinitionKeyIn() { + String key1 = "foo"; + String key2 = "bar"; + + given() + .queryParam("processDefinitionKeyIn", key1 + "," + key2) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + InOrder inOrder = inOrder(mockedQuery); + + inOrder.verify(mockedQuery).processDefinitionKeyIn("foo", "bar"); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessInstanceId() { + String processInstanceId = MockProvider.EXAMPLE_HIST_INCIDENT_PROC_INST_ID; + + given() + .queryParam("processInstanceId", processInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).processInstanceId(processInstanceId); + } + + @Test + public void testQueryByExecutionId() { + String executionId = MockProvider.EXAMPLE_HIST_INCIDENT_EXECUTION_ID; + + given() + .queryParam("executionId", executionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).executionId(executionId); + } + + @Test + public void testQueryByActivityId() { + String activityId = MockProvider.EXAMPLE_HIST_INCIDENT_ACTIVITY_ID; + + given() + .queryParam("activityId", activityId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).activityId(activityId); + } + + @Test + public void testQueryByCreateTimeBeforeAndAfter() { + given() + .queryParam("createTimeBefore", MockProvider.EXAMPLE_HIST_INCIDENT_CREATE_TIME_BEFORE) + .queryParam("createTimeAfter", MockProvider.EXAMPLE_HIST_INCIDENT_CREATE_TIME_AFTER) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).createTimeAfter(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_INCIDENT_CREATE_TIME_AFTER)); + verify(mockedQuery).createTimeBefore(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_INCIDENT_CREATE_TIME_BEFORE)); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByEndTimeBeforeAndAfter() { + given() + .queryParam("endTimeBefore", MockProvider.EXAMPLE_HIST_INCIDENT_END_TIME_BEFORE) + .queryParam("endTimeAfter", MockProvider.EXAMPLE_HIST_INCIDENT_END_TIME_AFTER) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).endTimeAfter(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_INCIDENT_END_TIME_AFTER)); + verify(mockedQuery).endTimeBefore(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HIST_INCIDENT_END_TIME_BEFORE)); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByFailedActivityId() { + String activityId = MockProvider.EXAMPLE_HIST_INCIDENT_FAILED_ACTIVITY_ID; + + given() + .queryParam("failedActivityId", activityId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).failedActivityId(activityId); + } + + @Test + public void testQueryByCauseIncidentId() { + String causeIncidentId = MockProvider.EXAMPLE_HIST_INCIDENT_CAUSE_INCIDENT_ID; + + given() + .queryParam("causeIncidentId", causeIncidentId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).causeIncidentId(causeIncidentId); + } + + @Test + public void testQueryByRootCauseIncidentId() { + String rootCauseIncidentId = MockProvider.EXAMPLE_HIST_INCIDENT_ROOT_CAUSE_INCIDENT_ID; + + given() + .queryParam("rootCauseIncidentId", rootCauseIncidentId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).rootCauseIncidentId(rootCauseIncidentId); + } + + @Test + public void testQueryByConfiguration() { + String configuration = MockProvider.EXAMPLE_HIST_INCIDENT_CONFIGURATION; + + given() + .queryParam("configuration", configuration) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).configuration(configuration); + } + + @Test + public void testQueryByHistoryConfiguration() { + String historyConfiguration = MockProvider.EXAMPLE_HIST_INCIDENT_HISTORY_CONFIGURATION; + + given() + .queryParam("historyConfiguration", historyConfiguration) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).historyConfiguration(historyConfiguration); + } + + @Test + public void testQueryByOpen() { + given() + .queryParam("open", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).open(); + } + + @Test + public void testQueryByResolved() { + given() + .queryParam("resolved", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).resolved(); + } + + @Test + public void testQueryByDeleted() { + given() + .queryParam("deleted", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).deleted(); + } + + @Test + public void testQueryByTenantIds() { + mockedQuery = setUpMockHistoricIncidentQuery(Arrays.asList( + MockProvider.createMockHistoricIncident(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricIncident(MockProvider.ANOTHER_EXAMPLE_TENANT_ID))); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List incidents = from(content).getList(""); + assertThat(incidents).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryWithoutTenantIdQueryParameter() { + // given + mockedQuery = setUpMockHistoricIncidentQuery(Collections.singletonList(MockProvider.createMockHistoricIncident(null))); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryByJobDefinitionIds() { + String jobDefinitionIds = EXAMPLE_JOB_DEFINITION_ID + "," + NON_EXISTING_JOB_DEFINITION_ID; + + given() + .queryParam("jobDefinitionIdIn", jobDefinitionIds) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORY_INCIDENT_QUERY_URL); + + verify(mockedQuery).jobDefinitionIdIn(EXAMPLE_JOB_DEFINITION_ID, NON_EXISTING_JOB_DEFINITION_ID); + verify(mockedQuery).list(); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d016ecf13f3fa1f701cbf48e2e561b3ad343496d --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestServiceInteractionTest.java @@ -0,0 +1,191 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.history.HistoricJobLog; +import org.camunda.bpm.engine.history.HistoricJobLogQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Roman Smirnov + * + */ +public class HistoricJobLogRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_JOB_LOG_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/job-log"; + protected static final String SINGLE_HISTORIC_JOB_LOG_RESOURCE_URL = HISTORIC_JOB_LOG_RESOURCE_URL + "/{id}"; + protected static final String HISTORIC_JOB_LOG_RESOURCE_GET_STACKTRACE_URL = SINGLE_HISTORIC_JOB_LOG_RESOURCE_URL + "/stacktrace"; + + protected ProcessEngine namedProcessEngine; + protected HistoryService mockHistoryService; + + protected HistoricJobLogQuery mockQuery; + + @Before + public void setUpRuntimeData() { + mockQuery = mock(HistoricJobLogQuery.class); + + HistoricJobLog mockedHistoricJobLog = MockProvider.createMockHistoricJobLog(); + + when(mockQuery.singleResult()).thenReturn(mockedHistoricJobLog); + when(mockQuery.logId(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID)).thenReturn(mockQuery); + + mockHistoryService = mock(HistoryService.class); + when(mockHistoryService.createHistoricJobLogQuery()).thenReturn(mockQuery); + + namedProcessEngine = getProcessEngine(MockProvider.EXAMPLE_PROCESS_ENGINE_NAME); + when(namedProcessEngine.getHistoryService()).thenReturn(mockHistoryService); + } + + @Test + public void testSimpleHistoricJobLogGet() { + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("id", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID)) + .body("timestamp", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_TIMESTAMP)) + .body("removalTime", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_REMOVAL_TIME)) + .body("jobId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_ID)) + .body("jobDueDate", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DUE_DATE)) + .body("jobRetries", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_RETRIES)) + .body("jobPriority", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_PRIORITY)) + .body("jobExceptionMessage", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_EXCEPTION_MSG)) + .body("jobDefinitionId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_ID)) + .body("jobDefinitionType", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_TYPE)) + .body("jobDefinitionConfiguration", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_CONFIG)) + .body("activityId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ACTIVITY_ID)) + .body("failedActivityId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_FAILED_ACTIVITY_ID)) + .body("executionId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_EXECUTION_ID)) + .body("processInstanceId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_INST_ID)) + .body("processDefinitionId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_ID)) + .body("processDefinitionKey", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_KEY)) + .body("deploymentId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_DEPLOYMENT_ID)) + .body("tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("hostname", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_HOSTNAME)) + .body("rootProcessInstanceId", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ROOT_PROC_INST_ID)) + .body("batchId", equalTo(MockProvider.EXAMPLE_BATCH_ID)) + .body("creationLog", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_CREATION_LOG)) + .body("failureLog", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_FAILURE_LOG)) + .body("successLog", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_SUCCESS_LOG)) + .body("deletionLog", equalTo(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_DELETION_LOG)) + .when() + .get(SINGLE_HISTORIC_JOB_LOG_RESOURCE_URL); + + InOrder inOrder = inOrder(mockQuery); + inOrder.verify(mockQuery).logId(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID); + inOrder.verify(mockQuery).singleResult(); + } + + @Test + public void testHistoricJobLogGetIdDoesntExist() { + String id = "nonExistingId"; + + HistoricJobLogQuery invalidQueryNonExistingHistoricJobLog = mock(HistoricJobLogQuery.class); + when(mockHistoryService.createHistoricJobLogQuery().logId(id)).thenReturn(invalidQueryNonExistingHistoricJobLog); + when(invalidQueryNonExistingHistoricJobLog.singleResult()).thenReturn(null); + + given() + .pathParam("id", id) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic job log with id " + id + " does not exist")) + .when() + .get(SINGLE_HISTORIC_JOB_LOG_RESOURCE_URL); + } + + @Test + public void testGetStacktrace() { + String stacktrace = "aStacktrace"; + when(mockHistoryService.getHistoricJobLogExceptionStacktrace(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID)).thenReturn(stacktrace); + + Response response = given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.TEXT) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_GET_STACKTRACE_URL); + + String content = response.asString(); + Assert.assertEquals(stacktrace, content); + } + + @Test + public void testGetStacktraceJobNotFound() { + String exceptionMessage = "historic job log not found"; + doThrow(new ProcessEngineException(exceptionMessage)).when(mockHistoryService).getHistoricJobLogExceptionStacktrace(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID) + .then() + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_GET_STACKTRACE_URL); + } + + @Test + public void testGetStacktraceThrowsAuthorizationException() { + String exceptionMessage = "expected exception"; + doThrow(new AuthorizationException(exceptionMessage)).when(mockHistoryService).getHistoricJobLogExceptionStacktrace(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID); + + given() + .pathParam("id", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID) + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(exceptionMessage)) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_GET_STACKTRACE_URL); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d6a693434d7a8416e6d28a7c54e26f56c5f76f09 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricJobLogRestServiceQueryTest.java @@ -0,0 +1,854 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricJobLog; +import org.camunda.bpm.engine.history.HistoricJobLogQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Roman Smirnov + * + */ +public class HistoricJobLogRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_JOB_LOG_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/job-log"; + protected static final String HISTORIC_JOB_LOG_COUNT_RESOURCE_URL = HISTORIC_JOB_LOG_RESOURCE_URL + "/count"; + + protected static final long JOB_LOG_QUERY_MAX_PRIORITY = Long.MAX_VALUE; + protected static final long JOB_LOG_QUERY_MIN_PRIORITY = Long.MIN_VALUE; + + protected HistoricJobLogQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricJobLogQuery(MockProvider.createMockHistoricJobLogs()); + } + + protected HistoricJobLogQuery setUpMockHistoricJobLogQuery(List mockedHistoricJogLogs) { + HistoricJobLogQuery mockedhistoricJobLogQuery = mock(HistoricJobLogQuery.class); + when(mockedhistoricJobLogQuery.list()).thenReturn(mockedHistoricJogLogs); + when(mockedhistoricJobLogQuery.count()).thenReturn((long) mockedHistoricJogLogs.size()); + + when(processEngine.getHistoryService().createHistoricJobLogQuery()).thenReturn(mockedhistoricJobLogQuery); + + return mockedhistoricJobLogQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processDefinitionKey", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).list(); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "processDefinitionId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("timestamp", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTimestamp(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("timestamp", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTimestamp(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobDueDate", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobDueDate(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobDueDate", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobDueDate(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobRetries", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobRetries(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobRetries", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobRetries(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByActivityId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deploymentId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeploymentId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("occurrence", "asc", Status.OK); + inOrder.verify(mockedQuery).orderPartiallyByOccurrence(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("occurrence", "desc", Status.OK); + inOrder.verify(mockedQuery).orderPartiallyByOccurrence(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobPriority", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByJobPriority(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("jobPriority", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByJobPriority(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("hostname", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHostname(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("hostname", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHostname(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("processInstanceId").desc() + .orderBy("timestamp").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_JOB_LOG_RESOURCE_URL); + + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByTimestamp(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_JOB_LOG_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + + @Test + public void testQueryCountForPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_JOB_LOG_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricJobLogQuery() { + String processInstanceId = MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + Response response = given() + .queryParam("processInstanceId", processInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processInstanceId(processInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List logs = from(content).getList(""); + Assert.assertEquals("There should be one historic job log returned.", 1, logs.size()); + Assert.assertNotNull("The returned historic job log should not be null.", logs.get(0)); + + verifyHistoricJobLogEntries(content); + } + + @Test + public void testSimpleHistoricJobLogQueryAsPost() { + String processInstanceId = MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_INST_ID; + + Map json = new HashMap(); + json.put("processInstanceId", processInstanceId); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processInstanceId(processInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List logs = from(content).getList(""); + Assert.assertEquals("There should be one historic job log returned.", 1, logs.size()); + Assert.assertNotNull("The returned historic job log should not be null.", logs.get(0)); + + verifyHistoricJobLogEntries(content); + } + + protected void verifyHistoricJobLogEntries(String content) { + String returnedId = from(content).getString("[0].id"); + String returnedTimestamp = from(content).getString("[0].timestamp"); + String returnedRemovalTime = from(content).getString("[0].removalTime"); + String returnedJobId = from(content).getString("[0].jobId"); + String returnedJobDueDate = from(content).getString("[0].jobDueDate"); + int returnedJobRetries = from(content).getInt("[0].jobRetries"); + long returnedJobPriority = from(content).getLong("[0].jobPriority"); + String returnedJobExceptionMessage = from(content).getString("[0].jobExceptionMessage"); + String returnedJobDefinitionId = from(content).getString("[0].jobDefinitionId"); + String returnedJobDefinitionType = from(content).getString("[0].jobDefinitionType"); + String returnedJobDefinitionConfiguration = from(content).getString("[0].jobDefinitionConfiguration"); + String returnedActivityId = from(content).getString("[0].activityId"); + String returnedFailedActivityId = from(content).getString("[0].failedActivityId"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedDeploymentId = from(content).getString("[0].deploymentId"); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + String returnedHostname = from(content).getString("[0].hostname"); + boolean returnedCreationLog = from(content).getBoolean("[0].creationLog"); + boolean returnedFailureLog = from(content).getBoolean("[0].failureLog"); + boolean returnedSuccessLog = from(content).getBoolean("[0].successLog"); + boolean returnedDeletionLog = from(content).getBoolean("[0].deletionLog"); + + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_TIMESTAMP, returnedTimestamp); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_REMOVAL_TIME, returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_ID, returnedJobId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DUE_DATE, returnedJobDueDate); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_RETRIES, returnedJobRetries); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_PRIORITY, returnedJobPriority); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_EXCEPTION_MSG, returnedJobExceptionMessage); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_ID, returnedJobDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_TYPE, returnedJobDefinitionType); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_CONFIG, returnedJobDefinitionConfiguration); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ACTIVITY_ID, returnedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_FAILED_ACTIVITY_ID, returnedFailedActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_EXECUTION_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_INST_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_DEPLOYMENT_ID, returnedDeploymentId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ROOT_PROC_INST_ID, returnedRootProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_HOSTNAME, returnedHostname); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_CREATION_LOG, returnedCreationLog); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_FAILURE_LOG, returnedFailureLog); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_SUCCESS_LOG, returnedSuccessLog); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_DELETION_LOG, returnedDeletionLog); + } + + @Test + public void testStringParameters() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testStringParametersAsPost() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + protected Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("logId", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_ID); + parameters.put("jobId", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_ID); + parameters.put("jobExceptionMessage", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_EXCEPTION_MSG); + parameters.put("jobDefinitionId", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_ID); + parameters.put("jobDefinitionType", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_CONFIG); + parameters.put("jobDefinitionConfiguration", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_JOB_DEF_CONFIG); + parameters.put("processInstanceId", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_INST_ID); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_ID); + parameters.put("processDefinitionKey", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_PROC_DEF_KEY); + parameters.put("deploymentId", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_DEPLOYMENT_ID); + parameters.put("hostname", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_HOSTNAME); + + return parameters; + } + + protected void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockedQuery).logId(stringQueryParameters.get("logId")); + verify(mockedQuery).jobId(stringQueryParameters.get("jobId")); + verify(mockedQuery).jobExceptionMessage(stringQueryParameters.get("jobExceptionMessage")); + verify(mockedQuery).jobDefinitionId(stringQueryParameters.get("jobDefinitionId")); + verify(mockedQuery).jobDefinitionType(stringQueryParameters.get("jobDefinitionType")); + verify(mockedQuery).jobDefinitionConfiguration(stringQueryParameters.get("jobDefinitionConfiguration")); + verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); + verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); + verify(mockedQuery).processDefinitionKey(stringQueryParameters.get("processDefinitionKey")); + verify(mockedQuery).deploymentId(stringQueryParameters.get("deploymentId")); + verify(mockedQuery).hostname(stringQueryParameters.get("hostname")); + + verify(mockedQuery).list(); + } + + @Test + public void testListParameters() { + String anActId = "anActId"; + String anotherActId = "anotherActId"; + + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + given() + .queryParam("activityIdIn", anActId + "," + anotherActId) + .queryParam("executionIdIn", anExecutionId + "," + anotherExecutionId) + .queryParam("failedActivityIdIn", anActId + "," + anotherActId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).activityIdIn(anActId, anotherActId); + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).failedActivityIdIn(anActId, anotherActId); + verify(mockedQuery).list(); + } + + @Test + public void testListParametersAsPost() { + String anActId = "anActId"; + String anotherActId = "anotherActId"; + + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + Map> json = new HashMap>(); + json.put("activityIdIn", Arrays.asList(anActId, anotherActId)); + json.put("executionIdIn", Arrays.asList(anExecutionId, anotherExecutionId)); + json.put("failedActivityIdIn", Arrays.asList(anActId, anotherActId)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).activityIdIn(anActId, anotherActId); + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).failedActivityIdIn(anActId, anotherActId); + verify(mockedQuery).list(); + } + + @Test + public void testBooleanParameters() { + Map params = getCompleteBooleanQueryParameters(); + + given() + .queryParams(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verifyBooleanParameterQueryInvocations(); + } + + @Test + public void testBooleanParametersAsPost() { + Map params = getCompleteBooleanQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + verifyBooleanParameterQueryInvocations(); + + } + + protected Map getCompleteBooleanQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("creationLog", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_CREATION_LOG); + parameters.put("failureLog", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_FAILURE_LOG); + parameters.put("successLog", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_SUCCESS_LOG); + parameters.put("deletionLog", MockProvider.EXAMPLE_HISTORIC_JOB_LOG_IS_DELETION_LOG); + + return parameters; + } + + protected void verifyBooleanParameterQueryInvocations() { + verify(mockedQuery).creationLog(); + verify(mockedQuery).failureLog(); + verify(mockedQuery).successLog(); + verify(mockedQuery).deletionLog(); + verify(mockedQuery).list(); + } + + @Test + public void testIntegerParameters() { + Map params = getCompleteIntegerQueryParameters(); + + given() + .queryParams(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verifyIntegerParameterQueryInvocations(); + } + + @Test + public void testIntegerParametersAsPost() { + Map params = getCompleteIntegerQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + verifyIntegerParameterQueryInvocations(); + + } + + protected Map getCompleteIntegerQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("jobPriorityLowerThanOrEquals", JOB_LOG_QUERY_MAX_PRIORITY); + parameters.put("jobPriorityHigherThanOrEquals", JOB_LOG_QUERY_MIN_PRIORITY); + + return parameters; + } + + protected void verifyIntegerParameterQueryInvocations() { + verify(mockedQuery).jobPriorityLowerThanOrEquals(JOB_LOG_QUERY_MAX_PRIORITY); + verify(mockedQuery).jobPriorityHigherThanOrEquals(JOB_LOG_QUERY_MIN_PRIORITY); + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricJobLogQuery(createMockHistoricJobLogsTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List jobLogs = from(content).getList(""); + assertThat(jobLogs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockHistoricJobLogQuery(createMockHistoricJobLogsTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List jobLogs = from(content).getList(""); + assertThat(jobLogs).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryWithoutTenantIdQueryParameter() { + // given + HistoricJobLog jobLog = MockProvider.createMockHistoricJobLog(null); + mockedQuery = setUpMockHistoricJobLogQuery(Collections.singletonList(jobLog)); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_JOB_LOG_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryWithoutTenantIdPostParameter() { + // given + HistoricJobLog jobLog = MockProvider.createMockHistoricJobLog(null); + mockedQuery = setUpMockHistoricJobLogQuery(Collections.singletonList(jobLog)); + Map queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); + + // when + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_JOB_LOG_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + private List createMockHistoricJobLogsTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricJobLog(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricJobLog(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..401a4657481d320ae4df9e4ed519a3c7e62016a6 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceInteractionTest.java @@ -0,0 +1,592 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.HashSet; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.batch.Batch; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.history.SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder; +import org.camunda.bpm.engine.history.SetRemovalTimeToHistoricProcessInstancesBuilder; +import org.camunda.bpm.engine.impl.HistoricProcessInstanceQueryImpl; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.batch.BatchDto; +import org.camunda.bpm.engine.rest.dto.history.HistoricProcessInstanceQueryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.JsonPathUtil; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +public class HistoricProcessInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String DELETE_REASON = "deleteReason"; + protected static final String TEST_DELETE_REASON = "test"; + protected static final String FAIL_IF_NOT_EXISTS = "failIfNotExists"; + protected static final String HISTORIC_PROCESS_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/process-instance"; + protected static final String HISTORIC_SINGLE_PROCESS_INSTANCE_URL = HISTORIC_PROCESS_INSTANCE_URL + "/{id}"; + protected static final String DELETE_HISTORIC_PROCESS_INSTANCES_ASYNC_URL = HISTORIC_PROCESS_INSTANCE_URL + "/delete"; + protected static final String SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL = HISTORIC_PROCESS_INSTANCE_URL + "/set-removal-time"; + protected static final String HISTORIC_SINGLE_PROCESS_INSTANCE_VARIABLES_URL = HISTORIC_PROCESS_INSTANCE_URL + "/{id}/variable-instances"; + + private HistoryService historyServiceMock; + + @Before + public void setUpRuntimeData() { + historyServiceMock = mock(HistoryService.class); + + // runtime service + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + } + + @Test + public void testGetSingleInstance() { + HistoricProcessInstance mockInstance = MockProvider.createMockHistoricProcessInstance(); + HistoricProcessInstanceQuery sampleInstanceQuery = mock(HistoricProcessInstanceQuery.class); + + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.processInstanceId(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.singleResult()).thenReturn(mockInstance); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_SINGLE_PROCESS_INSTANCE_URL); + + String content = response.asString(); + + String returnedProcessInstanceId = from(content).getString("id"); + String returnedProcessInstanceBusinessKey = from(content).getString("businessKey"); + String returnedProcessDefinitionId = from(content).getString("processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("processDefinitionKey"); + String returnedStartTime = from(content).getString("startTime"); + String returnedEndTime = from(content).getString("endTime"); + long returnedDurationInMillis = from(content).getLong("durationInMillis"); + String returnedStartUserId = from(content).getString("startUserId"); + String returnedStartActivityId = from(content).getString("startActivityId"); + String returnedDeleteReason = from(content).getString(DELETE_REASON); + String returnedSuperProcessInstanceId = from(content).getString("superProcessInstanceId"); + String returnedSuperCaseInstanceId = from(content).getString("superCaseInstanceId"); + String returnedCaseInstanceId = from(content).getString("caseInstanceId"); + String returnedTenantId = from(content).getString("tenantId"); + String returnedState = from(content).getString("state"); + String restartedProcessInstanceId = from(content).getString("restartedProcessInstanceId"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY, returnedProcessInstanceBusinessKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_TIME, returnedStartTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_END_TIME, returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DURATION_MILLIS, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_USER_ID, returnedStartUserId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_ACTIVITY_ID, returnedStartActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON, returnedDeleteReason); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_PROCESS_INSTANCE_ID, returnedSuperProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_CASE_INSTANCE_ID, returnedSuperCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STATE, returnedState); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, restartedProcessInstanceId); + + } + + @Test + public void testGetNonExistingProcessInstance() { + HistoricProcessInstanceQuery sampleInstanceQuery = mock(HistoricProcessInstanceQuery.class); + + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.processInstanceId(anyString())).thenReturn(sampleInstanceQuery); + when(sampleInstanceQuery.singleResult()).thenReturn(null); + + given().pathParam("id", "aNonExistingInstanceId") + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic process instance with id aNonExistingInstanceId does not exist")) + .when().get(HISTORIC_SINGLE_PROCESS_INSTANCE_URL); + } + + @Test + public void testDeleteProcessInstance() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(HISTORIC_SINGLE_PROCESS_INSTANCE_URL); + + verify(historyServiceMock).deleteHistoricProcessInstance(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + } + + @Test + public void testDeleteNonExistingProcessInstance() { + doThrow(new ProcessEngineException("expected exception")).when(historyServiceMock).deleteHistoricProcessInstance(anyString()); + + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()).contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", equalTo("Historic process instance with id " + MockProvider.EXAMPLE_PROCESS_INSTANCE_ID + " does not exist")) + .when().delete(HISTORIC_SINGLE_PROCESS_INSTANCE_URL); + } + + @Test + public void testDeleteNonExistingProcessInstanceIfExists() { + given().pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID).queryParam("failIfNotExists", false) + .then().expect().statusCode(Status.NO_CONTENT.getStatusCode()) + .when().delete(HISTORIC_SINGLE_PROCESS_INSTANCE_URL); + + verify(historyServiceMock).deleteHistoricProcessInstanceIfExists(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + } + + @Test + public void testDeleteProcessInstanceThrowsAuthorizationException() { + String message = "expected exception"; + doThrow(new AuthorizationException(message)).when(historyServiceMock).deleteHistoricProcessInstance(anyString()); + + given() + .pathParam("id", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID) + .then().expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .delete(HISTORIC_SINGLE_PROCESS_INSTANCE_URL); + } + + @Test + public void testDeleteAsync() { + List ids = Arrays.asList(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + Batch batchEntity = MockProvider.createMockBatch(); + when(historyServiceMock.deleteHistoricProcessInstancesAsync(anyList(), any(), anyString())).thenReturn(batchEntity); + + Map messageBodyJson = new HashMap(); + messageBodyJson.put("historicProcessInstanceIds", ids); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(historyServiceMock, times(1)).deleteHistoricProcessInstancesAsync( + eq(ids), eq((HistoricProcessInstanceQuery) null), eq(TEST_DELETE_REASON)); + } + + @Test + public void testDeleteAsyncWithQuery() { + Batch batchEntity = MockProvider.createMockBatch(); + when(historyServiceMock.deleteHistoricProcessInstancesAsync(any(), any(), any()) + ).thenReturn(batchEntity); + + Map messageBodyJson = new HashMap(); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + HistoricProcessInstanceQueryDto query = new HistoricProcessInstanceQueryDto(); + messageBodyJson.put("historicProcessInstanceQuery", query); + + Response response = given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when().post(DELETE_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + verifyBatchJson(response.asString()); + + verify(historyServiceMock, times(1)).deleteHistoricProcessInstancesAsync( + isNull(), isNull(), eq(TEST_DELETE_REASON)); + } + + + @Test + public void testDeleteAsyncWithBadRequestQuery() { + doThrow(new BadUserRequestException("process instance ids are empty")) + .when(historyServiceMock).deleteHistoricProcessInstancesAsync(eq((List) null), eq((HistoricProcessInstanceQuery) null), anyString()); + + Map messageBodyJson = new HashMap(); + messageBodyJson.put(DELETE_REASON, TEST_DELETE_REASON); + + given() + .contentType(ContentType.JSON).body(messageBodyJson) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when().post(DELETE_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + } + + @Test + public void testDeleteAllVariablesByProcessInstanceId() { + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(HISTORIC_SINGLE_PROCESS_INSTANCE_VARIABLES_URL); + + verify(historyServiceMock).deleteHistoricVariableInstancesByProcessInstanceId(EXAMPLE_PROCESS_INSTANCE_ID); + } + + @Test + public void testDeleteAllVariablesForNonExistingProcessInstance() { + doThrow(new NotFoundException("No historic process instance found with id: 'NON_EXISTING_ID'")) + .when(historyServiceMock).deleteHistoricVariableInstancesByProcessInstanceId("NON_EXISTING_ID"); + + given() + .pathParam("id", "NON_EXISTING_ID") + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No historic process instance found with id: 'NON_EXISTING_ID'")) + .when() + .delete(HISTORIC_SINGLE_PROCESS_INSTANCE_VARIABLES_URL); + } + + @Test + public void shouldSetRemovalTime_ByIds() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicProcessInstanceIds", Collections.singletonList(EXAMPLE_PROCESS_INSTANCE_ID)); + payload.put("calculatedRemovalTime", true); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricProcessInstances(); + + verify(builder).calculatedRemovalTime(); + verify(builder).byIds(EXAMPLE_PROCESS_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_ByQuery() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()).thenReturn(builderMock); + + HistoricProcessInstanceQuery query = mock(HistoricProcessInstanceQueryImpl.class, RETURNS_DEEP_STUBS); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(query); + + Map payload = new HashMap<>(); + payload.put("calculatedRemovalTime", true); + payload.put("historicProcessInstanceQuery", Collections.singletonMap("processDefinitionId", EXAMPLE_PROCESS_DEFINITION_ID)); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricProcessInstances(); + + verify(query).processDefinitionId(EXAMPLE_PROCESS_DEFINITION_ID); + + verify(builder).calculatedRemovalTime(); + verify(builder).byIds(null); + verify(builder).byQuery(query); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_Absolute() { + Date removalTime = new Date(); + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicProcessInstanceIds", Collections.singletonList(EXAMPLE_PROCESS_INSTANCE_ID)); + payload.put("absoluteRemovalTime", removalTime); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricProcessInstances(); + + verify(builder).absoluteRemovalTime(removalTime); + verify(builder).byIds(EXAMPLE_PROCESS_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_AbsoluteNoTime() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()).thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicProcessInstanceIds", Collections.singletonList(EXAMPLE_PROCESS_INSTANCE_ID)); + payload.put("absoluteRemovalTime", null); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + SetRemovalTimeToHistoricProcessInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricProcessInstances(); + + verify(builder).byIds(EXAMPLE_PROCESS_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_ClearTime() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()) + .thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicProcessInstanceIds", Collections.singletonList(EXAMPLE_PROCESS_INSTANCE_ID)); + payload.put("clearedRemovalTime", true); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricProcessInstances(); + + verify(builder).clearedRemovalTime(); + verify(builder).byIds(EXAMPLE_PROCESS_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_Response() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()).thenReturn(builderMock); + + Batch batchEntity = MockProvider.createMockBatch(); + when(builderMock.executeAsync()).thenReturn(batchEntity); + + Response response = given() + .contentType(ContentType.JSON) + .body(Collections.emptyMap()) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + verifyBatchJson(response.asString()); + } + + @Test + public void shouldSetRemovalTime_FailBadUserRequest() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()).thenReturn(builderMock); + + doThrow(BadUserRequestException.class).when(builderMock).executeAsync(); + + given() + .contentType(ContentType.JSON) + .body(Collections.emptyMap()) + .then() + .expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + } + + @Test + public void shouldSetRemovalTime_InChunks() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()) + .thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicProcessInstanceIds", Collections.singletonList(EXAMPLE_PROCESS_INSTANCE_ID)); + payload.put("clearedRemovalTime", true); + payload.put("updateInChunks", true); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricProcessInstances(); + + verify(builder).clearedRemovalTime(); + verify(builder).byIds(EXAMPLE_PROCESS_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).updateInChunks(); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void shouldSetRemovalTime_ChunkSize() { + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builderMock = + mock(SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder.class, RETURNS_DEEP_STUBS); + + when(historyServiceMock.setRemovalTimeToHistoricProcessInstances()) + .thenReturn(builderMock); + + Map payload = new HashMap<>(); + payload.put("historicProcessInstanceIds", Collections.singletonList(EXAMPLE_PROCESS_INSTANCE_ID)); + payload.put("clearedRemovalTime", true); + payload.put("updateChunkSize", 20); + + given() + .contentType(ContentType.JSON) + .body(payload) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when() + .post(SET_REMOVAL_TIME_HISTORIC_PROCESS_INSTANCES_ASYNC_URL); + + SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder builder = + historyServiceMock.setRemovalTimeToHistoricProcessInstances(); + + verify(builder).clearedRemovalTime(); + verify(builder).byIds(EXAMPLE_PROCESS_INSTANCE_ID); + verify(builder).byQuery(null); + verify(builder).chunkSize(20); + verify(builder).executeAsync(); + verifyNoMoreInteractions(builder); + } + + @Test + public void testOrQuery() { + // given + HistoricProcessInstanceQueryImpl mockedQuery = mock(HistoricProcessInstanceQueryImpl.class); + when(historyServiceMock.createHistoricProcessInstanceQuery()).thenReturn(mockedQuery); + String payload = "{\"orQueries\": [{ \"processDefinitionKey\": \"aKey\", \"processInstanceBusinessKey\": \"aBusinessKey\", \"completed\": true ,\"active\": true}]}"; + // when + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header(ACCEPT_JSON_HEADER) + .body(payload) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_URL); + + ArgumentCaptor argument = + ArgumentCaptor.forClass(HistoricProcessInstanceQueryImpl.class); + + verify(mockedQuery).addOrQuery(argument.capture()); + + // then + assertThat(argument.getValue().getProcessDefinitionKey()).isEqualTo("aKey"); + assertThat(argument.getValue().getBusinessKey()).isEqualTo("aBusinessKey"); + assertThat(argument.getValue().getState()).isEqualTo(new HashSet<>(Arrays.asList("COMPLETED", "ACTIVE"))); + } + + protected void verifyBatchJson(String batchJson) { + BatchDto batch = JsonPathUtil.from(batchJson).getObject("", BatchDto.class); + assertNotNull("The returned batch should not be null.", batch); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, batch.getId()); + assertEquals(MockProvider.EXAMPLE_BATCH_TYPE, batch.getType()); + assertEquals(MockProvider.EXAMPLE_BATCH_TOTAL_JOBS, batch.getTotalJobs()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOBS_PER_SEED, batch.getBatchJobsPerSeed()); + assertEquals(MockProvider.EXAMPLE_INVOCATIONS_PER_BATCH_JOB, batch.getInvocationsPerBatchJob()); + assertEquals(MockProvider.EXAMPLE_SEED_JOB_DEFINITION_ID, batch.getSeedJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_MONITOR_JOB_DEFINITION_ID, batch.getMonitorJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_JOB_DEFINITION_ID, batch.getBatchJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_TENANT_ID, batch.getTenantId()); + } + + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..51bb16a5bcd21770ae56b251b7a931bd1706b6d4 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceQueryTest.java @@ -0,0 +1,2515 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricProcessInstanceQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.variable.EqualsPrimitiveValue; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + + +public class HistoricProcessInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + protected static final String QUERY_PARAM_EXECUTED_JOB_BEFORE = "executedJobBefore"; + protected static final String QUERY_PARAM_EXECUTED_JOB_AFTER = "executedJobAfter"; + protected static final String QUERY_PARAM_EXECUTED_ACTIVITY_BEFORE = "executedActivityBefore"; + protected static final String QUERY_PARAM_EXECUTED_ACTIVITY_AFTER = "executedActivityAfter"; + protected static final String QUERY_PARAM_EXECUTED_ACTIVITY_IDS = "executedActivityIdIn"; + protected static final String QUERY_PARAM_ACTIVE_ACTIVITY_IDS = "activeActivityIdIn"; + protected static final String QUERY_PARAM_INCIDENT_IDS = "incidentIdIn"; + protected static final String QUERY_PARAM_ACTIVE_OR_FAILING_ACTIVITY_IDS = "activityIdIn"; + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_PROCESS_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/process-instance"; + protected static final String HISTORIC_PROCESS_INSTANCE_COUNT_RESOURCE_URL = HISTORIC_PROCESS_INSTANCE_RESOURCE_URL + "/count"; + + protected HistoricProcessInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricProcessInstanceQuery(MockProvider.createMockHistoricProcessInstances()); + } + + private HistoricProcessInstanceQuery setUpMockHistoricProcessInstanceQuery(List mockedHistoricProcessInstances) { + HistoricProcessInstanceQuery mockedhistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(mockedhistoricProcessInstanceQuery.list()).thenReturn(mockedHistoricProcessInstances); + when(mockedhistoricProcessInstanceQuery.count()).thenReturn((long) mockedHistoricProcessInstances.size()); + + when(processEngine.getHistoryService().createHistoricProcessInstanceQuery()).thenReturn(mockedhistoricProcessInstanceQuery); + + return mockedhistoricProcessInstanceQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processDefinitionKey", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidVariableRequests() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_" + invalidComparator + "_" + variableValue; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid variable comparator specified: " + invalidComparator)) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + // invalid format + queryValue = "invalidFormattedVariableQuery"; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("variable query parameter has to have format KEY_OPERATOR_VALUE")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("definitionId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "definitionId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("instanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionName", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("definitionVersion", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionVersion(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("businessKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceBusinessKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("businessKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceBusinessKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("startTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceStartTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("startTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceStartTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceEndTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceEndTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceDuration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceDuration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("instanceId").desc() + .orderBy("startTime").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByProcessInstanceStartTime(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_PROCESS_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_PROCESS_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricProcessQuery() { + String processInstanceId = MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + Response response = given() + .queryParam("processInstanceId", processInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processInstanceId(processInstanceId); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one process instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned process instance should not be null.", instances.get(0)); + + String returnedProcessInstanceId = from(content).getString("[0].id"); + String returnedProcessInstanceBusinessKey = from(content).getString("[0].businessKey"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedProcessDefinitionName = from(content).getString("[0].processDefinitionName"); + int returnedProcessDefinitionVersion= from(content).getInt("[0].processDefinitionVersion"); + String returnedStartTime = from(content).getString("[0].startTime"); + String returnedEndTime = from(content).getString("[0].endTime"); + String returnedRemovalTime = from(content).getString("[0].removalTime"); + long returnedDurationInMillis = from(content).getLong("[0].durationInMillis"); + String returnedStartUserId = from(content).getString("[0].startUserId"); + String returnedStartActivityId = from(content).getString("[0].startActivityId"); + String returnedDeleteReason = from(content).getString("[0].deleteReason"); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + String returnedSuperProcessInstanceId = from(content).getString("[0].superProcessInstanceId"); + String returnedSuperCaseInstanceId = from(content).getString("[0].superCaseInstanceId"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedState = from(content).getString("[0].state"); + String restartedProcessInstanceId = from(content).getString("[0].restartedProcessInstanceId"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY, returnedProcessInstanceBusinessKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME, returnedProcessDefinitionName); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION, returnedProcessDefinitionVersion); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_TIME, returnedStartTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_END_TIME, returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_REMOVAL_TIME, returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DURATION_MILLIS, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_USER_ID, returnedStartUserId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_ACTIVITY_ID, returnedStartActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON, returnedDeleteReason); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_ROOT_PROCESS_INSTANCE_ID, returnedRootProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_PROCESS_INSTANCE_ID, returnedSuperProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_CASE_INSTANCE_ID, returnedSuperCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STATE, returnedState); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, restartedProcessInstanceId); + } + + @Test + public void testGetHistoryProcessInstancesForRootProcessInstanceId() { + Response response = given().queryParam("rootProcessInstanceId", + MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_ROOT_PROCESS_INSTANCE_ID) + .header("accept", MediaType.APPLICATION_JSON) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + assertThat(instances).size().isGreaterThan(0); + + String returnedProcessInstanceId = from(content).getString("[0].id"); + String returnedProcessInstanceBusinessKey = from(content).getString("[0].businessKey"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedProcessDefinitionName = from(content).getString("[0].processDefinitionName"); + int returnedProcessDefinitionVersion = from(content).getInt("[0].processDefinitionVersion"); + String returnedStartTime = from(content).getString("[0].startTime"); + String returnedEndTime = from(content).getString("[0].endTime"); + String returnedRemovalTime = from(content).getString("[0].removalTime"); + long returnedDurationInMillis = from(content).getLong("[0].durationInMillis"); + String returnedStartUserId = from(content).getString("[0].startUserId"); + String returnedStartActivityId = from(content).getString("[0].startActivityId"); + String returnedDeleteReason = from(content).getString("[0].deleteReason"); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + String returnedSuperProcessInstanceId = from(content).getString("[0].superProcessInstanceId"); + String returnedSuperCaseInstanceId = from(content).getString("[0].superCaseInstanceId"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedState = from(content).getString("[0].state"); + String restartedProcessInstanceId = from(content).getString("[0].restartedProcessInstanceId"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY, returnedProcessInstanceBusinessKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME, returnedProcessDefinitionName); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_VERSION, returnedProcessDefinitionVersion); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_TIME, returnedStartTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_END_TIME, returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_REMOVAL_TIME, returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DURATION_MILLIS, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_USER_ID, returnedStartUserId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_START_ACTIVITY_ID, returnedStartActivityId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_DELETE_REASON, returnedDeleteReason); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_ROOT_PROCESS_INSTANCE_ID, + returnedRootProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_PROCESS_INSTANCE_ID, + returnedSuperProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_CASE_INSTANCE_ID, + returnedSuperCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_CASE_INSTANCE_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STATE, returnedState); + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, restartedProcessInstanceId); + } + + @Test + public void testAdditionalParametersExcludingProcesses() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + @Test + public void testAdditionalParametersExcludingProcessesAsPost() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + } + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("processInstanceId", MockProvider.EXAMPLE_PROCESS_INSTANCE_ID); + parameters.put("processInstanceBusinessKey", MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY); + parameters.put("processInstanceBusinessKeyLike", MockProvider.EXAMPLE_PROCESS_INSTANCE_BUSINESS_KEY_LIKE); + parameters.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + parameters.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + parameters.put("processDefinitionName", MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME); + parameters.put("processDefinitionNameLike", MockProvider.EXAMPLE_PROCESS_DEFINITION_NAME_LIKE); + parameters.put("startedBy", "startedBySomeone"); + parameters.put("superProcessInstanceId", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_PROCESS_INSTANCE_ID); + parameters.put("subProcessInstanceId", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUB_PROCESS_INSTANCE_ID); + parameters.put("superCaseInstanceId", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUPER_CASE_INSTANCE_ID); + parameters.put("subCaseInstanceId", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_SUB_CASE_INSTANCE_ID); + parameters.put("caseInstanceId", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_CASE_INSTANCE_ID); + parameters.put("state", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STATE); + parameters.put("incidentType", MockProvider.EXAMPLE_INCIDENT_TYPE); + parameters.put("rootProcessInstanceId", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_ROOT_PROCESS_INSTANCE_ID); + + return parameters; + } + + private void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); + verify(mockedQuery).processInstanceBusinessKey(stringQueryParameters.get("processInstanceBusinessKey")); + verify(mockedQuery).processInstanceBusinessKeyLike(stringQueryParameters.get("processInstanceBusinessKeyLike")); + verify(mockedQuery).processDefinitionId(stringQueryParameters.get("processDefinitionId")); + verify(mockedQuery).processDefinitionKey(stringQueryParameters.get("processDefinitionKey")); + verify(mockedQuery).processDefinitionName(stringQueryParameters.get("processDefinitionName")); + verify(mockedQuery).processDefinitionNameLike(stringQueryParameters.get("processDefinitionNameLike")); + verify(mockedQuery).startedBy(stringQueryParameters.get("startedBy")); + verify(mockedQuery).superProcessInstanceId(stringQueryParameters.get("superProcessInstanceId")); + verify(mockedQuery).subProcessInstanceId(stringQueryParameters.get("subProcessInstanceId")); + verify(mockedQuery).superCaseInstanceId(stringQueryParameters.get("superCaseInstanceId")); + verify(mockedQuery).subCaseInstanceId(stringQueryParameters.get("subCaseInstanceId")); + verify(mockedQuery).caseInstanceId(stringQueryParameters.get("caseInstanceId")); + verify(mockedQuery).incidentType(stringQueryParameters.get("incidentType")); + verify(mockedQuery).rootProcessInstanceId(stringQueryParameters.get("rootProcessInstanceId")); + + verify(mockedQuery).list(); + } + + @Test + public void testHistoricBeforeAndAfterStartTimeQuery() { + given() + .queryParam("startedBefore", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE) + .queryParam("startedAfter", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStartParameterQueryInvocations(); + } + + @Test + public void testHistoricBeforeAndAfterStartTimeQueryAsPost() { + Map parameters = getCompleteStartDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStartParameterQueryInvocations(); + } + + @Test + public void testHistoricBeforeAndAfterStartTimeAsStringQueryAsPost() { + Map parameters = getCompleteStartDateAsStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStringStartParameterQueryInvocations(); + } + + private Map getCompleteStartDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("startedAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER)); + parameters.put("startedBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE)); + + return parameters; + } + + private Map getCompleteStartDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("startedAfter", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER); + parameters.put("startedBefore", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE); + + return parameters; + } + + private void verifyStartParameterQueryInvocations() { + Map startDateParameters = getCompleteStartDateQueryParameters(); + + verify(mockedQuery).startedBefore(startDateParameters.get("startedBefore")); + verify(mockedQuery).startedAfter(startDateParameters.get("startedAfter")); + + verify(mockedQuery).list(); + } + + private void verifyStringStartParameterQueryInvocations() { + Map startDateParameters = getCompleteStartDateAsStringQueryParameters(); + + verify(mockedQuery).startedBefore(DateTimeUtil.parseDate(startDateParameters.get("startedBefore"))); + verify(mockedQuery).startedAfter(DateTimeUtil.parseDate(startDateParameters.get("startedAfter"))); + + verify(mockedQuery).list(); + } + + @Test + public void testHistoricAfterAndBeforeFinishTimeQuery() { + given() + .queryParam("finishedAfter", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_AFTER) + .queryParam("finishedBefore", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_BEFORE) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyFinishedParameterQueryInvocations(); + } + + @Test + public void testHistoricAfterAndBeforeFinishTimeQueryAsPost() { + Map parameters = getCompleteFinishedDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyFinishedParameterQueryInvocations(); + } + + @Test + public void testHistoricAfterAndBeforeFinishTimeAsStringQueryAsPost() { + Map parameters = getCompleteFinishedDateAsStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStringFinishedParameterQueryInvocations(); + } + + private Map getCompleteFinishedDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("finishedAfter", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_AFTER)); + parameters.put("finishedBefore", DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_BEFORE)); + + return parameters; + } + + private Map getCompleteFinishedDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("finishedAfter", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_AFTER); + parameters.put("finishedBefore", MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_FINISHED_BEFORE); + + return parameters; + } + + private void verifyFinishedParameterQueryInvocations() { + Map finishedDateParameters = getCompleteFinishedDateQueryParameters(); + + verify(mockedQuery).finishedAfter(finishedDateParameters.get("finishedAfter")); + verify(mockedQuery).finishedBefore(finishedDateParameters.get("finishedBefore")); + + verify(mockedQuery).list(); + } + + private void verifyStringFinishedParameterQueryInvocations() { + Map finishedDateParameters = getCompleteFinishedDateAsStringQueryParameters(); + + verify(mockedQuery).finishedAfter(DateTimeUtil.parseDate(finishedDateParameters.get("finishedAfter"))); + verify(mockedQuery).finishedBefore(DateTimeUtil.parseDate(finishedDateParameters.get("finishedBefore"))); + + verify(mockedQuery).list(); + } + + @Test + public void testProcessQueryFinished() { + given() + .queryParam("finished", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).finished(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testProcessQueryFinishedAsPost() { + Map body = new HashMap(); + body.put("finished", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).finished(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testProcessQueryUnfinished() { + List mockedHistoricProcessInstances = MockProvider.createMockRunningHistoricProcessInstances(); + HistoricProcessInstanceQuery mockedhistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(mockedhistoricProcessInstanceQuery.list()).thenReturn(mockedHistoricProcessInstances); + when(processEngine.getHistoryService().createHistoricProcessInstanceQuery()).thenReturn(mockedhistoricProcessInstanceQuery); + + Response response = given() + .queryParam("unfinished", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedhistoricProcessInstanceQuery); + inOrder.verify(mockedhistoricProcessInstanceQuery).unfinished(); + inOrder.verify(mockedhistoricProcessInstanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one process instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned process instance should not be null.", instances.get(0)); + + String returnedProcessInstanceId = from(content).getString("[0].id"); + String returnedEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(null, returnedEndTime); + } + + @Test + public void testProcessQueryUnfinishedAsPost() { + List mockedHistoricProcessInstances = MockProvider.createMockRunningHistoricProcessInstances(); + HistoricProcessInstanceQuery mockedhistoricProcessInstanceQuery = mock(HistoricProcessInstanceQuery.class); + when(mockedhistoricProcessInstanceQuery.list()).thenReturn(mockedHistoricProcessInstances); + when(processEngine.getHistoryService().createHistoricProcessInstanceQuery()).thenReturn(mockedhistoricProcessInstanceQuery); + + Map body = new HashMap(); + body.put("unfinished", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedhistoricProcessInstanceQuery); + inOrder.verify(mockedhistoricProcessInstanceQuery).unfinished(); + inOrder.verify(mockedhistoricProcessInstanceQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one process instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned process instance should not be null.", instances.get(0)); + + String returnedProcessInstanceId = from(content).getString("[0].id"); + String returnedEndTime = from(content).getString("[0].endTime"); + + Assert.assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, returnedProcessInstanceId); + Assert.assertEquals(null, returnedEndTime); + } + + @Test + public void testQueryWithJobsRetrying() { + given() + .queryParam("withJobsRetrying", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).withJobsRetrying(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryWithJobsRetryingAsPost() { + Map body = new HashMap(); + body.put("withJobsRetrying", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).withJobsRetrying(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryWithIncidents() { + given() + .queryParam("withIncidents", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).withIncidents(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryWithIncidentsAsPost() { + Map body = new HashMap(); + body.put("withIncidents", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).withIncidents(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryWithIncidentStatusOpen() { + given() + .queryParam("incidentStatus", "open") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentStatus("open"); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryWithIncidentStatusOpenAsPost() { + Map body = new HashMap(); + body.put("incidentStatus", "open"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentStatus("open"); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryCountIncidentStatusOpenForPost() { + Map body = new HashMap(); + body.put("incidentStatus", "open"); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_PROCESS_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + verify(mockedQuery).incidentStatus("open"); + } + + @Test + public void testQueryWithIncidentStatusResolved() { + given() + .queryParam("incidentStatus", "resolved") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentStatus("resolved"); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryWithIncidentStatusResolvedAsPost() { + Map body = new HashMap(); + body.put("incidentStatus", "resolved"); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentStatus("resolved"); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryCountIncidentStatusResolvedForPost() { + Map body = new HashMap(); + body.put("incidentStatus", "resolved"); + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_PROCESS_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + verify(mockedQuery).incidentStatus("resolved"); + } + + @Test + public void testQueryIncidentType() { + given() + .queryParam("incidentType", MockProvider.EXAMPLE_INCIDENT_TYPE) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentType(MockProvider.EXAMPLE_INCIDENT_TYPE); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryIncidentTypeAsPost() { + Map body = new HashMap(); + body.put("incidentType", MockProvider.EXAMPLE_INCIDENT_TYPE); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentType(MockProvider.EXAMPLE_INCIDENT_TYPE); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryIncidentMessage() { + given() + .queryParam("incidentMessage", MockProvider.EXAMPLE_INCIDENT_MESSAGE) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentMessage(MockProvider.EXAMPLE_INCIDENT_MESSAGE); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryIncidentMessageAsPost() { + Map body = new HashMap(); + body.put("incidentMessage", MockProvider.EXAMPLE_INCIDENT_MESSAGE); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentMessage(MockProvider.EXAMPLE_INCIDENT_MESSAGE); + inOrder.verify(mockedQuery).list(); + } + @Test + public void testQueryIncidentMessageLike() { + given() + .queryParam("incidentMessageLike", MockProvider.EXAMPLE_INCIDENT_MESSAGE_LIKE) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentMessageLike(MockProvider.EXAMPLE_INCIDENT_MESSAGE_LIKE); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryIncidentMessageLikeAsPost() { + Map body = new HashMap(); + body.put("incidentMessageLike", MockProvider.EXAMPLE_INCIDENT_MESSAGE_LIKE); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(body) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).incidentMessageLike(MockProvider.EXAMPLE_INCIDENT_MESSAGE_LIKE); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessInstanceIds() { + given() + .queryParam("processInstanceIds", "firstProcessInstanceId,secondProcessInstanceId") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyProcessInstanceIdSetInvocation(); + } + + @Test + public void testQueryByProcessInstanceIdsAsPost() { + Map> parameters = getCompleteProcessInstanceIdSetQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyProcessInstanceIdSetInvocation(); + } + + private Map> getCompleteProcessInstanceIdSetQueryParameters() { + Map> parameters = new HashMap>(); + + Set processInstanceIds = new HashSet(); + processInstanceIds.add("firstProcessInstanceId"); + processInstanceIds.add("secondProcessInstanceId"); + + parameters.put("processInstanceIds", processInstanceIds); + + return parameters; + } + + private void verifyProcessInstanceIdSetInvocation() { + Map> parameters = getCompleteProcessInstanceIdSetQueryParameters(); + + verify(mockedQuery).processInstanceIds(parameters.get("processInstanceIds")); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessInstanceIdNotIn() { + given() + .queryParam("processInstanceIdNotIn", "firstProcessInstanceId,secondProcessInstanceId") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceIdNotIn("firstProcessInstanceId", "secondProcessInstanceId"); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessInstanceIdNotInAsPost() { + Map> parameters = new HashMap>(); + + Set processInstanceIds = new HashSet(); + processInstanceIds.add("firstProcessInstanceId"); + processInstanceIds.add("secondProcessInstanceId"); + + parameters.put("processInstanceIdNotIn", processInstanceIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceIdNotIn("firstProcessInstanceId", "secondProcessInstanceId"); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessDefinitionKeyNotIn() { + given() + .queryParam("processDefinitionKeyNotIn", "firstProcessInstanceKey,secondProcessInstanceKey") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyProcessDefinitionKeyNotInListInvocation(); + } + + @Test + public void testQueryByProcessDefinitionKeyNotInAsPost() { + Map> parameters = getCompleteProcessDefinitionKeyNotInListQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyProcessDefinitionKeyNotInListInvocation(); + } + + private Map> getCompleteProcessDefinitionKeyNotInListQueryParameters() { + Map> parameters = new HashMap>(); + + List processInstanceIds = new ArrayList(); + processInstanceIds.add("firstProcessInstanceKey"); + processInstanceIds.add("secondProcessInstanceKey"); + + parameters.put("processDefinitionKeyNotIn", processInstanceIds); + + return parameters; + } + + private void verifyProcessDefinitionKeyNotInListInvocation() { + Map> parameters = getCompleteProcessDefinitionKeyNotInListQueryParameters(); + + verify(mockedQuery).processDefinitionKeyNotIn(parameters.get("processDefinitionKeyNotIn")); + verify(mockedQuery).list(); + } + + @Test + public void shouldQueryByBusinessKeyIn() { + given() + .queryParam("processInstanceBusinessKeyIn", "business-key-one,business-key-two") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyBusinessKeyInListInvocation(); + } + + @Test + public void shouldQueryByBusinessKeyInAsPost() { + Map> parameters = getCompleteBusinessKeyInListQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyBusinessKeyInListInvocation(); + } + + protected Map> getCompleteBusinessKeyInListQueryParameters() { + Map> parameters = new HashMap<>(); + + List processInstanceBusinessKeys = new ArrayList<>(); + processInstanceBusinessKeys.add("business-key-one"); + processInstanceBusinessKeys.add("business-key-two"); + + parameters.put("processInstanceBusinessKeyIn", processInstanceBusinessKeys); + + return parameters; + } + + protected void verifyBusinessKeyInListInvocation() { + Map> parameters = getCompleteBusinessKeyInListQueryParameters(); + List value = parameters.get("processInstanceBusinessKeyIn"); + + verify(mockedQuery).processInstanceBusinessKeyIn(value.toArray(new String[0])); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByProcessDefinitionKeyIn() { + given() + .queryParam("processDefinitionKeyIn", "firstProcessDefinitionKey,secondProcessDefinitionKey") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyProcessDefinitionKeyInListInvocation(); + } + + @Test + public void testQueryByProcessDefinitionKeyInAsPost() { + Map> parameters = getCompleteProcessDefinitionKeyInListQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyProcessDefinitionKeyInListInvocation(); + } + + private Map> getCompleteProcessDefinitionKeyInListQueryParameters() { + Map> parameters = new HashMap>(); + + List processInstanceIds = new ArrayList(); + processInstanceIds.add("firstProcessDefinitionKey"); + processInstanceIds.add("secondProcessDefinitionKey"); + + parameters.put("processDefinitionKeyIn", processInstanceIds); + + return parameters; + } + + private void verifyProcessDefinitionKeyInListInvocation() { + Map> parameters = getCompleteProcessDefinitionKeyInListQueryParameters(); + List value = parameters.get("processDefinitionKeyIn"); + + verify(mockedQuery).processDefinitionKeyIn(value.toArray(new String[value.size()])); + verify(mockedQuery).list(); + } + + @Test + public void testVariableValueEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gt_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueGreaterThan(variableName, variableValue); + } + + @Test + public void testVariableValueGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_gteq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueGreaterThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lt_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLessThan(variableName, variableValue); + } + + @Test + public void testVariableValueLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_lteq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLessThanOrEqual(variableName, variableValue); + } + + @Test + public void testVariableValueLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + } + + @Test + public void testVariableValueNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + } + + @Test + public void testVariableValuesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + @Test + public void testVariableValuesLikeIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_like_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableValuesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueLike(variableName, variableValue); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + } + + + @Test + public void testVariableNamesEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_eq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_neq_" + variableValue; + given().queryParam("variables", queryValue).queryParam("variableNamesIgnoreCase", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + verify(mockedQuery).variableValueNotEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + } + + @Test + public void testVariableValueEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueGreaterThan("varName", "varValue"); + } + + @Test + public void testVariableValueGreaterThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "gteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueGreaterThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lt"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueLessThan("varName", "varValue"); + } + + @Test + public void testVariableValueLessThanEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "lteq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueLessThanOrEqual("varName", "varValue"); + } + + @Test + public void testVariableValueLikeAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + @Test + public void testVariableValueNotEqualsAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testVariableValuesLikeIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "like"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableValueLike("varName", "varValue"); + } + + + @Test + public void testVariableNamesEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "eq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueEquals("varName", "varValue"); + } + + @Test + public void testVariableNamesNotEqualsIgnoreCaseAsPost() { + Map variableJson = new HashMap(); + variableJson.put("name", "varName"); + variableJson.put("value", "varValue"); + variableJson.put("operator", "neq"); + + List> variables = new ArrayList>(); + variables.add(variableJson); + + Map json = new HashMap(); + json.put("variables", variables); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableValueNotEquals("varName", "varValue"); + } + + @Test + public void testMultipleVariableParameters() { + String variableName1 = "varName"; + String variableValue1 = "varValue"; + String variableParameter1 = variableName1 + "_eq_" + variableValue1; + + String variableName2 = "anotherVarName"; + String variableValue2 = "anotherVarValue"; + String variableParameter2 = variableName2 + "_neq_" + variableValue2; + + String queryValue = variableParameter1 + "," + variableParameter2; + + given() + .queryParam("variables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueEquals(variableName1, variableValue1); + verify(mockedQuery).variableValueNotEquals(variableName2, variableValue2); + } + + @Test + public void testMultipleVariableParametersAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + String anotherVariableName = "anotherVarName"; + Integer anotherVariableValue = 30; + + Map variableJson = new HashMap(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + Map anotherVariableJson = new HashMap(); + anotherVariableJson.put("name", anotherVariableName); + anotherVariableJson.put("operator", "neq"); + anotherVariableJson.put("value", anotherVariableValue); + + List> variables = new ArrayList>(); + variables.add(variableJson); + variables.add(anotherVariableJson); + + Map json = new HashMap(); + json.put("variables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).variableValueNotEquals(eq(anotherVariableName), argThat(EqualsPrimitiveValue.numberValue(anotherVariableValue))); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricProcessInstanceQuery(createMockHistoricProcessInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockHistoricProcessInstanceQuery(createMockHistoricProcessInstancesTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testWithoutTenantIdParameter() { + mockedQuery = setUpMockHistoricProcessInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricProcessInstance(null))); + + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + @Test + public void testWithoutTenantIdPostParameter() { + mockedQuery = setUpMockHistoricProcessInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricProcessInstance(null))); + + Map queryParameters = new HashMap(); + queryParameters.put("withoutTenantId", true); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId1).isEqualTo(null); + } + + private List createMockHistoricProcessInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricProcessInstance(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricProcessInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + + @Test + public void testExecutedActivityBeforeAndAfterTimeQuery() { + given() + .queryParam(QUERY_PARAM_EXECUTED_ACTIVITY_BEFORE, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE) + .queryParam(QUERY_PARAM_EXECUTED_ACTIVITY_AFTER, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyExecutedActivityParameterQueryInvocations(); + } + + @Test + public void testExecutedActivityBeforeAndAfterTimeQueryAsPost() { + Map parameters = getCompleteExecutedActivityDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyExecutedActivityParameterQueryInvocations(); + } + + @Test + public void testExecutedActivityBeforeAndAfterTimeAsStringQueryAsPost() { + Map parameters = getCompleteExecutedActivityDateAsStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStringExecutedActivityParameterQueryInvocations(); + } + + + private void verifyExecutedActivityParameterQueryInvocations() { + Map startDateParameters = getCompleteExecutedActivityDateQueryParameters(); + + verify(mockedQuery).executedActivityBefore(startDateParameters.get(QUERY_PARAM_EXECUTED_ACTIVITY_BEFORE)); + verify(mockedQuery).executedActivityAfter(startDateParameters.get(QUERY_PARAM_EXECUTED_ACTIVITY_AFTER)); + + verify(mockedQuery).list(); + } + + private void verifyStringExecutedActivityParameterQueryInvocations() { + Map startDateParameters = getCompleteExecutedActivityDateAsStringQueryParameters(); + + verify(mockedQuery).executedActivityBefore(DateTimeUtil.parseDate(startDateParameters.get(QUERY_PARAM_EXECUTED_ACTIVITY_BEFORE))); + verify(mockedQuery).executedActivityAfter(DateTimeUtil.parseDate(startDateParameters.get(QUERY_PARAM_EXECUTED_ACTIVITY_AFTER))); + + verify(mockedQuery).list(); + } + + private Map getCompleteExecutedActivityDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put(QUERY_PARAM_EXECUTED_ACTIVITY_BEFORE, DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE)); + parameters.put(QUERY_PARAM_EXECUTED_ACTIVITY_AFTER, DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER)); + + return parameters; + } + + private Map getCompleteExecutedActivityDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put(QUERY_PARAM_EXECUTED_ACTIVITY_AFTER, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER); + parameters.put(QUERY_PARAM_EXECUTED_ACTIVITY_BEFORE, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE); + + return parameters; + } + + // =================================================================================================================== + + @Test + public void testExecutedJobBeforeAndAfterTimeQuery() { + given() + .queryParam(QUERY_PARAM_EXECUTED_JOB_BEFORE, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE) + .queryParam(QUERY_PARAM_EXECUTED_JOB_AFTER, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyExecutedJobParameterQueryInvocations(); + } + + @Test + public void testExecutedJobBeforeAndAfterTimeQueryAsPost() { + Map parameters = getCompleteExecutedJobDateQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyExecutedJobParameterQueryInvocations(); + } + + @Test + public void testExecutedJobBeforeAndAfterTimeAsStringQueryAsPost() { + Map parameters = getCompleteExecutedJobDateAsStringQueryParameters(); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verifyStringExecutedJobParameterQueryInvocations(); + } + + @Test + public void testExecutedActivityIdIn() { + + given() + .queryParam(QUERY_PARAM_EXECUTED_ACTIVITY_IDS, "1,2") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).executedActivityIdIn("1", "2"); + } + + @Test + public void testExecutedActivityIdInAsPost() { + Map> parameters = new HashMap>(); + parameters.put(QUERY_PARAM_EXECUTED_ACTIVITY_IDS, Arrays.asList("1", "2")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).executedActivityIdIn("1", "2"); + } + + @Test + public void testActiveActivityIdIn() { + + given() + .queryParam(QUERY_PARAM_ACTIVE_ACTIVITY_IDS, "1,2") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activeActivityIdIn("1", "2"); + } + + @Test + public void testActiveActivityIdInAsPost() { + Map> parameters = new HashMap>(); + parameters.put(QUERY_PARAM_ACTIVE_ACTIVITY_IDS, Arrays.asList("1", "2")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activeActivityIdIn("1", "2"); + } + + @Test + public void testQueryWithRootIncidents() { + given() + .queryParam("withRootIncidents", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).withRootIncidents(); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testQueryWithRootIncidentsAsPost() { + Map parameters = new HashMap(); + parameters.put("withRootIncidents", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withRootIncidents(); + } + + private void verifyExecutedJobParameterQueryInvocations() { + Map startDateParameters = getCompleteExecutedJobDateQueryParameters(); + + verify(mockedQuery).executedJobBefore(startDateParameters.get(QUERY_PARAM_EXECUTED_JOB_BEFORE)); + verify(mockedQuery).executedJobAfter(startDateParameters.get(QUERY_PARAM_EXECUTED_JOB_AFTER)); + + verify(mockedQuery).list(); + } + + private void verifyStringExecutedJobParameterQueryInvocations() { + Map startDateParameters = getCompleteExecutedJobDateAsStringQueryParameters(); + + verify(mockedQuery).executedJobBefore(DateTimeUtil.parseDate(startDateParameters.get(QUERY_PARAM_EXECUTED_JOB_BEFORE))); + verify(mockedQuery).executedJobAfter(DateTimeUtil.parseDate(startDateParameters.get(QUERY_PARAM_EXECUTED_JOB_AFTER))); + + verify(mockedQuery).list(); + } + + private Map getCompleteExecutedJobDateQueryParameters() { + Map parameters = new HashMap(); + + parameters.put(QUERY_PARAM_EXECUTED_JOB_BEFORE, DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE)); + parameters.put(QUERY_PARAM_EXECUTED_JOB_AFTER, DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER)); + + return parameters; + } + + private Map getCompleteExecutedJobDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put(QUERY_PARAM_EXECUTED_JOB_AFTER, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER); + parameters.put(QUERY_PARAM_EXECUTED_JOB_BEFORE, MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE); + + return parameters; + } + + @Test + public void testQueryByActive() { + given() + .queryParam("active", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).active(); + } + + + @Test + public void testQueryByCompleted() { + given() + .queryParam("completed", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).completed(); + } + + @Test + public void testQueryBySuspended() { + given() + .queryParam("suspended", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).suspended(); + } + + @Test + public void testQueryByExternallyTerminated() { + given() + .queryParam("externallyTerminated", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).externallyTerminated(); + } + + @Test + public void testQueryByInternallyTerminated() { + given() + .queryParam("internallyTerminated", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).internallyTerminated(); + } + + @Test + public void testQueryByTwoStates() { + String message = "expected exception"; + doThrow(new BadUserRequestException(message)).when(mockedQuery).completed(); + + given() + .queryParam("active", true) + .queryParam("completed", true) + .then() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).active(); + } + + @Test + public void testQueryByActiveAsPost() { + Map parameters = new HashMap(); + parameters.put("active", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).active(); + } + + @Test + public void testQueryByCompletedAsPost() { + Map parameters = new HashMap(); + parameters.put("completed", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).completed(); + } + + @Test + public void testQueryBySuspendedAsPost() { + Map parameters = new HashMap(); + parameters.put("suspended", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).suspended(); + } + + @Test + public void testQueryByExternallyTerminatedAsPost() { + Map parameters = new HashMap(); + parameters.put("externallyTerminated", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).externallyTerminated(); + } + + + @Test + public void testQueryByInternallyTerminatedAsPost() { + Map parameters = new HashMap(); + parameters.put("internallyTerminated", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).internallyTerminated(); + } + + @Test + public void testQueryByTwoStatesAsPost() { + String message = "expected exception"; + doThrow(new BadUserRequestException(message)).when(mockedQuery).completed(); + + Map parameters = new HashMap(); + parameters.put("active", true); + parameters.put("completed", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(BadUserRequestException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).active(); + } + + @Test + public void testQueryByRootProcessInstances() { + given() + .queryParam("rootProcessInstances", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).rootProcessInstances(); + } + + @Test + public void testQueryByRootProcessInstancesAsPost() { + Map parameters = new HashMap(); + parameters.put("rootProcessInstances", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).rootProcessInstances(); + } + @Test + public void testQueryByIncidentIdIn() { + given() + .queryParam(QUERY_PARAM_INCIDENT_IDS, "1,2") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).incidentIdIn("1", "2"); + } + + @Test + public void testQueryByIncidentIdInAsPost() { + Map> parameters = new HashMap>(); + parameters.put(QUERY_PARAM_INCIDENT_IDS, Arrays.asList("1", "2")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).incidentIdIn("1", "2"); + } + + @Test + public void testQueryByActivityIdIn() { + given() + .queryParam(QUERY_PARAM_ACTIVE_OR_FAILING_ACTIVITY_IDS, "1,2") + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityIdIn("1", "2"); + } + + @Test + public void testQueryByActivityIdInAsPost() { + Map> parameters = new HashMap>(); + parameters.put(QUERY_PARAM_ACTIVE_OR_FAILING_ACTIVITY_IDS, Arrays.asList("1", "2")); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(parameters) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_PROCESS_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityIdIn("1", "2"); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceReportTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceReportTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8aeaf21d38774b17e952b76bbd5a58bf5726ce1c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricProcessInstanceRestServiceReportTest.java @@ -0,0 +1,574 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.query.PeriodUnit.MONTH; +import static org.camunda.bpm.engine.query.PeriodUnit.QUARTER; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_PERIOD; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockHistoricProcessInstanceDurationReportByMonth; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockHistoricProcessInstanceDurationReportByQuarter; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.history.DurationReportResult; +import org.camunda.bpm.engine.history.HistoricProcessInstanceReport; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.converter.ReportResultToCsvConverter; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import javax.ws.rs.core.Response.Status; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Roman Smirnov + * + */ +public class HistoricProcessInstanceRestServiceReportTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_PROCESS_INSTANCE_REPORT_URL = TEST_RESOURCE_ROOT_PATH + "/history/process-instance/report"; + + protected HistoricProcessInstanceReport mockedReportQuery; + + @Before + public void setUpRuntimeData() { + mockedReportQuery = setUpMockHistoricProcessInstanceReportQuery(); + } + + private HistoricProcessInstanceReport setUpMockHistoricProcessInstanceReportQuery() { + HistoricProcessInstanceReport mockedReportQuery = mock(HistoricProcessInstanceReport.class); + + when(mockedReportQuery.processDefinitionIdIn(anyString())).thenReturn(mockedReportQuery); + when(mockedReportQuery.processDefinitionKeyIn(anyString())).thenReturn(mockedReportQuery); + when(mockedReportQuery.startedAfter(any(Date.class))).thenReturn(mockedReportQuery); + when(mockedReportQuery.startedBefore(any(Date.class))).thenReturn(mockedReportQuery); + + List durationReportByMonth = createMockHistoricProcessInstanceDurationReportByMonth(); + when(mockedReportQuery.duration(MONTH)).thenReturn(durationReportByMonth); + + List durationReportByQuarter = createMockHistoricProcessInstanceDurationReportByQuarter(); + when(mockedReportQuery.duration(QUARTER)).thenReturn(durationReportByQuarter); + + when(mockedReportQuery.duration(null)).thenThrow(new NotValidException("periodUnit is null")); + + when(processEngine.getHistoryService().createHistoricProcessInstanceReport()).thenReturn(mockedReportQuery); + + return mockedReportQuery; + } + + @Test + public void testEmptyReportByMonth() { + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "month") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verify(mockedReportQuery).duration(MONTH); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testEmptyReportByQuarter() { + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "quarter") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verify(mockedReportQuery).duration(QUARTER); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testInvalidReportType() { + given() + .queryParam("reportType", "abc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot set query parameter 'reportType' to value 'abc'")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testInvalidPeriodUnit() { + given() + .queryParam("periodUnit", "abc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot set query parameter 'periodUnit' to value 'abc'")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testMissingReportType() { + given() + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Unknown report type null")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testMissingPeriodUnit() { + given() + .queryParam("reportType", "duration") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("periodUnit is null")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testMissingAuthorization() { + String message = "not authorized"; + when(mockedReportQuery.duration(MONTH)).thenThrow(new AuthorizationException(message)); + + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "month") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testDurationReportByMonth() { + Response response = given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + String content = response.asString(); + List reports = from(content).getList(""); + Assert.assertEquals("There should be one report returned.", 1, reports.size()); + Assert.assertNotNull("The returned report should not be null.", reports.get(0)); + + long returnedAvg = from(content).getLong("[0].average"); + long returnedMax = from(content).getLong("[0].maximum"); + long returnedMin = from(content).getLong("[0].minimum"); + int returnedPeriod = from(content).getInt("[0].period"); + String returnedPeriodUnit = from(content).getString("[0].periodUnit"); + + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG, returnedAvg); + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX, returnedMax); + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN, returnedMin); + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_PERIOD, returnedPeriod); + Assert.assertEquals(MONTH.toString(), returnedPeriodUnit); + } + + @Test + public void testDurationReportByQuarter() { + Response response = given() + .queryParam("periodUnit", "quarter") + .queryParam("reportType", "duration") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + String content = response.asString(); + List reports = from(content).getList(""); + Assert.assertEquals("There should be one report returned.", 1, reports.size()); + Assert.assertNotNull("The returned report should not be null.", reports.get(0)); + + long returnedAvg = from(content).getLong("[0].average"); + long returnedMax = from(content).getLong("[0].maximum"); + long returnedMin = from(content).getLong("[0].minimum"); + int returnedPeriod = from(content).getInt("[0].period"); + String returnedPeriodUnit = from(content).getString("[0].periodUnit"); + + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG, returnedAvg); + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX, returnedMax); + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN, returnedMin); + Assert.assertEquals(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_PERIOD, returnedPeriod); + Assert.assertEquals(QUARTER.toString(), returnedPeriodUnit); + } + + @Test + public void testListParameters() { + String aProcDefId = "anProcDefId"; + String anotherProcDefId = "anotherProcDefId"; + + String aProcDefKey = "anProcDefKey"; + String anotherProcDefKey = "anotherProcDefKey"; + + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .queryParam("processDefinitionIdIn", aProcDefId + "," + anotherProcDefId) + .queryParam("processDefinitionKeyIn", aProcDefKey + "," + anotherProcDefKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verify(mockedReportQuery).processDefinitionIdIn(aProcDefId, anotherProcDefId); + verify(mockedReportQuery).processDefinitionKeyIn(aProcDefKey, anotherProcDefKey); + verify(mockedReportQuery).duration(MONTH); + } + + @Test + public void testHistoricBeforeAndAfterStartTimeQuery() { + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .queryParam("startedBefore", EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE) + .queryParam("startedAfter", EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verifyStringStartParameterQueryInvocations(); + } + + @Test + public void testEmptyCsvReportByMonth() { + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "month") + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verify(mockedReportQuery).duration(MONTH); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testEmptyCsvReportByQuarter() { + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "quarter") + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verify(mockedReportQuery).duration(QUARTER); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testCsvInvalidReportType() { + given() + .queryParam("reportType", "abc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot set query parameter 'reportType' to value 'abc'")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testCsvInvalidPeriodUnit() { + given() + .queryParam("periodUnit", "abc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot set query parameter 'periodUnit' to value 'abc'")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testCsvMissingReportType() { + given() + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Unknown report type null")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testCsvMissingPeriodUnit() { + given() + .queryParam("reportType", "duration") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("periodUnit is null")) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testCsvMissingAuthorization() { + String message = "not authorized"; + when(mockedReportQuery.duration(MONTH)).thenThrow(new AuthorizationException(message)); + + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "month") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + } + + @Test + public void testCsvDurationReportByMonth() { + Response response = given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "month") + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when().get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(ReportResultToCsvConverter.DURATION_HEADER)); + assertTrue(responseContent.contains(MONTH.toString())); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX))); + } + + @Test + public void testCsvDurationReportByQuarter() { + Response response = given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "quarter") + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when().get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(ReportResultToCsvConverter.DURATION_HEADER)); + assertTrue(responseContent.contains(QUARTER.toString())); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX))); + } + + @Test + public void testApplicationCsvDurationReportByMonth() { + Response response = given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "month") + .accept("application/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("application/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when().get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(ReportResultToCsvConverter.DURATION_HEADER)); + assertTrue(responseContent.contains(MONTH.toString())); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX))); + } + + @Test + public void testApplicationCsvDurationReportByQuarter() { + Response response = given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "quarter") + .accept("application/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("application/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when().get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + String responseContent = response.asString(); + assertTrue(responseContent.contains(ReportResultToCsvConverter.DURATION_HEADER)); + assertTrue(responseContent.contains(QUARTER.toString())); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_AVG))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MIN))); + assertTrue(responseContent.contains(String.valueOf(EXAMPLE_HISTORIC_PROC_INST_DURATION_REPORT_MAX))); + } + + @Test + public void testCsvListParameters() { + String aProcDefId = "anProcDefId"; + String anotherProcDefId = "anotherProcDefId"; + + String aProcDefKey = "anProcDefKey"; + String anotherProcDefKey = "anotherProcDefKey"; + + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .queryParam("processDefinitionIdIn", aProcDefId + "," + anotherProcDefId) + .queryParam("processDefinitionKeyIn", aProcDefKey + "," + anotherProcDefKey) + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verify(mockedReportQuery).processDefinitionIdIn(aProcDefId, anotherProcDefId); + verify(mockedReportQuery).processDefinitionKeyIn(aProcDefKey, anotherProcDefKey); + verify(mockedReportQuery).duration(MONTH); + } + + @Test + public void testCsvHistoricBeforeAndAfterStartTimeQuery() { + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .queryParam("startedBefore", EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE) + .queryParam("startedAfter", EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER) + .accept("text/csv") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType("text/csv") + .header("Content-Disposition", "attachment; " + + "filename=\"process-instance-report.csv\"; " + + "filename*=UTF-8''process-instance-report.csv") + .when() + .get(HISTORIC_PROCESS_INSTANCE_REPORT_URL); + + verifyStringStartParameterQueryInvocations(); + } + + private Map getCompleteStartDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("startedAfter", EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_AFTER); + parameters.put("startedBefore", EXAMPLE_HISTORIC_PROCESS_INSTANCE_STARTED_BEFORE); + + return parameters; + } + + private void verifyStringStartParameterQueryInvocations() { + Map startDateParameters = getCompleteStartDateAsStringQueryParameters(); + + verify(mockedReportQuery).startedBefore(DateTimeUtil.parseDate(startDateParameters.get("startedBefore"))); + verify(mockedReportQuery).startedAfter(DateTimeUtil.parseDate(startDateParameters.get("startedAfter"))); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..3b612178df6fdf6526b500251f1f9c49d8afd559 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricTaskInstanceRestServiceQueryTest.java @@ -0,0 +1,2607 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.rest.util.QueryParamUtils.arrayAsCommaSeperatedList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.history.HistoricTaskInstance; +import org.camunda.bpm.engine.history.HistoricTaskInstanceQuery; +import org.camunda.bpm.engine.impl.HistoricTaskInstanceQueryImpl; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +public class HistoricTaskInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_TASK_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/task"; + protected static final String HISTORIC_TASK_INSTANCE_COUNT_RESOURCE_URL = HISTORIC_TASK_INSTANCE_RESOURCE_URL + "/count"; + + protected HistoricTaskInstanceQuery mockedQuery; + + @Before + public void setUpRuntimeData() { + mockedQuery = setUpMockHistoricTaskInstanceQuery(MockProvider.createMockHistoricTaskInstances()); + } + + private HistoricTaskInstanceQuery setUpMockHistoricTaskInstanceQuery(List mockedHistoricTaskInstances) { + mockedQuery = mock(HistoricTaskInstanceQuery.class); + + when(mockedQuery.list()).thenReturn(mockedHistoricTaskInstances); + when(mockedQuery.count()).thenReturn((long) mockedHistoricTaskInstances.size()); + + when(processEngine.getHistoryService().createHistoricTaskInstanceQuery()).thenReturn(mockedQuery); + + return mockedQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processInstanceId", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("processInstanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy) + .queryParam("sortOrder", sortOrder) + .then() + .expect() + .statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("activityInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("processInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("executionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricTaskInstanceDuration(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("duration", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricTaskInstanceDuration(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricTaskInstanceEndTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("endTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricTaskInstanceEndTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("startTime", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceStartTime(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("startTime", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByHistoricActivityInstanceStartTime(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskName", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskName(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskName", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskDescription", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskDescription(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskDescription", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskDescription(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("assignee", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskAssignee(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("assignee", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskAssignee(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("owner", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskOwner(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("owner", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskOwner(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("dueDate", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskDueDate(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("dueDate", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskDueDate(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("followUpDate", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskFollowUpDate(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("followUpDate", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskFollowUpDate(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deleteReason", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByDeleteReason(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("deleteReason", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByDeleteReason(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskDefinitionKey", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskDefinitionKey(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("taskDefinitionKey", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskDefinitionKey(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("priority", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskPriority(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("priority", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTaskPriority(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseDefinitionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseDefinitionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseInstanceId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseInstanceId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseInstanceId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseExecutionId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseExecutionId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("caseExecutionId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByCaseExecutionId(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap<>(); + json.put("sorting", OrderingBuilder.create() + .orderBy("owner").desc() + .orderBy("priority").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + inOrder.verify(mockedQuery).orderByTaskOwner(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByTaskPriority(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + int firstResult = 0; + int maxResults = 10; + + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_TASK_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_TASK_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testSimpleHistoricTaskInstanceQuery() { + Response response = given() + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one historic task instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned historic task instance should not be null.", instances.get(0)); + + verifyHistoricTaskInstanceEntries(content); + } + + @Test + public void testSimpleHistoricTaskInstanceQueryAsPost() { + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).list(); + + String content = response.asString(); + List instances = from(content).getList(""); + Assert.assertEquals("There should be one historic task instance returned.", 1, instances.size()); + Assert.assertNotNull("The returned historic task instance should not be null.", instances.get(0)); + + verifyHistoricTaskInstanceEntries(content); + } + + @Test + public void testQueryByTaskId() { + String taskId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ID; + + given() + .queryParam("taskId", taskId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskId(taskId); + } + + @Test + public void testQueryByTaskIdAsPost() { + String taskId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ID; + + Map params = new HashMap<>(); + params.put("taskId", taskId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskId(taskId); + } + + @Test + public void testQueryByProcessInstanceId() { + String processInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_INST_ID; + + given() + .queryParam("processInstanceId", processInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceId(processInstanceId); + } + + @Test + public void testQueryByProcessInstanceIdAsPost() { + String processInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_INST_ID; + + Map params = new HashMap<>(); + params.put("processInstanceId", processInstanceId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceId(processInstanceId); + } + + @Test + public void testQueryByRootProcessInstanceId() { + String rootProcessInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ROOT_PROC_INST_ID; + + given().queryParam("rootProcessInstanceId", rootProcessInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).rootProcessInstanceId(rootProcessInstanceId); + } + + @Test + public void testQueryByRootProcessInstanceIdAsPost() { + String rootProcessInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ROOT_PROC_INST_ID; + + Map params = new HashMap<>(); + params.put("rootProcessInstanceId", rootProcessInstanceId); + + given().contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).rootProcessInstanceId(rootProcessInstanceId); + } + + @Test + public void testQueryByProcessInstanceBusinessKey() { + String processInstanceBusinessKey = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_INST_BUSINESS_KEY; + + given() + .queryParam("processInstanceBusinessKey", processInstanceBusinessKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceBusinessKey(processInstanceBusinessKey); + } + + @Test + public void testQueryByProcessInstanceBusinessKeyAsPost() { + String processInstanceBusinessKey = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_INST_BUSINESS_KEY; + + Map params = new HashMap<>(); + params.put("processInstanceBusinessKey", processInstanceBusinessKey); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceBusinessKey(processInstanceBusinessKey); + } + + @Test + public void testQueryByProcessInstanceBusinessKeyLike() { + String processInstanceBusinessKeyLike = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_INST_BUSINESS_KEY; + + given() + .queryParam("processInstanceBusinessKeyLike", processInstanceBusinessKeyLike) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceBusinessKeyLike(processInstanceBusinessKeyLike); + } + + @Test + public void testQueryByProcessInstanceBusinessKeyLikeAsPost() { + String processInstanceBusinessKeyLike = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_INST_BUSINESS_KEY; + + Map params = new HashMap<>(); + params.put("processInstanceBusinessKeyLike", processInstanceBusinessKeyLike); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceBusinessKeyLike(processInstanceBusinessKeyLike); + } + + @Test + public void testQueryByProcessInstanceBusinessKeyIn() { + given() + .queryParam("processInstanceBusinessKeyIn", arrayAsCommaSeperatedList("aBusinessKey", "anotherBusinessKey")) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceBusinessKeyIn("aBusinessKey", "anotherBusinessKey"); + } + + @Test + public void testQueryByProcessInstanceBusinessKeyInAsPost() { + String businessKey1 = "aBusinessKey"; + String businessKey2 = "anotherBusinessKey"; + List processInstanceBusinessKeyIn = new ArrayList<>(); + processInstanceBusinessKeyIn.add(businessKey1); + processInstanceBusinessKeyIn.add(businessKey2); + + Map params = new HashMap<>(); + params.put("processInstanceBusinessKeyIn", processInstanceBusinessKeyIn); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceBusinessKeyIn(businessKey1, businessKey2); + } + + @Test + public void testQueryByExecutionId() { + String executionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_EXEC_ID; + + given() + .queryParam("executionId", executionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).executionId(executionId); + } + + @Test + public void testQueryByExecutionIdAsPost() { + String executionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_EXEC_ID; + + Map params = new HashMap<>(); + params.put("executionId", executionId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).executionId(executionId); + } + + @Test + public void testQueryByActivityInstanceId() { + String activityInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ACT_INST_ID; + + given() + .queryParam("activityInstanceIdIn", activityInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityInstanceIdIn(activityInstanceId); + } + + @Test + public void testQueryByActivityInstanceIdAsPost() { + String activityInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ACT_INST_ID; + + List activityInstanceIds = new ArrayList<>(); + activityInstanceIds.add(activityInstanceId); + + Map params = new HashMap<>(); + params.put("activityInstanceIdIn", activityInstanceIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityInstanceIdIn(activityInstanceId); + } + + @Test + public void testQueryByActivityInstanceIds() { + String activityInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ACT_INST_ID; + String anotherActivityInstanceId = "anotherActivityInstanceId"; + + given() + .queryParam("activityInstanceIdIn", activityInstanceId + "," + anotherActivityInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityInstanceIdIn(activityInstanceId, anotherActivityInstanceId); + } + + @Test + public void testQueryByActivityInstanceIdsAsPost() { + String activityInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ACT_INST_ID; + String anotherActivityInstanceId = "anotherActivityInstanceId"; + + List activityInstanceIds = new ArrayList<>(); + activityInstanceIds.add(activityInstanceId); + activityInstanceIds.add(anotherActivityInstanceId); + + Map params = new HashMap<>(); + params.put("activityInstanceIdIn", activityInstanceIds); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityInstanceIdIn(activityInstanceId, anotherActivityInstanceId); + } + + @Test + public void testQueryByProcessDefinitionId() { + String processDefinitionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_ID; + + given() + .queryParam("processDefinitionId", processDefinitionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionId(processDefinitionId); + } + + @Test + public void testQueryByProcessDefinitionIdAsPost() { + String processDefinitionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_ID; + + Map params = new HashMap<>(); + params.put("processDefinitionId", processDefinitionId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionId(processDefinitionId); + } + + @Test + public void testQueryByProcessDefinitionKey() { + String processDefinitionKey = "aProcDefKey"; + + given() + .queryParam("processDefinitionKey", processDefinitionKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionKey(processDefinitionKey); + } + + @Test + public void testQueryByProcessDefinitionKeyAsPost() { + String processDefinitionKey = "aProcDefKey"; + + Map params = new HashMap<>(); + params.put("processDefinitionKey", processDefinitionKey); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionKey(processDefinitionKey); + } + + @Test + public void testQueryByProcessDefinitionName() { + String processDefinitionName = "aProcDefName"; + + given() + .queryParam("processDefinitionName", processDefinitionName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionName(processDefinitionName); + } + + @Test + public void testQueryByProcessDefinitionNameAsPost() { + String processDefinitionName = "aProcDefName"; + + Map params = new HashMap<>(); + params.put("processDefinitionName", processDefinitionName); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionName(processDefinitionName); + } + + @Test + public void testQueryByTaskName() { + String taskName = "aTaskName"; + + given() + .queryParam("taskName", taskName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskName(taskName); + } + + @Test + public void testQueryByTaskNameAsPost() { + String taskName = "aTaskName"; + + Map params = new HashMap<>(); + params.put("taskName", taskName); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskName(taskName); + } + + @Test + public void testQueryByTaskNameLike() { + String taskNameLike = "aTaskNameLike"; + + given() + .queryParam("taskNameLike", taskNameLike) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskNameLike(taskNameLike); + } + + @Test + public void testQueryByTaskNameLikeAsPost() { + String taskNameLike = "aTaskNameLike"; + + Map params = new HashMap<>(); + params.put("taskNameLike", taskNameLike); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskNameLike(taskNameLike); + } + + @Test + public void testQueryByTaskDescription() { + String taskDescription = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DESCRIPTION; + + given() + .queryParam("taskDescription", taskDescription) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDescription(taskDescription); + } + + @Test + public void testQueryByTaskDescriptionAsPost() { + String taskDescription = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DESCRIPTION; + + Map params = new HashMap<>(); + params.put("taskDescription", taskDescription); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDescription(taskDescription); + } + + @Test + public void testQueryByTaskDescriptionLike() { + String taskDescriptionLike = "aTaskDescriptionLike"; + + given() + .queryParam("taskDescriptionLike", taskDescriptionLike) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDescriptionLike(taskDescriptionLike); + } + + @Test + public void testQueryByTaskDescriptionLikeAsPost() { + String taskDescriptionLike = "aTaskDescriptionLike"; + + Map params = new HashMap<>(); + params.put("taskDescriptionLike", taskDescriptionLike); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDescriptionLike(taskDescriptionLike); + } + + @Test + public void testQueryByTaskDefinitionKey() { + String taskDefinitionKey = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DEF_KEY; + + given() + .queryParam("taskDefinitionKey", taskDefinitionKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDefinitionKey(taskDefinitionKey); + } + + @Test + public void testQueryByTaskDefinitionKeyAsPost() { + String taskDefinitionKey = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DEF_KEY; + + Map params = new HashMap<>(); + params.put("taskDefinitionKey", taskDefinitionKey); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDefinitionKey(taskDefinitionKey); + } + + @Test + public void testQueryByTaskDeleteReason() { + String taskDeleteReason = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DELETE_REASON; + + given() + .queryParam("taskDeleteReason", taskDeleteReason) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDeleteReason(taskDeleteReason); + } + + @Test + public void testQueryByTaskDeleteReasonAsPost() { + String taskDeleteReason = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DELETE_REASON; + + Map params = new HashMap<>(); + params.put("taskDeleteReason", taskDeleteReason); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDeleteReason(taskDeleteReason); + } + + @Test + public void testQueryByTaskDeleteReasonLike() { + String taskDeleteReasonLike = "aTaskDeleteReasonLike"; + + given() + .queryParam("taskDeleteReasonLike", taskDeleteReasonLike) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDeleteReasonLike(taskDeleteReasonLike); + } + + @Test + public void testQueryByTaskDeleteReasonLikeAsPost() { + String taskDeleteReasonLike = "aTaskDeleteReasonLike"; + + Map params = new HashMap<>(); + params.put("taskDeleteReasonLike", taskDeleteReasonLike); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDeleteReasonLike(taskDeleteReasonLike); + } + + @Test + public void testQueryByTaskAssignee() { + String taskAssignee = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ASSIGNEE; + + given() + .queryParam("taskAssignee", taskAssignee) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskAssignee(taskAssignee); + } + + @Test + public void testQueryByTaskAssigneeAsPost() { + String taskAssignee = MockProvider.EXAMPLE_HISTORIC_TASK_INST_ASSIGNEE; + + Map params = new HashMap<>(); + params.put("taskAssignee", taskAssignee); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskAssignee(taskAssignee); + } + + @Test + public void testQueryByTaskAssigneeLike() { + String taskAssigneeLike = "aTaskAssigneeLike"; + + given() + .queryParam("taskAssigneeLike", taskAssigneeLike) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskAssigneeLike(taskAssigneeLike); + } + + @Test + public void testQueryByTaskAssigneeLikeAsPost() { + String taskAssigneeLike = "aTaskAssigneeLike"; + + Map params = new HashMap<>(); + params.put("taskAssigneeLike", taskAssigneeLike); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskAssigneeLike(taskAssigneeLike); + } + + @Test + public void testQueryByTaskOwner() { + String taskOwner = MockProvider.EXAMPLE_HISTORIC_TASK_INST_OWNER; + + given() + .queryParam("taskOwner", taskOwner) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskOwner(taskOwner); + } + + @Test + public void testQueryByTaskOwnerAsPost() { + String taskOwner = MockProvider.EXAMPLE_HISTORIC_TASK_INST_OWNER; + + Map params = new HashMap<>(); + params.put("taskOwner", taskOwner); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskOwner(taskOwner); + } + + @Test + public void testQueryByTaskOwnerLike() { + String taskOwnerLike = "aTaskOwnerLike"; + + given() + .queryParam("taskOwnerLike", taskOwnerLike) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskOwnerLike(taskOwnerLike); + } + + @Test + public void testQueryByTaskOwnerLikeAsPost() { + String taskOwnerLike = "aTaskOwnerLike"; + + Map params = new HashMap<>(); + params.put("taskOwnerLike", taskOwnerLike); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskOwnerLike(taskOwnerLike); + } + + @Test + public void testQueryByTaskPriority() { + int taskPriority = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PRIORITY; + + given() + .queryParam("taskPriority", taskPriority) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskPriority(taskPriority); + } + + @Test + public void testQueryByTaskPriorityAsPost() { + int taskPriority = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PRIORITY; + + Map params = new HashMap<>(); + params.put("taskPriority", taskPriority); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskPriority(taskPriority); + } + + @Test + public void testQueryByAssigned() { + given() + .queryParam("assigned", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskAssigned(); + } + + @Test + public void testQueryByAssignedAsPost() { + Map params = new HashMap<>(); + params.put("assigned", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskAssigned(); + } + + @Test + public void testQueryByWithCandidateGroups() { + given() + .queryParam("withCandidateGroups", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withCandidateGroups(); + } + + @Test + public void testQueryByWithCandidateGroupsAsPost() { + Map params = new HashMap<>(); + params.put("withCandidateGroups", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withCandidateGroups(); + } + + @Test + public void testQueryByWithoutCandidateGroups() { + given() + .queryParam("withoutCandidateGroups", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withoutCandidateGroups(); + } + + @Test + public void testQueryByWithoutCandidateGroupsAsPost() { + Map params = new HashMap<>(); + params.put("withoutCandidateGroups", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).withoutCandidateGroups(); + } + + @Test + public void testQueryByUnassigned() { + given() + .queryParam("unassigned", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskUnassigned(); + } + + @Test + public void testQueryByUnassignedAsPost() { + Map params = new HashMap<>(); + params.put("unassigned", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskUnassigned(); + } + + @Test + public void testQueryByFinished() { + given() + .queryParam("finished", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).finished(); + } + + @Test + public void testQueryByFinishedAsPost() { + Map params = new HashMap<>(); + params.put("finished", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).finished(); + } + + @Test + public void testQueryByUnfinished() { + given() + .queryParam("unfinished", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).unfinished(); + } + + @Test + public void testQueryByUnfinishedAsPost() { + Map params = new HashMap<>(); + params.put("unfinished", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).unfinished(); + } + + @Test + public void testQueryByProcessFinished() { + given() + .queryParam("processFinished", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processFinished(); + } + + @Test + public void testQueryByProcessFinishedAsPost() { + Map params = new HashMap<>(); + params.put("processFinished", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processFinished(); + } + + @Test + public void testQueryByProcessUnfinished() { + given() + .queryParam("processUnfinished", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processUnfinished(); + } + + @Test + public void testQueryByProcessUnfinishedAsPost() { + Map params = new HashMap<>(); + params.put("processUnfinished", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processUnfinished(); + } + + @Test + public void testQueryByTaskParentTaskId() { + String taskParentTaskId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PARENT_TASK_ID; + + given() + .queryParam("taskParentTaskId", taskParentTaskId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskParentTaskId(taskParentTaskId); + } + + @Test + public void testQueryByTaskParentTaskIdAsPost() { + String taskParentTaskId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_PARENT_TASK_ID; + + Map params = new HashMap<>(); + params.put("taskParentTaskId", taskParentTaskId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskParentTaskId(taskParentTaskId); + } + + @Test + public void testQueryByTaskDueDate() { + String due = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DUE_DATE; + + given() + .queryParam("taskDueDate", due) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDueDate(DateTimeUtil.parseDate(due)); + } + + @Test + public void testQueryByTaskDueDateAsPost() { + String due = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DUE_DATE; + + Map params = new HashMap<>(); + params.put("taskDueDate", DateTimeUtil.parseDate(due)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDueDate(DateTimeUtil.parseDate(due)); + } + + @Test + public void testQueryByTaskDueDateBefore() { + String due = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DUE_DATE; + + given() + .queryParam("taskDueDateBefore", due) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDueBefore(DateTimeUtil.parseDate(due)); + } + + @Test + public void testQueryByTaskDueDateBeforeAsPost() { + String due = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DUE_DATE; + + Map params = new HashMap<>(); + params.put("taskDueDateBefore", DateTimeUtil.parseDate(due)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDueBefore(DateTimeUtil.parseDate(due)); + } + + @Test + public void testQueryByTaskDueDateAfter() { + String due = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DUE_DATE; + + given() + .queryParam("taskDueDateAfter", due) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDueAfter(DateTimeUtil.parseDate(due)); + } + + @Test + public void testQueryByTaskDueDateAfterAsPost() { + String due = MockProvider.EXAMPLE_HISTORIC_TASK_INST_DUE_DATE; + + Map params = new HashMap<>(); + params.put("taskDueDateAfter", DateTimeUtil.parseDate(due)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDueAfter(DateTimeUtil.parseDate(due)); + } + + @Test + public void testQueryWithoutTaskDueDateQueryParameter() { + // given + mockedQuery = setUpMockHistoricTaskInstanceQuery(Collections.singletonList( + MockProvider.createMockHistoricTaskInstance(MockProvider.EXAMPLE_TENANT_ID, null))); + + // when + Response response = given() + .queryParam("withoutTaskDueDate", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTaskDueDate(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTaskDueDate = from(content).getString("[0].due"); + assertThat(returnedTaskDueDate).isEqualTo(null); + } + + @Test + public void testQueryWithoutTaskDueDatePostParameter() { + // given + mockedQuery = setUpMockHistoricTaskInstanceQuery(Collections.singletonList( + MockProvider.createMockHistoricTaskInstance(MockProvider.EXAMPLE_TENANT_ID, null))); + Map queryParameters = Collections.singletonMap("withoutTaskDueDate", (Object) true); + + // when + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTaskDueDate(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTaskDueDate = from(content).getString("[0].due"); + assertThat(returnedTaskDueDate).isEqualTo(null); + } + + @Test + public void testQueryByTaskFollowUpDate() { + String followUp = MockProvider.EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE; + + given() + .queryParam("taskFollowUpDate", followUp) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskFollowUpDate(DateTimeUtil.parseDate(followUp)); + } + + @Test + public void testQueryByTaskFollowUpDateAsPost() { + String followUp = MockProvider.EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE; + + Map params = new HashMap<>(); + params.put("taskFollowUpDate", DateTimeUtil.parseDate(followUp)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskFollowUpDate(DateTimeUtil.parseDate(followUp)); + } + + @Test + public void testQueryByTaskFollowUpDateBefore() { + String followUp = MockProvider.EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE; + + given() + .queryParam("taskFollowUpDateBefore", followUp) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskFollowUpBefore(DateTimeUtil.parseDate(followUp)); + } + + @Test + public void testQueryByTaskFollowUpDateBeforeAsPost() { + String followUp = MockProvider.EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE; + + Map params = new HashMap<>(); + params.put("taskFollowUpDateBefore", DateTimeUtil.parseDate(followUp)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskFollowUpBefore(DateTimeUtil.parseDate(followUp)); + } + + @Test + public void testQueryByTaskFollowUpDateAfter() { + String followUp = MockProvider.EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE; + + given() + .queryParam("taskFollowUpDateAfter", followUp) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskFollowUpAfter(DateTimeUtil.parseDate(followUp)); + } + + @Test + public void testQueryByTaskFollowUpDateAfterAsPost() { + String followUp = MockProvider.EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE; + + Map params = new HashMap<>(); + params.put("taskFollowUpDateAfter", DateTimeUtil.parseDate(followUp)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskFollowUpAfter(DateTimeUtil.parseDate(followUp)); + } + + @Test + public void testQueryByStartedBefore() { + String startedBefore = MockProvider.EXAMPLE_HISTORIC_TASK_INST_START_TIME; + + given() + .queryParam("startedBefore", startedBefore) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).startedBefore(DateTimeUtil.parseDate(startedBefore)); + } + + @Test + public void testQueryByStartedBeforeWithInvalidParameter() { + String startedBefore = "\"pizza\""; + + given() + .queryParam("startedBefore", startedBefore) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON).body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body( + "message", + containsString("Cannot convert value " + startedBefore)) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + } + + @Test + public void testQueryByStartedBeforeAsPost() { + String startedBefore = MockProvider.EXAMPLE_HISTORIC_TASK_INST_START_TIME; + + Map params = new HashMap<>(); + params.put("startedBefore", DateTimeUtil.parseDate(startedBefore)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).startedBefore(DateTimeUtil.parseDate(startedBefore)); + } + + + @Test + public void testQueryByStartedAfter() { + String startedAfter = MockProvider.EXAMPLE_HISTORIC_TASK_INST_START_TIME; + + given() + .queryParam("startedAfter", startedAfter) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).startedAfter(DateTimeUtil.parseDate(startedAfter)); + } + + @Test + public void testQueryByStartedAfterAsPost() { + String startedAfter = MockProvider.EXAMPLE_HISTORIC_TASK_INST_START_TIME; + + Map params = new HashMap<>(); + params.put("startedAfter", DateTimeUtil.parseDate(startedAfter)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).startedAfter(DateTimeUtil.parseDate(startedAfter)); + } + + + @Test + public void testQueryByFinishedBefore() { + String finishedBefore = MockProvider.EXAMPLE_HISTORIC_TASK_INST_END_TIME; + + given() + .queryParam("finishedBefore", finishedBefore) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).finishedBefore(DateTimeUtil.parseDate(finishedBefore)); + } + + @Test + public void testQueryByFinishedBeforeAsPost() { + String finishedBefore = MockProvider.EXAMPLE_HISTORIC_TASK_INST_END_TIME; + + Map params = new HashMap<>(); + params.put("finishedBefore", DateTimeUtil.parseDate(finishedBefore)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).finishedBefore(DateTimeUtil.parseDate(finishedBefore)); + } + + + @Test + public void testQueryByFinishedAfter() { + String finishedAfter = MockProvider.EXAMPLE_HISTORIC_TASK_INST_END_TIME; + + given() + .queryParam("finishedAfter", finishedAfter) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).finishedAfter(DateTimeUtil.parseDate(finishedAfter)); + } + + @Test + public void testQueryByFinishedAfterAsPost() { + String finishedAfter = MockProvider.EXAMPLE_HISTORIC_TASK_INST_END_TIME; + + Map params = new HashMap<>(); + params.put("finishedAfter", DateTimeUtil.parseDate(finishedAfter)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).finishedAfter(DateTimeUtil.parseDate(finishedAfter)); + } + + @Test + public void testQueryByTaskVariable() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_eq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("taskVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskVariableValueEquals(variableName, variableValue); + } + + @Test + public void testQueryByTaskVariableValueIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_eq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).taskVariableValueEquals(variableName, variableValue); + } + + @Test + public void testQueryByTaskVariableNameIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_eq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).taskVariableValueEquals(variableName, variableValue); + } + + @Test + public void testQueryByTaskVariableNameValueIgnoreCase() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_eq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("taskVariables", queryValue) + .queryParam("variableNamesIgnoreCase", true) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).taskVariableValueEquals(variableName, variableValue); + } + + @Test + public void testQueryByTaskVariableAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + + Map variableJson = new HashMap<>(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map params = new HashMap<>(); + params.put("taskVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskVariableValueEquals(variableName, variableValue); + } + + @Test + public void testQueryByInvalidTaskVariable() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_" + invalidComparator + "_" + variableValue; + + given() + .queryParam("taskVariables", queryValue) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid variable comparator specified: " + invalidComparator)) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + // invalid format + queryValue = "invalidFormattedVariableQuery"; + + given() + .queryParam("taskVariables", queryValue) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("variable query parameter has to have format KEY_OPERATOR_VALUE")) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + } + + @Test + public void testQueryByInvalidTaskVariableAsPost() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + + Map variableJson = new HashMap<>(); + variableJson.put("name", variableName); + variableJson.put("operator", invalidComparator); + variableJson.put("value", variableValue); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map params = new HashMap<>(); + params.put("taskVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid variable comparator specified: " + invalidComparator)) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + } + + @Test + public void testQueryByProcessVariableEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_eq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueEquals(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableGreaterThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_gt_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueGreaterThan(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableGreaterThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_gteq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueGreaterThanOrEquals(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableLessThan() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_lt_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueLessThan(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableLessThanEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_lteq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueLessThanOrEquals(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_like_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueLike(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableNotLike() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_notLike_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueNotLike(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableNotEquals() { + String variableName = "varName"; + String variableValue = "varValue"; + String variableParameter = variableName + "_neq_" + variableValue; + + String queryValue = variableParameter; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueNotEquals(variableName, variableValue); + } + + @Test + public void testQueryByProcessVariableAsPost() { + String variableName = "varName"; + String variableValue = "varValue"; + + Map variableJson = new HashMap<>(); + variableJson.put("name", variableName); + variableJson.put("operator", "eq"); + variableJson.put("value", variableValue); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map params = new HashMap<>(); + params.put("processVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processVariableValueEquals(variableName, variableValue); + } + + @Test + public void testQueryByInvalidProcessVariable() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + String queryValue = variableName + "_" + invalidComparator + "_" + variableValue; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid process variable comparator specified: " + invalidComparator)) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + // invalid format + queryValue = "invalidFormattedVariableQuery"; + + given() + .queryParam("processVariables", queryValue) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("variable query parameter has to have format KEY_OPERATOR_VALUE")) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + } + + @Test + public void testQueryByInvalidProcessVariableAsPost() { + // invalid comparator + String invalidComparator = "anInvalidComparator"; + String variableName = "varName"; + String variableValue = "varValue"; + + Map variableJson = new HashMap<>(); + variableJson.put("name", variableName); + variableJson.put("operator", invalidComparator); + variableJson.put("value", variableValue); + + List> variables = new ArrayList<>(); + variables.add(variableJson); + + Map params = new HashMap<>(); + params.put("processVariables", variables); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Invalid process variable comparator specified: " + invalidComparator)) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + } + + @Test + public void testQueryByCaseDefinitionId() { + String caseDefinitionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_ID; + + given() + .queryParam("caseDefinitionId", caseDefinitionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseDefinitionId(caseDefinitionId); + } + + @Test + public void testQueryByCaseDefinitionIdAsPost() { + String caseDefinitionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_ID; + + Map params = new HashMap<>(); + params.put("caseDefinitionId", caseDefinitionId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseDefinitionId(caseDefinitionId); + } + + @Test + public void testQueryByCaseDefinitionKey() { + String caseDefinitionKey = "aCaseDefKey"; + + given() + .queryParam("caseDefinitionKey", caseDefinitionKey) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseDefinitionKey(caseDefinitionKey); + } + + @Test + public void testQueryByCaseDefinitionKeyAsPost() { + String caseDefinitionKey = "aCaseDefKey"; + + Map params = new HashMap<>(); + params.put("caseDefinitionKey", caseDefinitionKey); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseDefinitionKey(caseDefinitionKey); + } + + @Test + public void testQueryByCaseDefinitionName() { + String caseDefinitionName = "aCaseDefName"; + + given() + .queryParam("caseDefinitionName", caseDefinitionName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseDefinitionName(caseDefinitionName); + } + + @Test + public void testQueryByCaseDefinitionNameAsPost() { + String caseDefinitionName = "aCaseDefName"; + + Map params = new HashMap<>(); + params.put("caseDefinitionName", caseDefinitionName); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseDefinitionName(caseDefinitionName); + } + + @Test + public void testQueryByCaseInstanceId() { + String caseInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_INST_ID; + + given() + .queryParam("caseInstanceId", caseInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseInstanceId(caseInstanceId); + } + + @Test + public void testQueryByCaseInstanceIdAsPost() { + String caseInstanceId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_INST_ID; + + Map params = new HashMap<>(); + params.put("caseInstanceId", caseInstanceId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseInstanceId(caseInstanceId); + } + + @Test + public void testQueryByCaseExecutionId() { + String caseExecutionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_EXEC_ID; + + given() + .queryParam("caseExecutionId", caseExecutionId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseExecutionId(caseExecutionId); + } + + @Test + public void testQueryByCaseExecutionIdAsPost() { + String caseExecutionId = MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_EXEC_ID; + + Map params = new HashMap<>(); + params.put("caseExecutionId", caseExecutionId); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(params) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseExecutionId(caseExecutionId); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricTaskInstanceQuery(createMockHistoricTaskInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockHistoricTaskInstanceQuery(createMockHistoricTaskInstancesTwoTenants()); + + Map queryParameters = new HashMap<>(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryWithoutTenantIdQueryParameter() { + // given + mockedQuery = setUpMockHistoricTaskInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricTaskInstance(null))); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryWithoutTenantIdPostParameter() { + // given + mockedQuery = setUpMockHistoricTaskInstanceQuery(Collections.singletonList(MockProvider.createMockHistoricTaskInstance(null))); + Map queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); + + // when + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryTaskInvolvedUser() { + String taskInvolvedUser = MockProvider.EXAMPLE_HISTORIC_TASK_INST_TASK_INVOLVED_USER; + given() + .queryParam("taskInvolvedUser", taskInvolvedUser) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskInvolvedUser(taskInvolvedUser); + } + + @Test + public void testQueryTaskInvolvedGroup() { + String taskInvolvedGroup = MockProvider.EXAMPLE_HISTORIC_TASK_INST_TASK_INVOLVED_GROUP; + given() + .queryParam("taskInvolvedGroup", taskInvolvedGroup) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskInvolvedGroup(taskInvolvedGroup); + } + + @Test + public void testQueryTaskHadCandidateUser() { + String taskHadCandidateUser = MockProvider.EXAMPLE_HISTORIC_TASK_INST_TASK_HAD_CANDIDATE_USER; + given() + .queryParam("taskHadCandidateUser", taskHadCandidateUser) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskHadCandidateUser(taskHadCandidateUser); + } + + @Test + public void testQueryTaskHadCandidateGroup() { + String taskHadCandidateGroup = MockProvider.EXAMPLE_HISTORIC_TASK_INST_TASK_HAD_CANDIDATE_GROUP; + given() + .queryParam("taskHadCandidateGroup", taskHadCandidateGroup) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskHadCandidateGroup(taskHadCandidateGroup); + } + + @Test + public void testQueryByTaskDefinitionKeyIn() { + + String taskDefinitionKey1 = "aTaskDefinitionKey"; + String taskDefinitionKey2 = "anotherTaskDefinitionKey"; + + given() + .queryParam("taskDefinitionKeyIn", taskDefinitionKey1 + "," + taskDefinitionKey2) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDefinitionKeyIn(taskDefinitionKey1, taskDefinitionKey2); + verify(mockedQuery).list(); + } + + @Test + public void testQueryByTaskDefinitionKeyInAsPost() { + + String taskDefinitionKey1 = "aTaskDefinitionKey"; + String taskDefinitionKey2 = "anotherTaskDefinitionKey"; + + List taskDefinitionKeys = new ArrayList<>(); + taskDefinitionKeys.add(taskDefinitionKey1); + taskDefinitionKeys.add(taskDefinitionKey2); + + Map queryParameters = new HashMap<>(); + queryParameters.put("taskDefinitionKeyIn", taskDefinitionKeys); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).taskDefinitionKeyIn(taskDefinitionKey1, taskDefinitionKey2); + verify(mockedQuery).list(); + } + + @Test + public void testOrQuery() { + // given + HistoricTaskInstanceQueryImpl mockedQuery = mock(HistoricTaskInstanceQueryImpl.class); + when(processEngine.getHistoryService().createHistoricTaskInstanceQuery()).thenReturn(mockedQuery); + + String payload = "{ \"orQueries\": [{" + + "\"processDefinitionKey\": \"aKey\", " + + "\"processInstanceBusinessKey\": \"aBusinessKey\"}] }"; + + // when + given() + .contentType(POST_JSON_CONTENT_TYPE) + .header(ACCEPT_JSON_HEADER) + .body(payload) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_TASK_INSTANCE_RESOURCE_URL); + + ArgumentCaptor argument = + ArgumentCaptor.forClass(HistoricTaskInstanceQueryImpl.class); + + verify(mockedQuery).addOrQuery(argument.capture()); + + // then + assertThat(argument.getValue().getProcessDefinitionKey()).isEqualTo("aKey"); + assertThat(argument.getValue().getProcessInstanceBusinessKey()).isEqualTo("aBusinessKey"); + } + + private List createMockHistoricTaskInstancesTwoTenants() { + return Arrays.asList( + MockProvider.createMockHistoricTaskInstance(MockProvider.EXAMPLE_TENANT_ID), + MockProvider.createMockHistoricTaskInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID)); + } + + protected void verifyHistoricTaskInstanceEntries(String content) { + String returnedId = from(content).getString("[0].id"); + String returnedProcessDefinitionKey = from(content).getString("[0].processDefinitionKey"); + String returnedProcessDefinitionId = from(content).getString("[0].processDefinitionId"); + String returnedProcessInstanceId = from(content).getString("[0].processInstanceId"); + String returnedExecutionId = from(content).getString("[0].executionId"); + String returnedActivityInstanceId = from(content).getString("[0].activityInstanceId"); + String returnedName = from(content).getString("[0].name"); + String returnedDescription = from(content).getString("[0].description"); + String returnedDeleteReason = from(content).getString("[0].deleteReason"); + String returnedOwner = from(content).getString("[0].owner"); + String returnedAssignee = from(content).getString("[0].assignee"); + Date returnedStartTime = DateTimeUtil.parseDate(from(content).getString("[0].startTime")); + Date returnedEndTime = DateTimeUtil.parseDate(from(content).getString("[0].endTime")); + Long returnedDurationInMillis = from(content).getLong("[0].duration"); + String returnedTaskDefinitionKey = from(content).getString("[0].taskDefinitionKey"); + int returnedPriority = from(content).getInt("[0].priority"); + String returnedParentTaskId = from(content).getString("[0].parentTaskId"); + Date returnedDue = DateTimeUtil.parseDate(from(content).getString("[0].due")); + Date returnedFollow = DateTimeUtil.parseDate(from(content).getString("[0].followUp")); + String returnedCaseDefinitionKey = from(content).getString("[0].caseDefinitionKey"); + String returnedCaseDefinitionId = from(content).getString("[0].caseDefinitionId"); + String returnedCaseInstanceId = from(content).getString("[0].caseInstanceId"); + String returnedCaseExecutionId = from(content).getString("[0].caseExecutionId"); + String returnedTenantId = from(content).getString("[0].tenantId"); + String returnedTaskState = from(content).getString("[0].taskState"); + Date returnedRemovalTime = DateTimeUtil.parseDate(from(content).getString("[0].removalTime")); + String returnedRootProcessInstanceId = from(content).getString("[0].rootProcessInstanceId"); + + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_ID, returnedId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_INST_ID, returnedProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_ACT_INST_ID, returnedActivityInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_EXEC_ID, returnedExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_ID, returnedProcessDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_PROC_DEF_KEY, returnedProcessDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_NAME, returnedName); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_DESCRIPTION, returnedDescription); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_DELETE_REASON, returnedDeleteReason); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_OWNER, returnedOwner); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_ASSIGNEE, returnedAssignee); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_TASK_INST_START_TIME), returnedStartTime); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_TASK_INST_END_TIME), returnedEndTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_DURATION, returnedDurationInMillis); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_DEF_KEY, returnedTaskDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_PRIORITY, returnedPriority); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_TASK_INST_DUE_DATE), returnedDue); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_TASK_INST_FOLLOW_UP_DATE), returnedFollow); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_PARENT_TASK_ID, returnedParentTaskId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_KEY, returnedCaseDefinitionKey); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_DEF_ID, returnedCaseDefinitionId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_INST_ID, returnedCaseInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_CASE_EXEC_ID, returnedCaseExecutionId); + Assert.assertEquals(MockProvider.EXAMPLE_TENANT_ID, returnedTenantId); + Assert.assertEquals(DateTimeUtil.parseDate(MockProvider.EXAMPLE_HISTORIC_TASK_INST_REMOVAL_TIME), returnedRemovalTime); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_INST_ROOT_PROC_INST_ID, returnedRootProcessInstanceId); + Assert.assertEquals(MockProvider.EXAMPLE_HISTORIC_TASK_STATE,returnedTaskState); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricTaskReportRestServiceTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricTaskReportRestServiceTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f381b7e5b6bf01521b8f3ab58cf26a414a1a74c1 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricTaskReportRestServiceTest.java @@ -0,0 +1,611 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import io.restassured.http.ContentType; +import org.camunda.bpm.engine.AuthorizationException; +import org.camunda.bpm.engine.history.DurationReportResult; +import org.camunda.bpm.engine.history.HistoricTaskInstanceReport; +import org.camunda.bpm.engine.history.HistoricTaskInstanceReportResult; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.query.PeriodUnit; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import javax.ws.rs.core.Response.Status; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.camunda.bpm.engine.query.PeriodUnit.MONTH; +import static org.camunda.bpm.engine.query.PeriodUnit.QUARTER; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_END_TIME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_AVG; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MAX; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MIN; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_PERIOD; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_INST_END_TIME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_INST_START_TIME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_REPORT_COUNT; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_REPORT_DEFINITION; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEFINITION; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_NAME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_REPORT_TASK_NAME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_HISTORIC_TASK_START_TIME; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_TENANT_ID; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockHistoricTaskInstanceDurationReport; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockHistoricTaskInstanceReport; +import static org.camunda.bpm.engine.rest.helper.MockProvider.createMockHistoricTaskInstanceReportWithProcDef; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * @author Stefan Hentschel. + */ +public class HistoricTaskReportRestServiceTest extends AbstractRestServiceTest { + + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String TASK_REPORT_URL = TEST_RESOURCE_ROOT_PATH + "/history/task/report"; + + protected HistoricTaskInstanceReport mockedReportQuery; + + @Before + public void setUpRuntimeData() { + mockedReportQuery = setUpMockReportQuery(); + } + + private HistoricTaskInstanceReport setUpMockReportQuery() { + HistoricTaskInstanceReport mockedReportQuery = mock(HistoricTaskInstanceReport.class); + + List taskReportResults = createMockHistoricTaskInstanceReport(); + List taskReportResultsWithProcDef = createMockHistoricTaskInstanceReportWithProcDef(); + + when(mockedReportQuery.completedAfter(any(Date.class))).thenReturn(mockedReportQuery); + when(mockedReportQuery.completedBefore(any(Date.class))).thenReturn(mockedReportQuery); + + when(mockedReportQuery.countByTaskName()).thenReturn(taskReportResults); + when(mockedReportQuery.countByProcessDefinitionKey()).thenReturn(taskReportResultsWithProcDef); + + List durationReportByMonth = createMockHistoricTaskInstanceDurationReport(MONTH); + when(mockedReportQuery.duration(MONTH)).thenReturn(durationReportByMonth); + + List durationReportByQuarter = createMockHistoricTaskInstanceDurationReport(QUARTER); + when(mockedReportQuery.duration(QUARTER)).thenReturn(durationReportByQuarter); + + when(processEngine.getHistoryService().createHistoricTaskInstanceReport()).thenReturn(mockedReportQuery); + + return mockedReportQuery; + } + + @Test + public void testTaskCountMissingAuthorization() { + String message = "not authorized"; + when(mockedReportQuery.countByTaskName()).thenThrow(new AuthorizationException(message)); + + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "taskName") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(TASK_REPORT_URL); + } + + + @Test + public void testTaskCountByProcDefMissingAuthorization() { + String message = "not authorized"; + when(mockedReportQuery.countByProcessDefinitionKey()).thenThrow(new AuthorizationException(message)); + + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "processDefinition") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskCountReport() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "taskName") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("[0].count", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_COUNT.intValue())) + .body("[0].processDefinitionId", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_ID)) + .body("[0].processDefinitionName", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_NAME)) + .body("[0].processDefinitionKey", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEFINITION)) + .body("[0].taskName", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_TASK_NAME)) + .body("[0].tenantId", equalTo(EXAMPLE_TENANT_ID)) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).countByTaskName(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskCountReportWithCompletedBefore() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "taskName") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_END_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedBefore(any(Date.class)); + verify(mockedReportQuery).countByTaskName(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskCountReportWithCompletedAfter() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "taskName") + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_START_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedAfter(any(Date.class)); + verify(mockedReportQuery).countByTaskName(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskCountByProcDefReportWithCompletedBefore() { + given() + .queryParam("reportType", "count") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_END_TIME) + .queryParam("groupBy", "processDefinition") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedBefore(any(Date.class)); + verify(mockedReportQuery).countByProcessDefinitionKey(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskCountByProcDefReportWithCompletedAfter() { + given() + .queryParam("reportType", "count") + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_START_TIME) + .queryParam("groupBy", "processDefinition") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedAfter(any(Date.class)); + verify(mockedReportQuery).countByProcessDefinitionKey(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskCountReportWithGroupByProcDef() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "processDefinition") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).countByProcessDefinitionKey(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskCountReportWithGroupByTaskDef() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "taskName") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).countByTaskName(); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskCountReportWithGroupByAnyDef() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "anotherDefinition") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("groupBy parameter has invalid value: anotherDefinition")) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskCountWithAllParameters() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "processDefinition") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_INST_END_TIME) + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_INST_START_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("[0].count", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_COUNT.intValue())) + .body("[0].processDefinitionId", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_ID)) + .body("[0].processDefinitionName", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_NAME)) + .body("[0].processDefinitionKey", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEFINITION)) + .body("[0].taskName", equalTo(null)) + .body("[0].tenantId", equalTo(EXAMPLE_TENANT_ID)) + .when() + .get(TASK_REPORT_URL); + + verifyStringStartParameterQueryInvocations(); + verify(mockedReportQuery).countByProcessDefinitionKey(); + verifyNoMoreInteractions(mockedReportQuery); + + } + + @Test + public void testTaskCountWithAllParametersGroupByTask() { + given() + .queryParam("reportType", "count") + .queryParam("groupBy", "taskName") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_INST_END_TIME) + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_INST_START_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("[0].count", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_COUNT.intValue())) + .body("[0].processDefinitionId", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_ID)) + .body("[0].processDefinitionName", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEF_NAME)) + .body("[0].processDefinitionKey", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_PROC_DEFINITION)) + .body("[0].taskName", equalTo(EXAMPLE_HISTORIC_TASK_REPORT_TASK_NAME)) + .body("[0].tenantId", equalTo(EXAMPLE_TENANT_ID)) + .when() + .get(TASK_REPORT_URL); + + verifyStringStartParameterQueryInvocations(); + verify(mockedReportQuery).countByTaskName(); + verifyNoMoreInteractions(mockedReportQuery); + + } + + // TASK DURATION REPORT /////////////////////////////////////////////////////// + @Test + public void testTaskDurationMonthMissingAuthorization() { + String message = "not authorized"; + when(mockedReportQuery.duration(MONTH)).thenThrow(new AuthorizationException(message)); + + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "month") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskDurationQuarterMissingAuthorization() { + String message = "not authorized"; + when(mockedReportQuery.duration(QUARTER)).thenThrow(new AuthorizationException(message)); + + given() + .queryParam("reportType", "duration") + .queryParam("periodUnit", "quarter") + .then() + .expect() + .statusCode(Status.FORBIDDEN.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(AuthorizationException.class.getSimpleName())) + .body("message", equalTo(message)) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testWrongReportType() { + given() + .queryParam("reportType", "abc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot set query parameter 'reportType' to value 'abc'")) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskDurationReportWithoutDurationParam() { + given() + .queryParam("periodUnit", "month") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Parameter reportType is not set.")) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskDurationQuarterReportWithoutDurationParam() { + given() + .queryParam("periodUnit", "quarter") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Parameter reportType is not set.")) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskDurationReportWithInvalidPeriodUnit() { + given() + .queryParam("periodUnit", "abc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Cannot set query parameter 'periodUnit' to value 'abc'")) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskDurationReportWithMissingPeriodUnit() { + given() + .queryParam("reportType", "duration") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("periodUnit is null")) + .when() + .get(TASK_REPORT_URL); + } + + @Test + public void testTaskDurationReportByMonth() { + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("[0].average", equalTo((int) EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_AVG)) + .body("[0].maximum", equalTo((int) EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MAX)) + .body("[0].minimum", equalTo((int) EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MIN)) + .body("[0].period", equalTo(EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_PERIOD)) + .body("[0].periodUnit", equalTo(MONTH.toString())) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).duration(PeriodUnit.MONTH); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskDurationReportByQuarter() { + given() + .queryParam("periodUnit", "quarter") + .queryParam("reportType", "duration") + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .body("[0].average", equalTo((int) EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_AVG)) + .body("[0].maximum", equalTo((int) EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MAX)) + .body("[0].minimum", equalTo((int) EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_MIN)) + .body("[0].period", equalTo(EXAMPLE_HISTORIC_TASK_INST_DURATION_REPORT_PERIOD)) + .body("[0].periodUnit", equalTo(QUARTER.toString())) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).duration(PeriodUnit.QUARTER); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskDurationReportWithCompletedBeforeAndCompletedAfter() { + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_INST_START_TIME) + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_INST_END_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verifyStringStartParameterQueryInvocations(); + verify(mockedReportQuery).duration(PeriodUnit.MONTH); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskDurationReportWithCompletedBefore() { + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_END_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedBefore(any(Date.class)); + verify(mockedReportQuery).duration(PeriodUnit.MONTH); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskDurationReportWithCompletedAfter() { + given() + .queryParam("periodUnit", "month") + .queryParam("reportType", "duration") + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_START_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedAfter(any(Date.class)); + verify(mockedReportQuery).duration(PeriodUnit.MONTH); + verifyNoMoreInteractions(mockedReportQuery); + } + + + @Test + public void testTaskDurationQuarterReportWithCompletedBeforeAndCompletedAfter() { + given() + .queryParam("periodUnit", "quarter") + .queryParam("reportType", "duration") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_INST_START_TIME) + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_INST_END_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verifyStringStartParameterQueryInvocations(); + verify(mockedReportQuery).duration(PeriodUnit.QUARTER); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskDurationQuarterReportWithCompletedBefore() { + given() + .queryParam("periodUnit", "quarter") + .queryParam("reportType", "duration") + .queryParam("completedBefore", EXAMPLE_HISTORIC_TASK_END_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedBefore(any(Date.class)); + verify(mockedReportQuery).duration(PeriodUnit.QUARTER); + verifyNoMoreInteractions(mockedReportQuery); + } + + @Test + public void testTaskDurationQuarterReportWithCompletedAfter() { + given() + .queryParam("periodUnit", "quarter") + .queryParam("reportType", "duration") + .queryParam("completedAfter", EXAMPLE_HISTORIC_TASK_START_TIME) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.JSON) + .when() + .get(TASK_REPORT_URL); + + verify(mockedReportQuery).completedAfter(any(Date.class)); + verify(mockedReportQuery).duration(PeriodUnit.QUARTER); + verifyNoMoreInteractions(mockedReportQuery); + } + + + private Map getCompleteStartDateAsStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("completedBefore", EXAMPLE_HISTORIC_TASK_INST_START_TIME); + parameters.put("completedAfter", EXAMPLE_HISTORIC_TASK_INST_END_TIME); + + return parameters; + } + + private void verifyStringStartParameterQueryInvocations() { + Map startDateParameters = getCompleteStartDateAsStringQueryParameters(); + + verify(mockedReportQuery).completedBefore(DateTimeUtil.parseDate(startDateParameters.get("completedBefore"))); + verify(mockedReportQuery).completedAfter(DateTimeUtil.parseDate(startDateParameters.get("completedAfter"))); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..928ef52951375d7fad7334d14a3b7540579be13a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestServiceInteractionTest.java @@ -0,0 +1,389 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.either; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.exception.NotFoundException; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.helper.MockHistoricVariableInstanceBuilder; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.camunda.bpm.engine.variable.value.FileValue; +import org.camunda.bpm.engine.variable.value.ObjectValue; +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Daniel Meyer + * + */ +public class HistoricVariableInstanceRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/variable-instance"; + protected static final String VARIABLE_INSTANCE_URL = HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL + "/{id}"; + protected static final String VARIABLE_INSTANCE_BINARY_DATA_URL = VARIABLE_INSTANCE_URL + "/data"; + + protected HistoryService historyServiceMock; + + protected HistoricVariableInstanceQuery variableInstanceQueryMock; + + @Before + public void setupTestData() { + historyServiceMock = mock(HistoryService.class); + variableInstanceQueryMock = mock(HistoricVariableInstanceQuery.class); + + // mock engine service. + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + when(historyServiceMock.createHistoricVariableInstanceQuery()).thenReturn(variableInstanceQueryMock); + } + + @Test + public void testGetSingleVariableInstance() { + MockHistoricVariableInstanceBuilder builder = MockProvider.mockHistoricVariableInstance(); + + HistoricVariableInstance variableInstanceMock = builder.build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", builder.getId()) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("name", equalTo(builder.getName())) + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo(builder.getValue())) + .body("processDefinitionKey", equalTo(builder.getProcessDefinitionKey())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("caseDefinitionKey", equalTo(builder.getCaseDefinitionKey())) + .body("caseDefinitionId", equalTo(builder.getCaseDefinitionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("taskId", equalTo(builder.getTaskId())) + .body("tenantId", equalTo(builder.getTenantId())) + .body("createTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_CREATE_TIME)) + .body("removalTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_REMOVAL_TIME)) + .body("rootProcessInstanceId", equalTo(builder.getRootProcessInstanceId())) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + + } + + @Test + public void testGetSingleVariableInstanceDeserialized() { + ObjectValue serializedValue = MockObjectValue.fromObjectValue( + Variables.objectValue("a value").serializationDataFormat("aDataFormat").create()) + .objectTypeName("aTypeName"); + + MockHistoricVariableInstanceBuilder builder = MockProvider.mockHistoricVariableInstance().typedValue(serializedValue); + HistoricVariableInstance variableInstanceMock = builder.build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("name", equalTo(builder.getName())) + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo("a value")) + .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) + .body("valueInfo.objectTypeName", equalTo("aTypeName")) + .body("processDefinitionKey", equalTo(builder.getProcessDefinitionKey())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("caseDefinitionKey", equalTo(builder.getCaseDefinitionKey())) + .body("caseDefinitionId", equalTo(builder.getCaseDefinitionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("taskId", equalTo(builder.getTaskId())) + .body("tenantId", equalTo(builder.getTenantId())) + .body("createTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_CREATE_TIME)) + .body("removalTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_REMOVAL_TIME)) + .body("rootProcessInstanceId", equalTo(builder.getRootProcessInstanceId())) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + verify(variableInstanceQueryMock, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testGetSingleVariableInstanceSerialized() { + ObjectValue serializedValue = Variables.serializedObjectValue("a serialized value") + .serializationDataFormat("aDataFormat").objectTypeName("aTypeName").create(); + + MockHistoricVariableInstanceBuilder builder = MockProvider.mockHistoricVariableInstance().typedValue(serializedValue); + HistoricVariableInstance variableInstanceMock = builder.build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given() + .pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .queryParam("deserializeValue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("id", equalTo(builder.getId())) + .body("name", equalTo(builder.getName())) + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(builder.getTypedValue().getType()))) + .body("value", equalTo("a serialized value")) + .body("valueInfo.serializationDataFormat", equalTo("aDataFormat")) + .body("valueInfo.objectTypeName", equalTo("aTypeName")) + .body("processInstanceId", equalTo(builder.getProcessInstanceId())) + .body("processDefinitionKey", equalTo(builder.getProcessDefinitionKey())) + .body("processDefinitionId", equalTo(builder.getProcessDefinitionId())) + .body("executionId", equalTo(builder.getExecutionId())) + .body("errorMessage", equalTo(builder.getErrorMessage())) + .body("activityInstanceId", equalTo(builder.getActivityInstanceId())) + .body("caseDefinitionKey", equalTo(builder.getCaseDefinitionKey())) + .body("caseDefinitionId", equalTo(builder.getCaseDefinitionId())) + .body("caseInstanceId", equalTo(builder.getCaseInstanceId())) + .body("caseExecutionId", equalTo(builder.getCaseExecutionId())) + .body("taskId", equalTo(builder.getTaskId())) + .body("tenantId", equalTo(builder.getTenantId())) + .body("createTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_CREATE_TIME)) + .body("removalTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_REMOVAL_TIME)) + .body("rootProcessInstanceId", equalTo(builder.getRootProcessInstanceId())) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + verify(variableInstanceQueryMock, times(1)).disableCustomObjectDeserialization(); + } + + @Test + public void testGetSingleVariableInstanceForBinaryVariable() { + MockHistoricVariableInstanceBuilder builder = MockProvider.mockHistoricVariableInstance(); + + HistoricVariableInstance variableInstanceMock = builder + .typedValue(Variables.byteArrayValue(null)) + .build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("type", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.BYTES))) + .body("value", nullValue()) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + + } + + @Test + public void testGetNonExistingVariableInstance() { + + String nonExistingId = "nonExistingId"; + + when(variableInstanceQueryMock.variableId(nonExistingId)).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableBinaryFetching()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", nonExistingId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Historic variable instance with Id 'nonExistingId' does not exist.")) + .when().get(VARIABLE_INSTANCE_URL); + + verify(variableInstanceQueryMock, times(1)).disableBinaryFetching(); + + } + + @Test + public void testBinaryDataForBinaryVariable() { + final byte[] byteContent = "some bytes".getBytes(); + HistoricVariableInstance variableInstanceMock = MockProvider.mockHistoricVariableInstance() + .typedValue(Variables.byteArrayValue(byteContent)) + .build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .contentType(ContentType.BINARY.toString()) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + byte[] responseBytes = response.getBody().asByteArray(); + Assert.assertEquals(new String(byteContent), new String(responseBytes)); + verify(variableInstanceQueryMock, never()).disableBinaryFetching(); + + } + + @Test + public void testGetBinaryDataForFileVariable() { + String filename = "test.txt"; + byte[] byteContent = "test".getBytes(); + String encoding = "UTF-8"; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).encoding(encoding).create(); + HistoricVariableInstance variableInstanceMock = MockProvider.mockHistoricVariableInstance().typedValue(variableValue).build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + Response response = given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body(is(equalTo(new String(byteContent)))) + .header("Content-Disposition", "attachment; " + + "filename=\"" + filename + "\"; " + + "filename*=UTF-8''" + filename) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + //due to some problems with wildfly we gotta check this separately + String contentType = response.getContentType(); + assertThat(contentType, is(either(CoreMatchers.equalTo(ContentType.TEXT.toString() + "; charset=UTF-8")).or(CoreMatchers.equalTo(ContentType.TEXT.toString() + ";charset=UTF-8")))); + + verify(variableInstanceQueryMock, never()).disableBinaryFetching(); + } + + @Test + public void testBinaryDataForNonBinaryVariable() { + HistoricVariableInstance variableInstanceMock = MockProvider.createMockHistoricVariableInstance(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .body(containsString("Value of variable with id "+variableInstanceMock.getId()+" is not a binary value")) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + verify(variableInstanceQueryMock, never()).disableBinaryFetching(); + + } + + @Test + public void testGetBinaryDataForNonExistingVariableInstance() { + + String nonExistingId = "nonExistingId"; + + when(variableInstanceQueryMock.variableId(nonExistingId)).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(null); + + given().pathParam("id", nonExistingId) + .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("Historic variable instance with Id 'nonExistingId' does not exist.")) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + + verify(variableInstanceQueryMock, never()).disableBinaryFetching(); + + } + + @Test + public void testGetBinaryDataForNullFileVariable() { + String filename = "test.txt"; + byte[] byteContent = null; + FileValue variableValue = Variables.fileValue(filename).file(byteContent).mimeType(ContentType.TEXT.toString()).create(); + + HistoricVariableInstance variableInstanceMock = MockProvider.mockHistoricVariableInstance() + .typedValue(variableValue) + .build(); + + when(variableInstanceQueryMock.variableId(variableInstanceMock.getId())).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.disableCustomObjectDeserialization()).thenReturn(variableInstanceQueryMock); + when(variableInstanceQueryMock.singleResult()).thenReturn(variableInstanceMock); + + given().pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .then().expect().statusCode(Status.OK.getStatusCode()) + .and().contentType(ContentType.TEXT) + .and().body(is(equalTo(new String()))) + .when().get(VARIABLE_INSTANCE_BINARY_DATA_URL); + } + + @Test + public void testDeleteSingleVariableInstanceById() { + given() + .pathParam("id", MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .delete(VARIABLE_INSTANCE_URL); + + verify(historyServiceMock).deleteHistoricVariableInstance(MockProvider.EXAMPLE_VARIABLE_INSTANCE_ID); + } + + @Test + public void testDeleteNonExistingVariableInstanceById() { + doThrow(new NotFoundException("No historic variable instance found with id: 'NON_EXISTING_ID'")) + .when(historyServiceMock).deleteHistoricVariableInstance("NON_EXISTING_ID"); + + given() + .pathParam("id", "NON_EXISTING_ID") + .expect() + .statusCode(Status.NOT_FOUND.getStatusCode()) + .body(containsString("No historic variable instance found with id: 'NON_EXISTING_ID'")) + .when() + .delete(VARIABLE_INSTANCE_URL); + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d4155340ba5d71147cad3101ec88d5ee9a9ff7d0 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoricVariableInstanceRestServiceQueryTest.java @@ -0,0 +1,1059 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstanceQuery; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockHistoricVariableInstanceBuilder; +import org.camunda.bpm.engine.rest.helper.MockObjectValue; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.helper.VariableTypeHelper; +import org.camunda.bpm.engine.rest.util.OrderingBuilder; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.camunda.bpm.engine.variable.type.SerializableValueType; +import org.camunda.bpm.engine.variable.type.ValueType; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.Mockito; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.anyString; + +public class HistoricVariableInstanceRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/variable-instance"; + + protected static final String HISTORIC_VARIABLE_INSTANCE_COUNT_RESOURCE_URL = HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL + "/count"; + + protected HistoricVariableInstanceQuery mockedQuery; + protected HistoricVariableInstance mockInstance; + protected MockHistoricVariableInstanceBuilder mockInstanceBuilder; + + @Before + public void setUpRuntimeData() { + mockInstanceBuilder = MockProvider.mockHistoricVariableInstance(); + mockInstance = mockInstanceBuilder.build(); + + List mocks = new ArrayList(); + mocks.add(mockInstance); + + mockedQuery = setUpMockHistoricVariableInstanceQuery(mocks); + } + + private HistoricVariableInstanceQuery setUpMockHistoricVariableInstanceQuery(List mockedHistoricVariableInstances) { + + HistoricVariableInstanceQuery mockedHistoricVariableInstanceQuery = mock(HistoricVariableInstanceQuery.class); + when(mockedHistoricVariableInstanceQuery.list()).thenReturn(mockedHistoricVariableInstances); + when(mockedHistoricVariableInstanceQuery.count()).thenReturn((long) mockedHistoricVariableInstances.size()); + + when(processEngine.getHistoryService().createHistoricVariableInstanceQuery()).thenReturn(mockedHistoricVariableInstanceQuery); + + return mockedHistoricVariableInstanceQuery; + } + + @Test + public void testEmptyQuery() { + String queryKey = ""; + given() + .queryParam("processInstanceId", queryKey) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testNoParametersQuery() { + expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryDisableObjectDeserialization() { + given() + .queryParam("deserializeValues", false) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery).disableCustomObjectDeserialization(); + + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testNoParametersQueryAsPostDisableObjectDeserialization() { + given() + .queryParam("deserializeValues", false) + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).list(); + verify(mockedQuery).disableBinaryFetching(); + verify(mockedQuery).disableCustomObjectDeserialization(); + verifyNoMoreInteractions(mockedQuery); + } + + @Test + public void testInvalidSortingOptions() { + executeAndVerifySorting("anInvalidSortByOption", "asc", Status.BAD_REQUEST); + executeAndVerifySorting("instanceId", "anInvalidSortOrderOption", Status.BAD_REQUEST); + } + + protected void executeAndVerifySorting(String sortBy, String sortOrder, Status expectedStatus) { + given() + .queryParam("sortBy", sortBy).queryParam("sortOrder", sortOrder) + .then() + .expect().statusCode(expectedStatus.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortByParameterOnly() { + given() + .queryParam("sortBy", "instanceId") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortOrderParameterOnly() { + given() + .queryParam("sortOrder", "asc") + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single sorting parameter specified. sortBy and sortOrder required")) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testSortingParameters() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + + executeAndVerifySorting("instanceId", "asc", Status.OK); + + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + + executeAndVerifySorting("variableName", "desc", Status.OK); + + inOrder.verify(mockedQuery).orderByVariableName(); + inOrder.verify(mockedQuery).desc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "asc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).asc(); + + inOrder = Mockito.inOrder(mockedQuery); + executeAndVerifySorting("tenantId", "desc", Status.OK); + inOrder.verify(mockedQuery).orderByTenantId(); + inOrder.verify(mockedQuery).desc(); + } + + @Test + public void testSecondarySortingAsPost() { + InOrder inOrder = Mockito.inOrder(mockedQuery); + Map json = new HashMap(); + json.put("sorting", OrderingBuilder.create() + .orderBy("instanceId").desc() + .orderBy("variableName").asc() + .getJson()); + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .header("accept", MediaType.APPLICATION_JSON) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + inOrder.verify(mockedQuery).orderByProcessInstanceId(); + inOrder.verify(mockedQuery).desc(); + inOrder.verify(mockedQuery).orderByVariableName(); + inOrder.verify(mockedQuery).asc(); + } + + @Test + public void testSuccessfulPagination() { + + int firstResult = 0; + int maxResults = 10; + given() + .queryParam("firstResult", firstResult) + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, maxResults); + } + + @Test + public void testMissingFirstResultParameter() { + int maxResults = 10; + given() + .queryParam("maxResults", maxResults) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(0, maxResults); + } + + @Test + public void testMissingMaxResultsParameter() { + int firstResult = 10; + given() + .queryParam("firstResult", firstResult) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).listPage(firstResult, Integer.MAX_VALUE); + } + + @Test + public void testQueryCount() { + expect() + .statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testQueryCountForPost() { + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(EMPTY_JSON_OBJECT) + .expect() + .body("count", equalTo(1)) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_COUNT_RESOURCE_URL); + + verify(mockedQuery).count(); + } + + @Test + public void testVariableNameLikeQuery() { + String variableNameLike = "aVariableNameLike"; + + given() + .queryParam("variableNameLike", variableNameLike) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).variableNameLike(variableNameLike); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testVariableNameLikeQueryIgnoreCase() { + String variableNameLike = "aVariableNameLike"; + + given() + .queryParam("variableNameLike", variableNameLike) + .queryParam("variableNamesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableNameLike(variableNameLike); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).list(); + } + + @Test + public void testHistoricVariableQueryByVariableTypeIn() { + String aVariableType = "string"; + String anotherVariableType = "integer"; + + given() + .queryParam("variableTypeIn", aVariableType + "," + anotherVariableType) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableTypeIn(aVariableType, anotherVariableType); + } + + @Test + public void testHistoricVariableQueryByVariableTypeInAsPost() { + String aVariableType = "string"; + String anotherVariableType = "integer"; + + List variableTypeIn= new ArrayList(); + variableTypeIn.add(aVariableType); + variableTypeIn.add(anotherVariableType); + + Map json = new HashMap(); + json.put("variableTypeIn", variableTypeIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableTypeIn(aVariableType, anotherVariableType); + } + + @Test + public void testSimpleHistoricVariableQuery() { + String processInstanceId = MockProvider.EXAMPLE_PROCESS_INSTANCE_ID; + + given() + .queryParam("processInstanceId", processInstanceId) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("size()", is(1)) + .body("[0].id", equalTo(mockInstanceBuilder.getId())) + .body("[0].name", equalTo(mockInstanceBuilder.getName())) + .body("[0].type", equalTo(VariableTypeHelper.toExpectedValueTypeName(mockInstanceBuilder.getTypedValue().getType()))) + .body("[0].value", equalTo(mockInstanceBuilder.getValue())) + .body("[0].processDefinitionKey", equalTo(mockInstanceBuilder.getProcessDefinitionKey())) + .body("[0].processDefinitionId", equalTo(mockInstanceBuilder.getProcessDefinitionId())) + .body("[0].processInstanceId", equalTo(mockInstanceBuilder.getProcessInstanceId())) + .body("[0].executionId", equalTo(mockInstanceBuilder.getExecutionId())) + .body("[0].errorMessage", equalTo(mockInstanceBuilder.getErrorMessage())) + .body("[0].activityInstanceId", equalTo(mockInstanceBuilder.getActivityInstanceId())) + .body("[0].caseDefinitionKey", equalTo(mockInstanceBuilder.getCaseDefinitionKey())) + .body("[0].caseDefinitionId", equalTo(mockInstanceBuilder.getCaseDefinitionId())) + .body("[0].caseInstanceId", equalTo(mockInstanceBuilder.getCaseInstanceId())) + .body("[0].caseExecutionId", equalTo(mockInstanceBuilder.getCaseExecutionId())) + .body("[0].taskId", equalTo(mockInstanceBuilder.getTaskId())) + .body("[0].tenantId", equalTo(mockInstanceBuilder.getTenantId())) + .body("[0].createTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_CREATE_TIME)) + .body("[0].removalTime", equalTo(MockProvider.EXAMPLE_HISTORIC_VARIABLE_INSTANCE_REMOVAL_TIME)) + .body("[0].rootProcessInstanceId", equalTo(mockInstanceBuilder.getRootProcessInstanceId())) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).processInstanceId(processInstanceId); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testSerializableVariableInstanceRetrieval() { + MockHistoricVariableInstanceBuilder builder = MockProvider.mockHistoricVariableInstance() + .typedValue(MockObjectValue.fromObjectValue(Variables + .objectValue("a serialized value") + .serializationDataFormat(Variables.SerializationDataFormats.JAVA) + .create()) + .objectTypeName(String.class.getName())); + + List mockInstances = new ArrayList(); + mockInstances.add(builder.build()); + + mockedQuery = setUpMockHistoricVariableInstanceQuery(mockInstances); + + given() + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("[0].type", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT))) + .body("[0].value", equalTo("a serialized value")) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, equalTo(String.class.getName())) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, equalTo(Variables.SerializationDataFormats.JAVA.getName())) + .when().get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + // should not resolve custom objects but existing API requires it +// verify(mockedQuery).disableCustomObjectDeserialization(); + verify(mockedQuery, never()).disableCustomObjectDeserialization(); + } + + @Test + public void testSpinVariableInstanceRetrieval() { + MockHistoricVariableInstanceBuilder builder = MockProvider.mockHistoricVariableInstance() + .typedValue(Variables + .serializedObjectValue("aSpinSerializedValue") + .serializationDataFormat("aDataFormat") + .objectTypeName("aRootType") + .create()); + + List mockInstances = new ArrayList(); + mockInstances.add(builder.build()); + + mockedQuery = setUpMockHistoricVariableInstanceQuery(mockInstances); + + given() + .then().expect().statusCode(Status.OK.getStatusCode()) + .and() + .body("size()", is(1)) + .body("[0].type", equalTo(VariableTypeHelper.toExpectedValueTypeName(ValueType.OBJECT))) + .body("[0].value", equalTo("aSpinSerializedValue")) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_OBJECT_TYPE_NAME, + equalTo("aRootType")) + .body("[0].valueInfo." + SerializableValueType.VALUE_INFO_SERIALIZATION_DATA_FORMAT, + equalTo("aDataFormat")) + .when().get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testAdditionalParametersExcludingVariables() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + given() + .queryParams(stringQueryParameters) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verifyStringParameterQueryInvocations(); + verify(mockedQuery).list(); + } + + private Map getCompleteStringQueryParameters() { + Map parameters = new HashMap(); + + parameters.put("processInstanceId", MockProvider.EXAMPLE_VARIABLE_INSTANCE_PROC_INST_ID); + parameters.put("variableName", MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME); + parameters.put("variableValue", MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue()); + return parameters; + } + + private void verifyStringParameterQueryInvocations() { + Map stringQueryParameters = getCompleteStringQueryParameters(); + + verify(mockedQuery).processInstanceId(stringQueryParameters.get("processInstanceId")); + verify(mockedQuery).variableName(stringQueryParameters.get("variableName")); + verify(mockedQuery).variableValueEquals(stringQueryParameters.get("variableName"), stringQueryParameters.get("variableValue")); + } + + @Test + public void testVariableNameAndValueQuery() { + String variableName = MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME; + String variableValue = MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue(); + + given() + .queryParam("variableName", variableName) + .queryParam("variableValue", variableValue) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("size()", is(1)) + .body("[0].name", equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME)) + .body("[0].value", equalTo(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + InOrder inOrder = inOrder(mockedQuery); + inOrder.verify(mockedQuery).variableValueEquals(variableName, variableValue); + inOrder.verify(mockedQuery).list(); + } + + @Test + public void testVariableNameAndValueIgnoreCaseQuery() { + String variableName = MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME; + String variableValue = MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue(); + + given() + .queryParam("variableName", variableName) + .queryParam("variableNamesIgnoreCase", true) + .queryParam("variableValue", variableValue) + .queryParam("variableValuesIgnoreCase", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .and() + .body("size()", is(1)) + .body("[0].name", equalTo(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME)) + .body("[0].value", equalTo(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableValueEquals(variableName, variableValue); + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).list(); + } + + @Test + public void testVariableValueQuery_BadRequest() { + given() + .queryParam("variableValue", MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE) + .then() + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("Only a single variable value parameter specified: variable name and value are required to be able to query after a specific variable value.")) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + } + + @Test + public void testHistoricVariableQueryByExecutionIdsAndTaskIds() { + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + String aTaskId = "aTaskId"; + String anotherTaskId = "anotherTaskId"; + + given() + .queryParam("executionIdIn", anExecutionId + "," + anotherExecutionId) + .queryParam("taskIdIn", aTaskId + "," + anotherTaskId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).taskIdIn(aTaskId, anotherTaskId); + } + + @Test + public void testHistoricVariableQueryByExecutionIdsAndTaskIdsAsPost() { + String anExecutionId = "anExecutionId"; + String anotherExecutionId = "anotherExecutionId"; + + List executionIdIn= new ArrayList(); + executionIdIn.add(anExecutionId); + executionIdIn.add(anotherExecutionId); + + String aTaskId = "aTaskId"; + String anotherTaskId = "anotherTaskId"; + + List taskIdIn= new ArrayList(); + taskIdIn.add(aTaskId); + taskIdIn.add(anotherTaskId); + + Map json = new HashMap(); + json.put("executionIdIn", executionIdIn); + json.put("taskIdIn", taskIdIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).executionIdIn(anExecutionId, anotherExecutionId); + verify(mockedQuery).taskIdIn(aTaskId, anotherTaskId); + } + + @Test + public void testHistoricVariableQueryByProcessInstanceIdIn () { + String aProcessInstanceId = "aProcessInstanceId"; + String anotherProcessInstanceId = "anotherProcessInstanceId"; + + given() + .queryParam("processInstanceIdIn", aProcessInstanceId + "," + anotherProcessInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceIdIn(aProcessInstanceId, anotherProcessInstanceId); + } + + @Test + public void testHistoricVariableQueryByProcessInstanceIdInAsPOST() { + String aProcessInstanceId = "aProcessInstanceId"; + String anotherProcessInstanceId = "anotherProcessInstanceId"; + + List processInstanceIdIn= new ArrayList(); + processInstanceIdIn.add(aProcessInstanceId); + processInstanceIdIn.add(anotherProcessInstanceId); + processInstanceIdIn.add(null); + + Map json = new HashMap(); + json.put("processInstanceIdIn", processInstanceIdIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processInstanceIdIn(aProcessInstanceId, anotherProcessInstanceId,null); + } + + @Test + public void testHistoricVariableQueryByActivityInstanceIds() { + String anActivityInstanceId = "anActivityInstanceId"; + String anotherActivityInstanceId = "anotherActivityInstanceId"; + + given() + .queryParam("activityInstanceIdIn", anActivityInstanceId + "," + anotherActivityInstanceId) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityInstanceIdIn(anActivityInstanceId, anotherActivityInstanceId); + } + + @Test + public void testHistoricVariableQueryByActivityInstanceIdsAsPost() { + String anActivityInstanceId = "anActivityInstanceId"; + String anotherActivityInstanceId = "anotherActivityInstanceId"; + + List activityInstanceIdIn= new ArrayList(); + activityInstanceIdIn.add(anActivityInstanceId); + activityInstanceIdIn.add(anotherActivityInstanceId); + + Map json = new HashMap(); + json.put("activityInstanceIdIn", activityInstanceIdIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).activityInstanceIdIn(anActivityInstanceId, anotherActivityInstanceId); + } + + @Test + public void testHistoricVariableQueryByCaseInstanceId() { + + given() + .queryParam("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseInstanceId(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + } + + @Test + public void testHistoricVariableQueryByCaseInstanceIdAsPost() { + Map json = new HashMap(); + json.put("caseInstanceId", MockProvider.EXAMPLE_CASE_INSTANCE_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseInstanceId(MockProvider.EXAMPLE_CASE_INSTANCE_ID); + } + + @Test + public void testHistoricVariableQueryByCaseExecutionIds() { + + String caseExecutionIds = MockProvider.EXAMPLE_CASE_EXECUTION_ID + "," + MockProvider.ANOTHER_EXAMPLE_CASE_EXECUTION_ID; + + given() + .queryParam("caseExecutionIdIn", caseExecutionIds) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseExecutionIdIn(MockProvider.EXAMPLE_CASE_EXECUTION_ID, MockProvider.ANOTHER_EXAMPLE_CASE_EXECUTION_ID); + } + + @Test + public void testHistoricVariableQueryByCaseExecutionIdsAsPost() { + Map json = new HashMap(); + json.put("caseExecutionIdIn", Arrays.asList(MockProvider.EXAMPLE_CASE_EXECUTION_ID, MockProvider.ANOTHER_EXAMPLE_CASE_EXECUTION_ID)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseExecutionIdIn(MockProvider.EXAMPLE_CASE_EXECUTION_ID, MockProvider.ANOTHER_EXAMPLE_CASE_EXECUTION_ID); + } + + @Test + public void testTenantIdListParameter() { + mockedQuery = setUpMockHistoricVariableInstanceQuery(createMockHistoricVariableInstancesTwoTenants()); + + Response response = given() + .queryParam("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testTenantIdListPostParameter() { + mockedQuery = setUpMockHistoricVariableInstanceQuery(createMockHistoricVariableInstancesTwoTenants()); + + Map queryParameters = new HashMap(); + queryParameters.put("tenantIdIn", MockProvider.EXAMPLE_TENANT_ID_LIST.split(",")); + + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).tenantIdIn(MockProvider.EXAMPLE_TENANT_ID, MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + verify(mockedQuery).list(); + + String content = response.asString(); + List executions = from(content).getList(""); + assertThat(executions).hasSize(2); + + String returnedTenantId1 = from(content).getString("[0].tenantId"); + String returnedTenantId2 = from(content).getString("[1].tenantId"); + + assertThat(returnedTenantId1).isEqualTo(MockProvider.EXAMPLE_TENANT_ID); + assertThat(returnedTenantId2).isEqualTo(MockProvider.ANOTHER_EXAMPLE_TENANT_ID); + } + + @Test + public void testQueryFilterWithoutTenantIdParameter() { + // given + HistoricVariableInstance historicVariableInstance = MockProvider + .mockHistoricVariableInstance(null) + .build(); + mockedQuery = setUpMockHistoricVariableInstanceQuery(Collections.singletonList(historicVariableInstance)); + + // when + Response response = given() + .queryParam("withoutTenantId", true) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testQueryFilterWithoutTenantIdPostParameter() { + // given + HistoricVariableInstance historicVariableInstance = MockProvider + .mockHistoricVariableInstance(null) + .build(); + mockedQuery = setUpMockHistoricVariableInstanceQuery(Collections.singletonList(historicVariableInstance)); + Map queryParameters = Collections.singletonMap("withoutTenantId", (Object) true); + + // when + Response response = given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(queryParameters) + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + // then + verify(mockedQuery).withoutTenantId(); + verify(mockedQuery).list(); + + String content = response.asString(); + List definitions = from(content).getList(""); + assertThat(definitions).hasSize(1); + + String returnedTenantId = from(content).getString("[0].tenantId"); + assertThat(returnedTenantId).isEqualTo(null); + } + + @Test + public void testHistoricVariableQueryByCaseActivityIds() { + + String caseExecutionIds = MockProvider.EXAMPLE_CASE_ACTIVITY_ID + "," + MockProvider.ANOTHER_EXAMPLE_CASE_ACTIVITY_ID; + + given() + .queryParam("caseActivityIdIn", caseExecutionIds) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseActivityIdIn(MockProvider.EXAMPLE_CASE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_CASE_ACTIVITY_ID); + } + + @Test + public void testHistoricVariableQueryByCaseActivityIdsAsPost() { + Map json = new HashMap(); + json.put("caseActivityIdIn", Arrays.asList(MockProvider.EXAMPLE_CASE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_CASE_ACTIVITY_ID)); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).caseActivityIdIn(MockProvider.EXAMPLE_CASE_ACTIVITY_ID, MockProvider.ANOTHER_EXAMPLE_CASE_ACTIVITY_ID); + } + + @Test + public void testIncludeDeletedVariables() { + when(mockedQuery.includeDeleted()).thenReturn(mockedQuery); + + given() + .queryParam("includeDeleted", true) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).includeDeleted(); + } + + @Test + public void testHistoricVariableQueryByProcessDefinitionIdAsPost() { + when(mockedQuery.processDefinitionId(anyString())).thenReturn(mockedQuery); + Map json = new HashMap(); + json.put("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testHistoricVariableQueryByProcessDefinitionId() { + when(mockedQuery.processDefinitionId(anyString())).thenReturn(mockedQuery); + + given() + .queryParam("processDefinitionId", MockProvider.EXAMPLE_PROCESS_DEFINITION_ID) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionId(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID); + } + + @Test + public void testHistoricVariableQueryByProcessDefinitionKeyAsPost() { + when(mockedQuery.processDefinitionKey(anyString())).thenReturn(mockedQuery); + Map json = new HashMap(); + json.put("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + } + + @Test + public void testHistoricVariableQueryByProcessDefinitionKey() { + when(mockedQuery.processDefinitionKey(anyString())).thenReturn(mockedQuery); + + given() + .queryParam("processDefinitionKey", MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).processDefinitionKey(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY); + } + + private List createMockHistoricVariableInstancesTwoTenants() { + return Arrays.asList( + MockProvider.mockHistoricVariableInstance(MockProvider.EXAMPLE_TENANT_ID).build(), + MockProvider.mockHistoricVariableInstance(MockProvider.ANOTHER_EXAMPLE_TENANT_ID).build()); + } + + @Test + public void testHistoricVariableQueryByVariableNameAndValueIgnoreCaseAsPost() { + when(mockedQuery.processDefinitionKey(anyString())).thenReturn(mockedQuery); + Map json = new HashMap(); + json.put("variableName", "aVariableName"); + json.put("variableValue", "aVariableValue"); + json.put("variableNamesIgnoreCase", true); + json.put("variableValuesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).matchVariableValuesIgnoreCase(); + verify(mockedQuery).variableName("aVariableName"); + verify(mockedQuery).variableValueEquals("aVariableName", "aVariableValue"); + } + + @Test + public void testHistoricVariableQueryByVariableNameLikeIgnoreCaseAsPost() { + when(mockedQuery.processDefinitionKey(anyString())).thenReturn(mockedQuery); + Map json = new HashMap(); + json.put("variableNameLike", "aVariableName"); + json.put("variableNamesIgnoreCase", true); + + given() + .contentType(POST_JSON_CONTENT_TYPE) + .body(json) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).matchVariableNamesIgnoreCase(); + verify(mockedQuery).variableNameLike("aVariableName"); + } + + @Test + public void shouldQueryByVariableNameInAsGet() { + String aVariableName = "aVariableName"; + String anotherVariableName = "anotherVariableName"; + + given() + .queryParam("variableNameIn", aVariableName + "," + anotherVariableName) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableNameIn(aVariableName, anotherVariableName); + } + + @Test + public void shouldQueryByVariableNameInAsPost() { + String aVariableName = "aVariableName"; + String anotherVariableName = "anotherVariableName"; + + List variableNameIn = new ArrayList<>(); + variableNameIn.add(aVariableName); + variableNameIn.add(anotherVariableName); + + Map json = new HashMap<>(); + json.put("variableNameIn", variableNameIn); + + given().contentType(POST_JSON_CONTENT_TYPE).body(json) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORIC_VARIABLE_INSTANCE_RESOURCE_URL); + + verify(mockedQuery).variableNameIn(aVariableName, anotherVariableName); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoryCleanupRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoryCleanupRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b2b00d217e95cf2cba0910744cac79f2dfdfa46a --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/HistoryCleanupRestServiceInteractionTest.java @@ -0,0 +1,262 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl; +import org.camunda.bpm.engine.impl.jobexecutor.historycleanup.BatchWindowManager; +import org.camunda.bpm.engine.impl.jobexecutor.historycleanup.DefaultBatchWindowManager; +import org.camunda.bpm.engine.impl.jobexecutor.historycleanup.HistoryCleanupHelper; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.mapper.JacksonConfigurator; +import org.camunda.bpm.engine.rest.util.DateTimeUtils; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.runtime.Job; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import io.restassured.http.ContentType; +import static io.restassured.RestAssured.given; +import static org.mockito.Mockito.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.equalTo; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +public class HistoryCleanupRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String HISTORY_CLEANUP_URL = TEST_RESOURCE_ROOT_PATH + "/history/cleanup"; + protected static final String FIND_HISTORY_CLEANUP_JOB_URL = HISTORY_CLEANUP_URL + "/job"; + protected static final String FIND_HISTORY_CLEANUP_JOBS_URL = HISTORY_CLEANUP_URL + "/jobs"; + protected static final String CONFIGURATION_URL = HISTORY_CLEANUP_URL + "/configuration"; + + private HistoryService historyServiceMock; + + @Before + public void setUpRuntimeData() { + historyServiceMock = mock(HistoryService.class); + Job mockJob = MockProvider.createMockJob(); + List mockJobs = MockProvider.createMockJobs(); + when(historyServiceMock.cleanUpHistoryAsync(anyBoolean())) + .thenReturn(mockJob); + when(historyServiceMock.findHistoryCleanupJob()) + .thenReturn(mockJob); + when(historyServiceMock.findHistoryCleanupJobs()) + .thenReturn(mockJobs); + + // runtime service + when(processEngine.getHistoryService()).thenReturn(historyServiceMock); + } + + @Test + public void testFindHistoryCleanupJob() { + given().contentType(ContentType.JSON) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(FIND_HISTORY_CLEANUP_JOB_URL); + + verify(historyServiceMock).findHistoryCleanupJob(); + } + + @Test + public void testFindNoHistoryCleanupJob() { + when(historyServiceMock.findHistoryCleanupJob()) + .thenReturn(null); + + given().contentType(ContentType.JSON) + .then() + .expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .when().get(FIND_HISTORY_CLEANUP_JOB_URL); + + verify(historyServiceMock).findHistoryCleanupJob(); + } + + @Test + public void testFindHistoryCleanupJobs() { + given().contentType(ContentType.JSON) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(FIND_HISTORY_CLEANUP_JOBS_URL); + + verify(historyServiceMock).findHistoryCleanupJobs(); + } + + @Test + public void testFindNoHistoryCleanupJobs() { + when(historyServiceMock.findHistoryCleanupJobs()) + .thenReturn(null); + + given().contentType(ContentType.JSON) + .then() + .expect().statusCode(Status.NOT_FOUND.getStatusCode()) + .when().get(FIND_HISTORY_CLEANUP_JOBS_URL); + + verify(historyServiceMock).findHistoryCleanupJobs(); + } + + @Test + public void testHistoryCleanupImmediatelyDueDefault() { + given().contentType(ContentType.JSON) + .then() + .expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORY_CLEANUP_URL); + + verify(historyServiceMock).cleanUpHistoryAsync(true); + } + + @Test + public void testHistoryCleanupImmediatelyDue() { + given().contentType(ContentType.JSON) + .queryParam("immediatelyDue", true) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORY_CLEANUP_URL); + + verify(historyServiceMock).cleanUpHistoryAsync(true); + } + + @Test + public void testHistoryCleanup() { + given().contentType(ContentType.JSON).queryParam("immediatelyDue", false) + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().post(HISTORY_CLEANUP_URL); + + verify(historyServiceMock).cleanUpHistoryAsync(false); + } + + @Test + public void testHistoryConfigurationOutsideBatchWindow() throws ParseException { + ProcessEngineConfigurationImpl processEngineConfigurationImplMock = mock(ProcessEngineConfigurationImpl.class); + Date startDate = HistoryCleanupHelper.parseTimeConfiguration("23:59"); + Date endDate = HistoryCleanupHelper.parseTimeConfiguration("00:00"); + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationImplMock); + when(processEngineConfigurationImplMock.getHistoryCleanupBatchWindowStartTime()).thenReturn("23:59"); + when(processEngineConfigurationImplMock.getHistoryCleanupBatchWindowEndTime()).thenReturn("00:00"); + when(processEngineConfigurationImplMock.getBatchWindowManager()).thenReturn(new DefaultBatchWindowManager()); + when(processEngineConfigurationImplMock.isHistoryCleanupEnabled()).thenReturn(true); + + SimpleDateFormat sdf = new SimpleDateFormat(JacksonConfigurator.dateFormatString); + Date now = sdf.parse("2017-09-01T22:00:00.000+0000"); + + ClockUtil.setCurrentTime(now); + Calendar today = Calendar.getInstance(); + today.setTime(now); + Calendar tomorrow = Calendar.getInstance(); + tomorrow.setTime(DateTimeUtils.addDays(now, 1)); + + Date dateToday = DateTimeUtils.updateTime(today.getTime(), startDate); + Date dateTomorrow = DateTimeUtils.updateTime(tomorrow.getTime(), endDate); + + given() + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("batchWindowStartTime", containsString(sdf.format(dateToday))) + .body("batchWindowEndTime", containsString(sdf.format(dateTomorrow))) + .body("enabled", equalTo(true)) + .when() + .get(CONFIGURATION_URL); + + } + + @Test + public void testHistoryConfigurationWithinBatchWindow() throws ParseException { + ProcessEngineConfigurationImpl processEngineConfigurationImplMock = mock(ProcessEngineConfigurationImpl.class); + Date startDate = HistoryCleanupHelper.parseTimeConfiguration("22:00+0200"); + Date endDate = HistoryCleanupHelper.parseTimeConfiguration("23:00+0200"); + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationImplMock); + when(processEngineConfigurationImplMock.getHistoryCleanupBatchWindowStartTime()).thenReturn("22:00+0200"); + when(processEngineConfigurationImplMock.getHistoryCleanupBatchWindowEndTime()).thenReturn("23:00+0200"); + when(processEngineConfigurationImplMock.getBatchWindowManager()).thenReturn(new DefaultBatchWindowManager()); + when(processEngineConfigurationImplMock.isHistoryCleanupEnabled()).thenReturn(true); + + SimpleDateFormat sdf = new SimpleDateFormat(JacksonConfigurator.dateFormatString); + Date now = sdf.parse("2017-09-01T22:00:00.000+0200"); + ClockUtil.setCurrentTime(now); + + Calendar today = Calendar.getInstance(); + today.setTime(now); + + Date dateToday = DateTimeUtils.updateTime(today.getTime(), startDate); + Date dateTomorrow = DateTimeUtils.updateTime(today.getTime(), endDate); + + given() + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("batchWindowStartTime", containsString(sdf.format(dateToday))) + .body("batchWindowEndTime", containsString(sdf.format(dateTomorrow))) + .body("enabled", equalTo(true)) + .when() + .get(CONFIGURATION_URL); + + } + + @Test + public void testHistoryConfigurationWhenBatchNotDefined() { + ProcessEngineConfigurationImpl processEngineConfigurationImplMock = mock(ProcessEngineConfigurationImpl.class); + when(processEngine.getProcessEngineConfiguration()).thenReturn(processEngineConfigurationImplMock); + when(processEngineConfigurationImplMock.getHistoryCleanupBatchWindowStartTime()).thenReturn(null); + when(processEngineConfigurationImplMock.getHistoryCleanupBatchWindowEndTime()).thenReturn(null); + when(processEngineConfigurationImplMock.isHistoryCleanupEnabled()).thenReturn(true); + when(processEngineConfigurationImplMock.getBatchWindowManager()).thenReturn(new DefaultBatchWindowManager()); + + given() + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("batchWindowStartTime", equalTo(null)) + .body("batchWindowEndTime", equalTo(null)) + .body("enabled", equalTo(true)) + .when() + .get(CONFIGURATION_URL); + + } + + @Test + public void shouldReturnEnabledFalse() { + ProcessEngineConfigurationImpl engineConfigMock = mock(ProcessEngineConfigurationImpl.class); + when(processEngine.getProcessEngineConfiguration()).thenReturn(engineConfigMock); + + BatchWindowManager batchWindowManager = mock(BatchWindowManager.class); + when(engineConfigMock.getBatchWindowManager()).thenReturn(batchWindowManager); + when(engineConfigMock.isHistoryCleanupEnabled()).thenReturn(false); + + given() + .contentType(ContentType.JSON) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("batchWindowStartTime", equalTo(null)) + .body("batchWindowEndTime", equalTo(null)) + .body("enabled", equalTo(false)) + .when() + .get(CONFIGURATION_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/UserOperationLogRestServiceQueryTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/UserOperationLogRestServiceQueryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..67fd28942732e6f32c8ad8271889e8d8c7f43777 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/history/UserOperationLogRestServiceQueryTest.java @@ -0,0 +1,349 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.history; + +import static io.restassured.RestAssured.expect; +import static io.restassured.RestAssured.given; +import static io.restassured.path.json.JsonPath.from; +import static org.camunda.bpm.engine.history.UserOperationLogEntry.OPERATION_TYPE_CLAIM; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_USER_OPERATION_ANNOTATION; +import static org.camunda.bpm.engine.rest.helper.MockProvider.EXAMPLE_USER_OPERATION_LOG_ID; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Date; +import java.util.List; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.BadUserRequestException; +import org.camunda.bpm.engine.EntityTypes; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.exception.NotValidException; +import org.camunda.bpm.engine.history.UserOperationLogEntry; +import org.camunda.bpm.engine.history.UserOperationLogQuery; +import org.camunda.bpm.engine.impl.calendar.DateTimeUtil; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.history.UserOperationLogEntryDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +import io.restassured.http.ContentType; +import io.restassured.response.Response; + +/** + * @author Danny Gräf + */ +public class UserOperationLogRestServiceQueryTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String USER_OPERATION_LOG_RESOURCE_URL = TEST_RESOURCE_ROOT_PATH + "/history/user-operation"; + + protected static final String USER_OPERATION_LOG_COUNT_RESOURCE_URL = USER_OPERATION_LOG_RESOURCE_URL + "/count"; + + protected static final String USER_OPERATION_LOG_ANNOTATION = USER_OPERATION_LOG_RESOURCE_URL + "/{operationId}"; + + protected static final String USER_OPERATION_LOG_SET_ANNOTATION_RESOURCE_URL = + USER_OPERATION_LOG_ANNOTATION + "/set-annotation"; + + protected static final String USER_OPERATION_LOG_CLEAR_ANNOTATION_RESOURCE_URL = + USER_OPERATION_LOG_ANNOTATION + "/clear-annotation"; + + protected UserOperationLogQuery queryMock; + + protected HistoryService historyService; + + @Before + public void setUpMock() { + List entries = MockProvider.createUserOperationLogEntries(); + queryMock = mock(UserOperationLogQuery.class); + when(queryMock.list()).thenReturn(entries); + when(queryMock.listPage(anyInt(), anyInt())).thenReturn(entries); + when(queryMock.count()).thenReturn((long) entries.size()); + + historyService = mock(HistoryService.class); + when(processEngine.getHistoryService()).thenReturn(historyService); + when(historyService.createUserOperationLogQuery()).thenReturn(queryMock); + } + + @Test + public void testQueryCount() { + expect().statusCode(Status.OK.getStatusCode()) + .body("count", equalTo(1)) + .when().get(USER_OPERATION_LOG_COUNT_RESOURCE_URL); + + verify(queryMock).count(); + } + + @Test + public void testEmptyQuery() { + expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + + verify(queryMock, never()).deploymentId(anyString()); + verify(queryMock, never()).processDefinitionId(anyString()); + verify(queryMock, never()).processDefinitionKey(anyString()); + verify(queryMock, never()).processInstanceId(anyString()); + verify(queryMock, never()).executionId(anyString()); + verify(queryMock, never()).caseDefinitionId(anyString()); + verify(queryMock, never()).caseInstanceId(anyString()); + verify(queryMock, never()).caseExecutionId(anyString()); + verify(queryMock, never()).taskId(anyString()); + verify(queryMock, never()).jobId(anyString()); + verify(queryMock, never()).jobDefinitionId(anyString()); + verify(queryMock, never()).batchId(anyString()); + verify(queryMock, never()).userId(anyString()); + verify(queryMock, never()).operationId(anyString()); + verify(queryMock, never()).externalTaskId(anyString()); + verify(queryMock, never()).operationType(anyString()); + verify(queryMock, never()).entityType(anyString()); + verify(queryMock, never()).category(anyString()); + verify(queryMock, never()).property(anyString()); + verify(queryMock, never()).afterTimestamp(any(Date.class)); + verify(queryMock, never()).beforeTimestamp(any(Date.class)); + verify(queryMock, never()).orderByTimestamp(); + verify(queryMock, never()).asc(); + verify(queryMock, never()).desc(); + verify(queryMock).list(); + } + + @Test + public void testQueryParameter() { + Response response = given() + .queryParam("deploymentId", "a-deployment-id") + .queryParam("processDefinitionId", "1") + .queryParam("processDefinitionKey", "6") + .queryParam("processInstanceId", "2") + .queryParam("executionId", "3") + .queryParam("caseDefinitionId", "x") + .queryParam("caseInstanceId", "y") + .queryParam("caseExecutionId", "z") + .queryParam("taskId", "4") + .queryParam("jobId", "7") + .queryParam("jobDefinitionId", "8") + .queryParam("batchId", MockProvider.EXAMPLE_BATCH_ID) + .queryParam("userId", "icke") + .queryParam("operationId", "5") + .queryParam("externalTaskId", "1") + .queryParam("operationType", OPERATION_TYPE_CLAIM) + .queryParam("entityType", EntityTypes.TASK) + .queryParam("entityTypeIn", EntityTypes.TASK + "," + EntityTypes.VARIABLE) + .queryParam("category", UserOperationLogEntry.CATEGORY_TASK_WORKER) + .queryParam("categoryIn", UserOperationLogEntry.CATEGORY_TASK_WORKER + "," + UserOperationLogEntry.CATEGORY_OPERATOR) + .queryParam("property", "owner") + .then().expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + + verify(queryMock).deploymentId("a-deployment-id"); + verify(queryMock).processDefinitionId("1"); + verify(queryMock).processDefinitionKey("6"); + verify(queryMock).processInstanceId("2"); + verify(queryMock).executionId("3"); + verify(queryMock).caseDefinitionId("x"); + verify(queryMock).caseInstanceId("y"); + verify(queryMock).caseExecutionId("z"); + verify(queryMock).taskId("4"); + verify(queryMock).jobId("7"); + verify(queryMock).jobDefinitionId("8"); + verify(queryMock).batchId(MockProvider.EXAMPLE_BATCH_ID); + verify(queryMock).userId("icke"); + verify(queryMock).operationId("5"); + verify(queryMock).externalTaskId("1"); + verify(queryMock).operationType(OPERATION_TYPE_CLAIM); + verify(queryMock).entityType(EntityTypes.TASK); + verify(queryMock).entityTypeIn(EntityTypes.TASK, EntityTypes.VARIABLE); + verify(queryMock).category(UserOperationLogEntry.CATEGORY_TASK_WORKER); + verify(queryMock).categoryIn(UserOperationLogEntry.CATEGORY_TASK_WORKER, UserOperationLogEntry.CATEGORY_OPERATOR); + verify(queryMock).property("owner"); + verify(queryMock).list(); + + String json = response.asString(); + UserOperationLogEntryDto actual = from(json).getObject("[0]", UserOperationLogEntryDto.class); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_LOG_ID, actual.getId()); + assertEquals(MockProvider.EXAMPLE_DEPLOYMENT_ID, actual.getDeploymentId()); + assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID, actual.getProcessDefinitionId()); + assertEquals(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY, actual.getProcessDefinitionKey()); + assertEquals(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID, actual.getProcessInstanceId()); + assertEquals(MockProvider.EXAMPLE_EXECUTION_ID, actual.getExecutionId()); + assertEquals(MockProvider.EXAMPLE_CASE_DEFINITION_ID, actual.getCaseDefinitionId()); + assertEquals(MockProvider.EXAMPLE_CASE_INSTANCE_ID, actual.getCaseInstanceId()); + assertEquals(MockProvider.EXAMPLE_CASE_EXECUTION_ID, actual.getCaseExecutionId()); + assertEquals(MockProvider.EXAMPLE_TASK_ID, actual.getTaskId()); + assertEquals(MockProvider.EXAMPLE_JOB_ID, actual.getJobId()); + assertEquals(MockProvider.EXAMPLE_JOB_DEFINITION_ID, actual.getJobDefinitionId()); + assertEquals(MockProvider.EXAMPLE_BATCH_ID, actual.getBatchId()); + assertEquals(MockProvider.EXAMPLE_USER_ID, actual.getUserId()); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_TIMESTAMP, from(json).getString("[0].timestamp")); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_ID, actual.getOperationId()); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_TYPE, actual.getOperationType()); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_ENTITY, actual.getEntityType()); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_PROPERTY, actual.getProperty()); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_ORG_VALUE, actual.getOrgValue()); + assertEquals(MockProvider.EXAMPLE_USER_OPERATION_NEW_VALUE, actual.getNewValue()); + } + + @Test + public void testQueryAfterTimestamp() { + given().queryParam("afterTimestamp", MockProvider.EXAMPLE_USER_OPERATION_TIMESTAMP) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + verify(queryMock).afterTimestamp(DateTimeUtil.parseDate(MockProvider.EXAMPLE_USER_OPERATION_TIMESTAMP)); + } + + @Test + public void testQueryBeforeTimestamp() { + given().queryParam("beforeTimestamp", MockProvider.EXAMPLE_USER_OPERATION_TIMESTAMP) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + verify(queryMock).beforeTimestamp(DateTimeUtil.parseDate(MockProvider.EXAMPLE_USER_OPERATION_TIMESTAMP)); + } + + @Test + public void testSortByTimestampAscending() { + given() + .queryParam("sortBy", "timestamp") + .queryParam("sortOrder", "asc") + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + verify(queryMock).orderByTimestamp(); + verify(queryMock).asc(); + verify(queryMock, never()).desc(); + } + + @Test + public void testSortByTimestampDescending() { + given() + .queryParam("sortBy", "timestamp") + .queryParam("sortOrder", "desc") + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + verify(queryMock).orderByTimestamp(); + verify(queryMock).desc(); + verify(queryMock, never()).asc(); + } + + @Test + public void testInvalidSortByParameter() { + given() + .queryParam("sortBy", "unknownField") + .queryParam("sortOrder", "desc") + .expect().statusCode(Status.BAD_REQUEST.getStatusCode()) + .contentType(ContentType.JSON) + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + } + + @Test + public void testPagination() { + given() + .queryParam("firstResult", 7) + .queryParam("maxResults", 13) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + verify(queryMock).listPage(7, 13); + } + + @Test + public void testFirstResultMissing() { + given().queryParam("maxResults", 13) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + verify(queryMock).listPage(0, 13); + } + + @Test + public void testMaxResultsMissing() { + given().queryParam("firstResult", 7) + .expect().statusCode(Status.OK.getStatusCode()) + .when().get(USER_OPERATION_LOG_RESOURCE_URL); + verify(queryMock).listPage(7, Integer.MAX_VALUE); + } + + @Test + public void shouldSetAnnotation() { + given() + .pathParam("operationId", EXAMPLE_USER_OPERATION_LOG_ID) + .contentType(MediaType.APPLICATION_JSON) + .body("{ \"annotation\": \"" + EXAMPLE_USER_OPERATION_ANNOTATION + "\" }") + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(USER_OPERATION_LOG_SET_ANNOTATION_RESOURCE_URL); + + verify(historyService) + .setAnnotationForOperationLogById(EXAMPLE_USER_OPERATION_LOG_ID, EXAMPLE_USER_OPERATION_ANNOTATION); + } + + @Test + public void shouldThrowExceptionWhenSetAnnotation() { + doThrow(NotValidException.class) + .when(historyService) + .setAnnotationForOperationLogById(anyString(), anyString()); + + given() + .pathParam("operationId", EXAMPLE_USER_OPERATION_LOG_ID) + .contentType(MediaType.APPLICATION_JSON) + .body("{ \"annotation\": \"" + EXAMPLE_USER_OPERATION_ANNOTATION + "\" }") + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(USER_OPERATION_LOG_SET_ANNOTATION_RESOURCE_URL); + } + + @Test + public void shouldClearAnnotation() { + given() + .pathParam("operationId", EXAMPLE_USER_OPERATION_LOG_ID) + .expect() + .statusCode(Status.NO_CONTENT.getStatusCode()) + .when() + .put(USER_OPERATION_LOG_CLEAR_ANNOTATION_RESOURCE_URL); + + verify(historyService) + .clearAnnotationForOperationLogById(EXAMPLE_USER_OPERATION_LOG_ID); + } + + @Test + public void shouldThrowExceptionWhenClearAnnotation() { + doThrow(BadUserRequestException.class) + .when(historyService) + .clearAnnotationForOperationLogById(anyString()); + + Response response = given() + .pathParam("operationId", EXAMPLE_USER_OPERATION_LOG_ID) + .expect() + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .put(USER_OPERATION_LOG_CLEAR_ANNOTATION_RESOURCE_URL); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/impl/FetchAndLockHandlerTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/impl/FetchAndLockHandlerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..365b8560e1851dec22926a2b2ff0f08076c19863 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/impl/FetchAndLockHandlerTest.java @@ -0,0 +1,525 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import static org.camunda.bpm.engine.rest.impl.FetchAndLockHandlerImpl.BLOCKING_QUEUE_CAPACITY_PARAM_NAME; +import static org.camunda.bpm.engine.rest.impl.FetchAndLockHandlerImpl.DEFAULT_BLOCKING_QUEUE_CAPACITY; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.hamcrest.MockitoHamcrest.argThat; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.ws.rs.container.AsyncResponse; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngine; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.externaltask.ExternalTaskQueryTopicBuilder; +import org.camunda.bpm.engine.externaltask.FetchAndLockBuilder; +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.impl.util.ClockUtil; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.exception.RestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.hamcrest.collection.IsCollectionWithSize; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +/** + * @author Tassilo Weidner + */ +@RunWith(MockitoJUnitRunner.class) +public class FetchAndLockHandlerTest { + + @Mock + protected ProcessEngine processEngine; + + @Mock + protected IdentityService identityService; + + @Mock + protected ExternalTaskService externalTaskService; + + @Mock + protected ExternalTaskQueryTopicBuilder externalTaskQueryTopicBuilder; + + @Mock + protected FetchAndLockBuilder fetchAndLockBuilder; + + @Mock + private ServletContext servletContext; + + @Mock + private ServletContextEvent servletContextEvent; + + @Spy + protected FetchAndLockHandlerImpl handler; + + protected LockedExternalTask lockedExternalTaskMock; + + protected static final Date START_DATE = new Date(1457326800000L); + + @Before + public void initMocks() { + when(fetchAndLockBuilder.workerId(anyString())).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.maxTasks(anyInt())).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.usePriority(anyBoolean())).thenReturn(fetchAndLockBuilder); + + when(processEngine.getIdentityService()).thenReturn(identityService); + when(processEngine.getExternalTaskService()).thenReturn(externalTaskService); + when(processEngine.getName()).thenReturn("default"); + + when(externalTaskService.fetchAndLock()).thenReturn(fetchAndLockBuilder); + + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + + when(externalTaskQueryTopicBuilder.topic(any(String.class), anyLong())).thenReturn(externalTaskQueryTopicBuilder); + + doNothing().when(handler).suspend(anyLong()); + doReturn(processEngine).when(handler).getProcessEngine(any(FetchAndLockRequest.class)); + + lockedExternalTaskMock = MockProvider.createMockLockedExternalTask(); + + when(servletContextEvent.getServletContext()).thenReturn(servletContext); + handler.contextInitialized(servletContextEvent); + } + + @Before + public void setClock() { + ClockUtil.setCurrentTime(START_DATE); + } + + @After + public void resetClock() { + ClockUtil.reset(); + } + + @After + public void resetUniqueWorkerRequestParam() { + handler.parseUniqueWorkerRequestParam("false"); + } + + @Test + public void shouldResumeAsyncResponseDueToAvailableTasks() { + // given + List tasks = new ArrayList(); + tasks.add(lockedExternalTaskMock); + + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + when(externalTaskQueryTopicBuilder.execute()).thenReturn(tasks); + + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + + // when + handler.acquire(); + + // then + verify(asyncResponse).resume(argThat(IsCollectionWithSize.hasSize(1))); + assertThat(handler.getPendingRequests().size(), is(0)); + verify(handler).suspend(Long.MAX_VALUE); + } + + @Test + public void shouldNotResumeAsyncResponseDueToNoAvailableTasks() { + // given + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + when(externalTaskQueryTopicBuilder.execute()).thenReturn(Collections.emptyList()); + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + + // when + handler.acquire(); + + // then + verify(asyncResponse, never()).resume(any()); + assertThat(handler.getPendingRequests().size(), is(1)); + verify(handler).suspend(5000L); + } + + @Test + public void shouldResumeAsyncResponseDueToTimeoutExpired_1() { + // given + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + when(externalTaskQueryTopicBuilder.execute()).thenReturn(Collections.emptyList()); + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + handler.acquire(); + + // assume + assertThat(handler.getPendingRequests().size(), is(1)); + verify(handler).suspend(5000L); + + List tasks = new ArrayList(); + tasks.add(lockedExternalTaskMock); + + when(externalTaskQueryTopicBuilder.execute()).thenReturn(tasks); + + addSecondsToClock(5); + + // when + handler.acquire(); + + // then + verify(asyncResponse).resume(argThat(IsCollectionWithSize.hasSize(1))); + assertThat(handler.getPendingRequests().size(), is(0)); + verify(handler).suspend(Long.MAX_VALUE); + } + + @Test + public void shouldResumeAsyncResponseDueToTimeoutExpired_2() { + // given + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + when(externalTaskQueryTopicBuilder.execute()).thenReturn(Collections.emptyList()); + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + + addSecondsToClock(1); + handler.acquire(); + + // assume + assertThat(handler.getPendingRequests().size(), is(1)); + verify(handler).suspend(4000L); + + addSecondsToClock(4); + + // when + handler.acquire(); + + // then + verify(asyncResponse).resume(argThat(IsCollectionWithSize.hasSize(0))); + assertThat(handler.getPendingRequests().size(), is(0)); + verify(handler).suspend(Long.MAX_VALUE); + } + + @Test + public void shouldResumeAsyncResponseDueToTimeoutExpired_3() { + // given + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + when(externalTaskQueryTopicBuilder.execute()).thenReturn(Collections.emptyList()); + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + handler.addPendingRequest(createDto(4000L), asyncResponse, processEngine); + + addSecondsToClock(1); + handler.acquire(); + + // assume + assertThat(handler.getPendingRequests().size(), is(2)); + verify(handler).suspend(3000L); + + addSecondsToClock(4); + + // when + handler.acquire(); + + // then + verify(asyncResponse, times(2)).resume(Collections.emptyList()); + assertThat(handler.getPendingRequests().size(), is(0)); + verify(handler).suspend(Long.MAX_VALUE); + } + + @Test + public void shouldResumeAsyncResponseImmediatelyDueToProcessEngineException() { + // given + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + when(externalTaskQueryTopicBuilder.execute()).thenThrow(new ProcessEngineException()); + + // when + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + + // Then + assertThat(handler.getPendingRequests().size(), is(0)); + verify(handler, never()).suspend(anyLong()); + verify(asyncResponse).resume(any(ProcessEngineException.class)); + } + + @Test + public void shouldResumeAsyncResponseAfterBackoffDueToProcessEngineException() { + // given + when(fetchAndLockBuilder.subscribe()).thenReturn(externalTaskQueryTopicBuilder); + when(externalTaskQueryTopicBuilder.execute()).thenReturn(Collections.emptyList()); + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + handler.acquire(); + + // assume + assertThat(handler.getPendingRequests().size(), is(1)); + verify(handler).suspend(5000L); + + // when + doThrow(new ProcessEngineException()).when(externalTaskQueryTopicBuilder).execute(); + handler.acquire(); + + // then + assertThat(handler.getPendingRequests().size(), is(0)); + verify(handler).suspend(Long.MAX_VALUE); + verify(asyncResponse).resume(any(ProcessEngineException.class)); + } + + @Test + public void shouldResumeAsyncResponseDueToTimeoutExceeded() { + // given - no pending requests + + // assume + assertThat(handler.getPendingRequests().size(), is(0)); + + // when + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT + 1), asyncResponse, processEngine); + + // then + verify(handler, never()).suspend(anyLong()); + assertThat(handler.getPendingRequests().size(), is(0)); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(InvalidRequestException.class); + verify(asyncResponse).resume(argumentCaptor.capture()); + assertThat(argumentCaptor.getValue().getMessage(), is("The asynchronous response timeout cannot " + + "be set to a value greater than " + FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT + " milliseconds")); + } + + @Test + public void shouldPollPeriodicallyWhenRequestPending() { + // given + doReturn(Collections.emptyList()).when(externalTaskQueryTopicBuilder).execute(); + + // when + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT), asyncResponse, processEngine); + handler.acquire(); + + // then + verify(handler).suspend(FetchAndLockHandlerImpl.PENDING_REQUEST_FETCH_INTERVAL); + } + + @Test + public void shouldNotPollPeriodicallyWhenNotRequestsPending() { + // when + handler.acquire(); + + // then + verify(handler).suspend(FetchAndLockHandlerImpl.MAX_BACK_OFF_TIME); + } + + @Test + public void shouldCancelPreviousPendingRequestWhenWorkerIdsEqual() { + // given + doReturn(Collections.emptyList()).when(externalTaskQueryTopicBuilder).execute(); + + handler.parseUniqueWorkerRequestParam("true"); + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT, "aWorkerId"), asyncResponse, processEngine); + handler.acquire(); + + handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT, "aWorkerId"), mock(AsyncResponse.class), processEngine); + + // when + handler.acquire(); + + // then + verify(asyncResponse).cancel(); + assertThat(handler.getPendingRequests().size(), is(1)); + } + + @Test + public void shouldNotCancelPreviousPendingRequestWhenWorkerIdsDiffer() { + // given + doReturn(Collections.emptyList()).when(externalTaskQueryTopicBuilder).execute(); + + handler.parseUniqueWorkerRequestParam("true"); + + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT, "aWorkerId"), asyncResponse, processEngine); + handler.acquire(); + + handler.addPendingRequest(createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT, "anotherWorkerId"), mock(AsyncResponse.class), processEngine); + + // when + handler.acquire(); + + // then + verify(asyncResponse, never()).cancel(); + assertThat(handler.getPendingRequests().size(), is(2)); + } + + @Test + public void shouldResumeAsyncResponseDueToTooManyRequests() { + // given + + // when + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.errorTooManyRequests(asyncResponse); + + // then + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(InvalidRequestException.class); + verify(asyncResponse).resume(argumentCaptor.capture()); + assertThat(argumentCaptor.getValue().getMessage(), is("At the moment the server has to handle too " + + "many requests at the same time. Please try again later.")); + } + + @Test + public void shouldSuspendForeverDueToNoPendingRequests() { + // given - no pending requests + + // assume + assertThat(handler.getPendingRequests().size(), is(0)); + + // when + handler.acquire(); + + // then + assertThat(handler.getPendingRequests().size(), is(0)); + verify(handler).suspend(Long.MAX_VALUE); + } + + @Test + public void shouldRejectRequestDueToShutdown() { + // given + AsyncResponse asyncResponse = mock(AsyncResponse.class); + handler.addPendingRequest(createDto(5000L), asyncResponse, processEngine); + handler.acquire(); + + // assume + assertThat(handler.getPendingRequests().size(), is(1)); + + // when + handler.rejectPendingRequests(); + + // then + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(RestException.class); + + verify(asyncResponse).resume(argumentCaptor.capture()); + assertThat(argumentCaptor.getValue().getStatus(), is(Status.INTERNAL_SERVER_ERROR)); + assertThat(argumentCaptor.getValue().getMessage(), is("Request rejected due to shutdown of application server.")); + } + + @Test + public void shouldInitialiseQueueWithSpecifiedParam() { + // given + String queueSizeParamValue = "5"; + when(servletContext.getInitParameter(BLOCKING_QUEUE_CAPACITY_PARAM_NAME)).then(invocation -> queueSizeParamValue); + + // when + handler.contextInitialized(servletContextEvent); + + // then + assertThat(handler.queue.remainingCapacity(), is(5)); + } + + @Test + public void shouldInitialiseQueueWithDefaultCapacityWhenAbsentParam() { + // given no parameter + + // when + handler.contextInitialized(servletContextEvent); + + // then + assertThat(handler.queue.remainingCapacity(), is(DEFAULT_BLOCKING_QUEUE_CAPACITY)); + } + + @Test + public void shouldInitialiseQueueWithDefaultCapacityIfInvalidParam() { + // given + String queueSizeParamValue = "NaN"; + when(servletContext.getInitParameter(BLOCKING_QUEUE_CAPACITY_PARAM_NAME)).then(invocation -> queueSizeParamValue); + + // when + handler.contextInitialized(servletContextEvent); + + // then + assertThat(handler.queue.remainingCapacity(), is(DEFAULT_BLOCKING_QUEUE_CAPACITY)); + } + + @Test + public void shouldInitialiseQueueWithDefaultCapacityIfNotGreaterThanZero() { + // given + String queueSizeParamValue = "-3"; + when(servletContext.getInitParameter(BLOCKING_QUEUE_CAPACITY_PARAM_NAME)).then(invocation -> queueSizeParamValue); + + // when + handler.contextInitialized(servletContextEvent); + + // then + assertThat(handler.queue.remainingCapacity(), is(DEFAULT_BLOCKING_QUEUE_CAPACITY)); + } + + protected FetchExternalTasksExtendedDto createDto(Long responseTimeout, String workerId) { + FetchExternalTasksExtendedDto externalTask = new FetchExternalTasksExtendedDto(); + + FetchExternalTasksExtendedDto.FetchExternalTaskTopicDto topic = new FetchExternalTasksExtendedDto.FetchExternalTaskTopicDto(); + topic.setTopicName("aTopicName"); + topic.setLockDuration(12354L); + + externalTask.setMaxTasks(5); + externalTask.setWorkerId(workerId); + externalTask.setTopics(Collections.singletonList(topic)); + + if (responseTimeout != null) { + externalTask.setAsyncResponseTimeout(responseTimeout); + } + + return externalTask; + } + + protected FetchExternalTasksExtendedDto createDto(Long responseTimeout) { + return createDto(responseTimeout, "aWorkerId"); + } + + protected Date addSeconds(Date date, int seconds) { + return new Date(date.getTime() + seconds * 1000); + } + + protected void addSecondsToClock(int seconds) { + Date newDate = addSeconds(ClockUtil.getCurrentTime(), seconds); + ClockUtil.setCurrentTime(newDate); + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/impl/FetchAndLockRestServiceInteractionTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/impl/FetchAndLockRestServiceInteractionTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5e7eb0964a0cfb5f00026900b1ee7650bfe6632c --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/impl/FetchAndLockRestServiceInteractionTest.java @@ -0,0 +1,418 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.impl; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.anyList; +import static org.mockito.Mockito.anyLong; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.restassured.http.ContentType; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import javax.servlet.ServletContextEvent; +import javax.ws.rs.core.Response.Status; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.IdentityService; +import org.camunda.bpm.engine.ProcessEngineException; +import org.camunda.bpm.engine.externaltask.ExternalTaskQueryTopicBuilder; +import org.camunda.bpm.engine.externaltask.FetchAndLockBuilder; +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.identity.Group; +import org.camunda.bpm.engine.identity.Tenant; +import org.camunda.bpm.engine.impl.identity.Authentication; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksDto.FetchExternalTaskTopicDto; +import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksExtendedDto; +import org.camunda.bpm.engine.rest.exception.InvalidRequestException; +import org.camunda.bpm.engine.rest.helper.MockProvider; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +/** + * @author Tassilo Weidner + */ +@RunWith(MockitoJUnitRunner.Silent.class) +public class FetchAndLockRestServiceInteractionTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + private static final String FETCH_EXTERNAL_TASK_URL = "/rest-test/external-task/fetchAndLock"; + + @Mock + private ExternalTaskService externalTaskService; + + @Mock + private ExternalTaskQueryTopicBuilder fetchTopicBuilder; + + @Mock + private FetchAndLockBuilder fetchAndLockBuilder; + + @Mock + private IdentityService identityServiceMock; + + private LockedExternalTask lockedExternalTaskMock; + + private List groupIds; + private List tenantIds; + + @Before + public void setUpRuntimeData() { + when(processEngine.getExternalTaskService()).thenReturn(externalTaskService); + + lockedExternalTaskMock = MockProvider.createMockLockedExternalTask(); + + when(externalTaskService.fetchAndLock(anyInt(), any(String.class), any(Boolean.class))) + .thenReturn(fetchTopicBuilder); + + when(externalTaskService.fetchAndLock()).thenReturn(fetchAndLockBuilder); + + // fetch and lock builder + when(fetchAndLockBuilder.workerId(anyString())).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.maxTasks(anyInt())).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.usePriority(anyBoolean())).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.orderByCreateTime()).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.asc()).thenReturn(fetchAndLockBuilder); + when(fetchAndLockBuilder.desc()).thenReturn(fetchAndLockBuilder); + + when(fetchAndLockBuilder.subscribe()).thenReturn(fetchTopicBuilder); + + when(fetchTopicBuilder.topic(anyString(), anyLong())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.variables(anyList())).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.enableCustomObjectDeserialization()).thenReturn(fetchTopicBuilder); + when(fetchTopicBuilder.processDefinitionVersionTag(anyString())).thenReturn(fetchTopicBuilder); + + // for authentication + when(processEngine.getIdentityService()).thenReturn(identityServiceMock); + + List groupMocks = MockProvider.createMockGroups(); + groupIds = groupMocks.stream().map(Group::getId).collect(Collectors.toList()); + + List tenantMocks = Collections.singletonList(MockProvider.createMockTenant()); + tenantIds = tenantMocks.stream().map(Tenant::getId).collect(Collectors.toList()); + + new FetchAndLockContextListener().contextInitialized(mock(ServletContextEvent.class, RETURNS_DEEP_STUBS)); + } + + @Test + public void shouldFetchAndLock() { + when(fetchTopicBuilder.execute()).thenReturn(new ArrayList<>(Collections.singleton(lockedExternalTaskMock))); + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(null, true, true, false); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("[0].id", equalTo(MockProvider.EXTERNAL_TASK_ID)) + .body("[0].topicName", equalTo(MockProvider.EXTERNAL_TASK_TOPIC_NAME)) + .body("[0].workerId", equalTo(MockProvider.EXTERNAL_TASK_WORKER_ID)) + .body("[0].lockExpirationTime", equalTo(MockProvider.EXTERNAL_TASK_LOCK_EXPIRATION_TIME)) + .body("[0].createTime", equalTo(MockProvider.EXTERNAL_TASK_CREATE_TIME)) + .body("[0].processInstanceId", equalTo(MockProvider.EXAMPLE_PROCESS_INSTANCE_ID)) + .body("[0].executionId", equalTo(MockProvider.EXAMPLE_EXECUTION_ID)) + .body("[0].activityId", equalTo(MockProvider.EXAMPLE_ACTIVITY_ID)) + .body("[0].activityInstanceId", equalTo(MockProvider.EXAMPLE_ACTIVITY_INSTANCE_ID)) + .body("[0].processDefinitionId", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_ID)) + .body("[0].processDefinitionKey", equalTo(MockProvider.EXAMPLE_PROCESS_DEFINITION_KEY)) + .body("[0].tenantId", equalTo(MockProvider.EXAMPLE_TENANT_ID)) + .body("[0].retries", equalTo(MockProvider.EXTERNAL_TASK_RETRIES)) + .body("[0].errorMessage", equalTo(MockProvider.EXTERNAL_TASK_ERROR_MESSAGE)) + .body("[0].errorMessage", equalTo(MockProvider.EXTERNAL_TASK_ERROR_MESSAGE)) + .body("[0].priority", equalTo(MockProvider.EXTERNAL_TASK_PRIORITY)) + .body("[0].variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME, notNullValue()) + .body("[0].variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".value", equalTo(MockProvider.EXAMPLE_PRIMITIVE_VARIABLE_VALUE.getValue())) + .body("[0].variables." + MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME + ".type", equalTo("String")) + .when().post(FETCH_EXTERNAL_TASK_URL); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService, times(1)).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(true); + + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).variables(Collections.singletonList(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, externalTaskService); + } + + @Test + public void shouldFetchWithoutVariables() { + when(fetchTopicBuilder.execute()).thenReturn(new ArrayList<>(Collections.singleton(lockedExternalTaskMock))); + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(null); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .body("[0].id", equalTo(MockProvider.EXTERNAL_TASK_ID)) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService, times(1)).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, externalTaskService); + } + + @Test + public void shouldFetchWithCustomObjectDeserializationEnabled() { + when(fetchTopicBuilder.execute()) + .thenReturn(new ArrayList<>(Collections.singleton(lockedExternalTaskMock))); + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(null, false, true, true); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + InOrder inOrder = inOrder(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + + inOrder.verify(externalTaskService).fetchAndLock(); + + inOrder.verify(fetchAndLockBuilder).workerId("aWorkerId"); + inOrder.verify(fetchAndLockBuilder).maxTasks(5); + inOrder.verify(fetchAndLockBuilder).usePriority(false); + + inOrder.verify(fetchAndLockBuilder).subscribe(); + + inOrder.verify(fetchTopicBuilder).topic("aTopicName", 12354L); + inOrder.verify(fetchTopicBuilder).variables(Collections.singletonList(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME)); + inOrder.verify(fetchTopicBuilder).enableCustomObjectDeserialization(); + inOrder.verify(fetchTopicBuilder).execute(); + + verifyNoMoreInteractions(fetchAndLockBuilder, fetchTopicBuilder, externalTaskService); + } + + @Test + public void shouldThrowInvalidRequestExceptionOnMaxTimeoutExceeded() { + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(FetchAndLockHandlerImpl.MAX_REQUEST_TIMEOUT + 1); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .body("type", equalTo(InvalidRequestException.class.getSimpleName())) + .body("message", containsString("The asynchronous response timeout cannot be set to a value greater than ")) + .statusCode(Status.BAD_REQUEST.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + } + + @Test + public void shouldThrowProcessEngineExceptionDuringTimeout() { + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(500L); + + when(fetchTopicBuilder.execute()) + .thenReturn(Collections.emptyList()) + .thenReturn(Collections.emptyList()) + .thenThrow(new ProcessEngineException("anExceptionMessage")); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("anExceptionMessage")) + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + verify(fetchTopicBuilder, atLeastOnce()).execute(); + } + + @Test + public void shouldThrowProcessEngineExceptionNotDuringTimeout() { + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(500L); + + when(fetchTopicBuilder.execute()) + .thenThrow(new ProcessEngineException("anExceptionMessage")); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .body("type", equalTo(ProcessEngineException.class.getSimpleName())) + .body("message", equalTo("anExceptionMessage")) + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + verify(fetchTopicBuilder, times(1)).execute(); + } + + @Test + public void shouldResponseImmediatelyDueToAvailableTasks() { + when(fetchTopicBuilder.execute()) + .thenReturn(new ArrayList<>(Collections.singleton(lockedExternalTaskMock))); + + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(500L); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .body("size()", is(1)) + .statusCode(Status.OK.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + } + + @Ignore + @Test + public void shouldSetAuthenticationProperly() { + when(identityServiceMock.getCurrentAuthentication()) + .thenReturn(new Authentication(MockProvider.EXAMPLE_USER_ID, groupIds, tenantIds)); + + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(500L); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Authentication.class); + verify(identityServiceMock, atLeastOnce()).setAuthentication(argumentCaptor.capture()); + + assertThat(argumentCaptor.getValue().getUserId(), is(MockProvider.EXAMPLE_USER_ID)); + assertThat(argumentCaptor.getValue().getGroupIds(), is(groupIds)); + assertThat(argumentCaptor.getValue().getTenantIds(), is(tenantIds)); + } + + @Test + public void shouldReturnInternalServerErrorResponseJsonWithTypeAndMessage() { + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(500L); + + when(fetchTopicBuilder.execute()) + .thenThrow(new IllegalArgumentException("anExceptionMessage")); + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .body("type", equalTo(IllegalArgumentException.class.getSimpleName())) + .body("message", equalTo("anExceptionMessage")) + .statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + verify(fetchTopicBuilder, times(1)).execute(); + } + + @Test + public void shouldFetchAndLockByProcessDefinitionVersionTag() { + when(fetchTopicBuilder.execute()) + .thenReturn(new ArrayList(Collections.singleton(lockedExternalTaskMock))); + + FetchExternalTasksExtendedDto fetchExternalTasksDto = createDto(500L); + for (FetchExternalTaskTopicDto topic : fetchExternalTasksDto.getTopics()) { + topic.setProcessDefinitionVersionTag("version"); + } + + given() + .contentType(ContentType.JSON) + .body(fetchExternalTasksDto) + .then() + .expect() + .statusCode(Status.OK.getStatusCode()) + .when() + .post(FETCH_EXTERNAL_TASK_URL); + + verify(fetchTopicBuilder).processDefinitionVersionTag("version"); + } + + // helper ///////////////////////// + + private FetchExternalTasksExtendedDto createDto(Long responseTimeout) { + return createDto(responseTimeout, false, false, false); + } + + private FetchExternalTasksExtendedDto createDto(Long responseTimeout, boolean usePriority, boolean withVariables, boolean withDeserialization) { + FetchExternalTasksExtendedDto fetchExternalTasksDto = new FetchExternalTasksExtendedDto(); + if (responseTimeout != null) { + fetchExternalTasksDto.setAsyncResponseTimeout(responseTimeout); + } + fetchExternalTasksDto.setMaxTasks(5); + fetchExternalTasksDto.setWorkerId("aWorkerId"); + fetchExternalTasksDto.setUsePriority(usePriority); + FetchExternalTasksExtendedDto.FetchExternalTaskTopicDto topicDto = new FetchExternalTasksExtendedDto.FetchExternalTaskTopicDto(); + fetchExternalTasksDto.setTopics(Collections.singletonList(topicDto)); + topicDto.setTopicName("aTopicName"); + topicDto.setLockDuration(12354L); + if (withVariables) { + topicDto.setVariables(Collections.singletonList(MockProvider.EXAMPLE_VARIABLE_INSTANCE_NAME)); + } + topicDto.setDeserializeValues(withDeserialization); + fetchExternalTasksDto.setTopics(Collections.singletonList(topicDto)); + return fetchExternalTasksDto; + } + +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/mapper/Java8DateTimePojo.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/mapper/Java8DateTimePojo.java new file mode 100644 index 0000000000000000000000000000000000000000..2f72d2d79edd31f84cad707e564ed3d645995248 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/mapper/Java8DateTimePojo.java @@ -0,0 +1,32 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.mapper; + +import java.time.LocalDate; + +public class Java8DateTimePojo { + + private LocalDate localDate = LocalDate.now(); + + public LocalDate getLocalDate() { + return localDate; + } + + public void setLocalDate(LocalDate localDate) { + this.localDate = localDate; + } +} diff --git a/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/mapper/Java8DateTimeTest.java b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/mapper/Java8DateTimeTest.java new file mode 100644 index 0000000000000000000000000000000000000000..15aa855e0488fe1e5a6db5015655c8b70129c525 --- /dev/null +++ b/source_data/pinned/camunda-dmn-examples/commit-ee4826e5e76c/engine-rest/engine-rest/src/test/java/org/camunda/bpm/engine/rest/mapper/Java8DateTimeTest.java @@ -0,0 +1,72 @@ +/* + * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH + * under one or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information regarding copyright + * ownership. Camunda licenses this file to you under the Apache License, + * Version 2.0; you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.camunda.bpm.engine.rest.mapper; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.time.LocalDate; + +import javax.ws.rs.core.Response.Status; + +import org.camunda.bpm.engine.impl.RuntimeServiceImpl; +import org.camunda.bpm.engine.rest.AbstractRestServiceTest; +import org.camunda.bpm.engine.rest.util.container.TestContainerRule; +import org.camunda.bpm.engine.variable.Variables; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; + +public class Java8DateTimeTest extends AbstractRestServiceTest { + + @ClassRule + public static TestContainerRule rule = new TestContainerRule(); + + protected static final String PROCESS_INSTANCE_URL = TEST_RESOURCE_ROOT_PATH + "/process-instance"; + protected static final String SINGLE_PROCESS_INSTANCE_URL = PROCESS_INSTANCE_URL + "/{id}"; + protected static final String PROCESS_INSTANCE_VARIABLES_URL = SINGLE_PROCESS_INSTANCE_URL + "/variables"; + protected static final String SINGLE_PROCESS_INSTANCE_VARIABLE_URL = PROCESS_INSTANCE_VARIABLES_URL + "/{varId}"; + + protected RuntimeServiceImpl runtimeServiceMock; + + @Before + public void setUpRuntimeData() { + runtimeServiceMock = mock(RuntimeServiceImpl.class); + + when(runtimeServiceMock.getVariableTyped(eq(EXAMPLE_PROCESS_INSTANCE_ID), eq(EXAMPLE_VARIABLE_KEY), eq(true))) + .thenReturn(Variables.objectValue(new Java8DateTimePojo()).create()); + + when(processEngine.getRuntimeService()).thenReturn(runtimeServiceMock); + } + + @Test + public void testGetVariable() { + given() + .pathParam("id", EXAMPLE_PROCESS_INSTANCE_ID) + .pathParam("varId", EXAMPLE_VARIABLE_KEY) + .then().expect() + .statusCode(Status.OK.getStatusCode()) + .body("value.localDate", is(LocalDate.now().toString())) + .body("type", is("Object")) + .when() + .get(SINGLE_PROCESS_INSTANCE_VARIABLE_URL); + } + +}