diff --git a/camunda-bpm-camel-cdi/pom.xml b/camunda-bpm-camel-cdi/pom.xml deleted file mode 100644 index 52927d7..0000000 --- a/camunda-bpm-camel-cdi/pom.xml +++ /dev/null @@ -1,161 +0,0 @@ - - - - camunda BPM - Apache Camel Integration (CDI) - camunda-bpm-camel-cdi - - - org.camunda.bpm.extension.camel - camunda-bpm-camel - 0.9.0-SNAPSHOT - - 4.0.0 - - - true - - - - - org.camunda.bpm.extension.camel - camunda-bpm-camel-common - - - org.camunda.bpm - camunda-engine - ${camunda-bpm.version} - provided - - - org.camunda.bpm - camunda-engine-cdi - ${camunda-bpm.version} - - - - org.slf4j - slf4j-api - ${sl4j.version} - - - org.slf4j - jcl-over-slf4j - ${sl4j.version} - - - org.slf4j - slf4j-log4j12 - ${sl4j.version} - - - - - org.apache.camel - camel-core - ${camel.version} - - - org.apache.camel - camel-cdi - ${camel.version} - - - - - org.camunda.bpm.extension.camel - camunda-bpm-camel-common-tests - - - junit - junit - ${junit.version} - test - - - com.h2database - h2 - ${h2.version} - test - - - org.apache.camel - camel-mvel - ${camel.version} - test - - - com.fasterxml.uuid - java-uuid-generator - 4.0.1 - test - - - org.easytesting - fest-assert-core - ${fest.assert.version} - test - - - org.jboss.as - jboss-as-arquillian-container-remote - 7.1.3.Final - test - - - org.jboss.arquillian.junit - arquillian-junit-container - 1.0.3.Final - test - - - org.jboss.spec - jboss-javaee-6.0 - 2.0.0.Final - pom - provided - - - xalan - org.apache.xalan - - - - - - - - - - - - - maven-failsafe-plugin - 2.22.2 - - - -Djava.util.logging.config.file=${basedir}/src/test/resources/logging.properties - ${project.build.sourceEncoding} - - - - failsafe-integration-tests - integration-test - - integration-test - - - - failsafe-verify - verify - - verify - - - - - - - diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/ArquillianTestsProcessApplication.java b/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/ArquillianTestsProcessApplication.java deleted file mode 100644 index b7af433..0000000 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/ArquillianTestsProcessApplication.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.camunda.bpm.camel.cdi; - -import org.apache.camel.builder.RouteBuilder; -import org.camunda.bpm.application.ProcessApplication; -import org.camunda.bpm.application.ProcessApplicationInterface; -import org.camunda.bpm.application.impl.EjbProcessApplication; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.ejb.*; -import javax.inject.Inject; - -/** - * We need this class because @Startup annotations are lazily instantiated and not *really* initalized at - * startup. We use this class to make sure that the CamelContextBootstrap is initialized at startup. - */ -@Singleton -@Startup -@ConcurrencyManagement(ConcurrencyManagementType.BEAN) -@TransactionAttribute(TransactionAttributeType.REQUIRED) -@ProcessApplication -@Local(ProcessApplicationInterface.class) -public class ArquillianTestsProcessApplication extends EjbProcessApplication { - - private static final Logger LOG = LoggerFactory.getLogger(ArquillianTestsProcessApplication.class); - - @Inject - CamelContextBootstrap camelContext; - - /* - * Every integration test needs to provide a method that will return the Camel route - * to be use for testing with a @Produces annotation - */ - @Inject - RouteBuilder testRoute; - - @PostConstruct - public void start() throws Exception { - LOG.info(">>"); - LOG.info(">> Starting the ArquillianTestsProcessApplication "); - LOG.info(">>"); - - camelContext.addRoute(testRoute); - camelContext.start(); - deploy(); - } - - @PreDestroy - public void stop() { - undeploy(); - } - -} \ No newline at end of file diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/BaseArquillianIntegrationTest.java b/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/BaseArquillianIntegrationTest.java deleted file mode 100644 index d08a5d8..0000000 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/BaseArquillianIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.camunda.bpm.camel.cdi; - -import org.camunda.bpm.camel.common.CamelService; -import org.camunda.bpm.camel.spring.util.LogService; -import org.camunda.bpm.camel.spring.util.LogServiceImpl; -import org.camunda.bpm.engine.HistoryService; -import org.camunda.bpm.engine.RuntimeService; -import org.camunda.bpm.engine.TaskService; -import org.jboss.shrinkwrap.api.ArchivePaths; -import org.jboss.shrinkwrap.api.ShrinkWrap; -import org.jboss.shrinkwrap.api.asset.EmptyAsset; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.jboss.shrinkwrap.resolver.api.DependencyResolvers; -import org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver; - -import javax.inject.Inject; - -public abstract class BaseArquillianIntegrationTest { - - @Inject - @SuppressWarnings("cdi-ambiguous-dependency") - protected RuntimeService runtimeService; - - @Inject - @SuppressWarnings("cdi-ambiguous-dependency") - protected TaskService taskService; - - @Inject - @SuppressWarnings("cdi-ambiguous-dependency") - protected HistoryService historyService; - - @Inject - CamelContextBootstrap camelContextBootstrap; - - @Inject - CamelService camelService; - - protected static WebArchive prepareTestDeployment(String deploymentArchiveName, - String processDefinition) { - MavenDependencyResolver resolver = DependencyResolvers.use(MavenDependencyResolver.class) - .loadMetadataFromPom("pom.xml"); - - WebArchive war = ShrinkWrap.create(WebArchive.class, deploymentArchiveName + ".war") - .addAsLibraries(resolver.artifact("org.camunda.bpm:camunda-engine-cdi").resolveAsFiles()) - .addAsLibraries(resolver.artifact("org.camunda.bpm.extension.camel:camunda-bpm-camel-common").resolveAsFiles()) - .addAsLibraries(resolver.artifact("org.apache.camel:camel-core").resolveAsFiles()) - .addAsLibraries(resolver.artifact("org.apache.camel:camel-cdi").resolveAsFiles()) - .addAsLibraries(resolver.artifact("org.easytesting:fest-assert-core").resolveAsFiles()) - // FIXME: this does not work we need to add this project's resources one by one - //.addAsLibraries(resolver.artifact("org.camunda.bpm.extension.camel:camunda-bpm-camel-cdi").resolveAsFiles()) - .addClass(CamelServiceImpl.class) - .addClass(BaseArquillianIntegrationTest.class) - .addClass(ArquillianTestsProcessApplication.class) - .addClass(CamelContextBootstrap.class) - - .addClass(LogService.class) - .addClass(LogServiceImpl.class) - .addClass(LogServiceCdiImpl.class) - - //.addClass(camelRouteClass) - .addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml")) - .addAsWebResource("META-INF/processes.xml", "WEB-INF/classes/META-INF/processes.xml") - .addAsResource(processDefinition) - ; - - /* - * For troubleshooting purposes use the following two lines to export the WAR to the filesystem - * to see if everything needed is there! - */ - //File destinationDir = new File("/Users/rafa/dev/plexiti/vc/the-job-announcement-fox/target"); - //war.as(ExplodedExporter.class).exportExploded(destinationDir); - - return war; - } -} diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/LogServiceCdiImpl.java b/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/LogServiceCdiImpl.java deleted file mode 100644 index 4b68c7c..0000000 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/LogServiceCdiImpl.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.camunda.bpm.camel.cdi; - -import javax.inject.Named; - -import org.camunda.bpm.camel.spring.util.LogServiceImpl; - -@Named("log") -public class LogServiceCdiImpl extends LogServiceImpl { - -} diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/ReceiveFromCamelIT.java b/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/ReceiveFromCamelIT.java deleted file mode 100644 index 846141a..0000000 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/ReceiveFromCamelIT.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.camunda.bpm.camel.cdi; - -import org.apache.camel.ProducerTemplate; -import org.apache.camel.builder.RouteBuilder; -import org.apache.camel.cdi.Uri; -import org.apache.camel.component.mock.MockEndpoint; -import org.camunda.bpm.engine.runtime.ProcessInstance; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Produces; -import javax.inject.Inject; - -import java.util.HashMap; -import java.util.Map; - -import static org.fest.assertions.api.Assertions.assertThat; - -@RunWith(Arquillian.class) -public class ReceiveFromCamelIT extends BaseArquillianIntegrationTest { - - private static String PROCESS_DEFINITION_KEY = "receiveFromCamelProcess"; - - @Deployment - public static WebArchive createDeployment() { - return prepareTestDeployment(PROCESS_DEFINITION_KEY, "process/ReceiveFromCamel.bpmn20.xml"); - } - - @Inject - @Uri("mock:resultEndpoint") - MockEndpoint resultEndpoint; - - @Produces - @ApplicationScoped - public RouteBuilder createRoute() { - return new RouteBuilder() { - public void configure() { - from("direct:sendToCamundaBpm") - .routeId("receive-from-camel-route") - .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") - .to("camunda-bpm://signal?processDefinitionKey=receiveFromCamelProcess&activityId=waitForCamel") - .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") - .to(resultEndpoint) - ; - } - }; - } - - @Test - public void doTest() throws InterruptedException { - Map processVariables = new HashMap(); - processVariables.put("var1", "foo"); - processVariables.put("var2", "bar"); - ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("receiveFromCamelProcess", processVariables); - - // Verify that a process instance has executed and there is one instance executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("receiveFromCamelProcess").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("receiveFromCamelProcess").count()).isEqualTo(1); - - /* - * We need the process instance ID to be able to send the message to it - * - * FIXME: we need to fix this with the process execution id or even better with the Activity Instance Model - * http://camundabpm.blogspot.de/2013/06/introducing-activity-instance-model-to.html - */ - ProducerTemplate tpl = camelContextBootstrap.getCamelContext().createProducerTemplate(); - tpl.sendBodyAndProperty("direct:sendToCamundaBpm", null, EXCHANGE_HEADER_PROCESS_INSTANCE_ID, processInstance.getId()); - - // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(resultEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo(processInstance.getId()); - - // Assert that the process instance is finished - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("receiveFromCamelProcess").count()).isEqualTo(0); - } -} \ No newline at end of file diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/SendToCamelIT.java b/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/SendToCamelIT.java deleted file mode 100644 index c06d824..0000000 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/SendToCamelIT.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.camunda.bpm.camel.cdi; - -import org.apache.camel.builder.RouteBuilder; -import org.apache.camel.cdi.Uri; -import org.apache.camel.component.mock.MockEndpoint; -import org.camunda.bpm.engine.runtime.ProcessInstance; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Produces; -import javax.inject.Inject; - -import java.util.HashMap; -import java.util.Map; - -import static org.fest.assertions.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; - -@RunWith(Arquillian.class) -public class SendToCamelIT extends BaseArquillianIntegrationTest { - - private static String PROCESS_DEFINITION_KEY = "sendToCamelProcess"; - - @Deployment - public static WebArchive createDeployment() { - return prepareTestDeployment(PROCESS_DEFINITION_KEY, "process/SendToCamel.bpmn20.xml"); - } - - @Inject - @Uri("mock:resultEndpoint") - MockEndpoint resultEndpoint; - - @Produces - @ApplicationScoped - public RouteBuilder createRoute() { - return new RouteBuilder() { - public void configure() { - from("direct:sendToCamelServiceTask") - .routeId("send-to-camel-route") - .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") - .to(resultEndpoint) - ; - } - }; - } - - @Test - public void doTest() throws InterruptedException { - Map processVariables = new HashMap(); - processVariables.put("var1", "foo"); - processVariables.put("var2", "bar"); - ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("sendToCamelProcess", processVariables); - - // Verify that a process instance was executed and there are no instances executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("sendToCamelProcess").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("sendToCamelProcess").count()).isEqualTo(0); - - // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(resultEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo(processInstance.getId()); - - // Assert that the body of the message received by the endpoint contains a hash map with the value of the process variable 'var1' sent from camunda BPM - assertThat(resultEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo("{var1=foo}"); - - // FIXME: check that var2 is also present as a property! - } -} \ No newline at end of file diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/SmokeIT.java b/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/SmokeIT.java deleted file mode 100644 index 418c0d7..0000000 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/SmokeIT.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.camunda.bpm.camel.cdi; - -import org.apache.camel.builder.RouteBuilder; -import org.apache.camel.cdi.Uri; -import org.apache.camel.component.mock.MockEndpoint; -import org.camunda.bpm.engine.task.Task; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Produces; -import javax.inject.Inject; - -import static org.fest.assertions.api.Assertions.assertThat; - -/* - * This test is basically a ... smoke test. It's a baseline to check that all the moving pieces - * (Maven deps, Arquillian config, ...) are working OK: - * - process definition deployment - * - Camel context instantiation and route startup - * - ... - * - * See other tests in this package for actual exercising of the camunda BPM <-> Camel integration - */ -@RunWith(Arquillian.class) -public class SmokeIT extends BaseArquillianIntegrationTest { - - private static String PROCESS_DEFINITION_KEY = "smokeTestProcess"; - - @Deployment - public static WebArchive createDeployment() { - return prepareTestDeployment(PROCESS_DEFINITION_KEY, "process/SmokeTest.bpmn20.xml"); - } - - @Inject - @Uri("resultEndpoint") - MockEndpoint resultEndpoint; - - @Produces - @ApplicationScoped - public RouteBuilder createRoute() { - return new RouteBuilder() { - public void configure() { - from("timer://smoke-message?repeatCount=1") - .routeId("smoke-test-route") - .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") - .to(resultEndpoint) - ; - } - }; - } - - @Test - public void doTest() throws InterruptedException { - - assertThat(camelContextBootstrap).isNotNull(); - assertThat(camelContextBootstrap.getCamelContext()).isNotNull(); - assertThat(camelService).isNotNull(); - - runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY); - Task task = taskService.createTaskQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).singleResult(); - assertThat(task).isNotNull(); - assertThat("My Task").isEqualTo(task.getName()); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()).isEqualTo(1); - - taskService.complete(task.getId()); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()).isEqualTo(0); - resultEndpoint.expectedMessageCount(1); - resultEndpoint.assertIsSatisfied(); - } -} diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/StartProcessFromRouteIT.java b/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/StartProcessFromRouteIT.java deleted file mode 100644 index 40678fb..0000000 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/StartProcessFromRouteIT.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.camunda.bpm.camel.cdi; - -import org.apache.camel.ProducerTemplate; -import org.apache.camel.builder.RouteBuilder; -import org.apache.camel.cdi.Uri; -import org.apache.camel.component.mock.MockEndpoint; -import org.jboss.arquillian.container.test.api.Deployment; -import org.jboss.arquillian.junit.Arquillian; -import org.jboss.shrinkwrap.api.spec.WebArchive; -import org.junit.Test; -import org.junit.runner.RunWith; - -import javax.enterprise.context.ApplicationScoped; -import javax.enterprise.inject.Produces; -import javax.inject.Inject; - -import java.util.Collections; - -import static org.fest.assertions.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; - -@RunWith(Arquillian.class) -public class StartProcessFromRouteIT extends BaseArquillianIntegrationTest { - - private static String PROCESS_DEFINITION_KEY = "startProcessFromRoute"; - - @Deployment - public static WebArchive createDeployment() { - return prepareTestDeployment(PROCESS_DEFINITION_KEY, "process/StartProcessFromRoute.bpmn20.xml"); - } - - @Inject - @Uri("mock:mockEndpoint") - MockEndpoint mockEndpoint; - - @Inject - @Uri("mock:processVariableEndpoint") - MockEndpoint processVariableEndpoint; - - @Produces - @ApplicationScoped - public RouteBuilder createRoute() { - return new RouteBuilder() { - public void configure() { - from("direct:start") - .routeId("start-process-from-route") - .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") - .to("camunda-bpm://start?processDefinitionKey=startProcessFromRoute©BodyAsVariable=var1") - .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") - .to(mockEndpoint) - ; - - from("direct:processVariable") - .routeId("processVariableRoute") - .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") - .to(processVariableEndpoint) - ; - } - }; - } - - @Test - public void doTest() throws InterruptedException { - ProducerTemplate tpl = camelContextBootstrap.getCamelContext().createProducerTemplate(); - - String processInstanceId = (String) tpl.requestBody("direct:start", Collections.singletonMap("var1", "valueOfVar1")); - assertThat(processInstanceId).isNotNull(); - System.out.println("Process instance ID: " + processInstanceId); - - // Verify that a process instance was executed and there are no instances executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(0); - - // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo(processInstanceId); - - // The body of the message comming out from the camunda-bpm: endpoint is the process instance - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo(processInstanceId); - - // We should receive a hash map with the value of 'var1' as the body of the message - assertThat(processVariableEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo("{var1=valueOfVar1}"); - } -} \ No newline at end of file diff --git a/camunda-bpm-camel-cdi/src/test/resources/log4j.properties b/camunda-bpm-camel-cdi/src/test/resources/log4j.properties deleted file mode 100644 index 1a421b8..0000000 --- a/camunda-bpm-camel-cdi/src/test/resources/log4j.properties +++ /dev/null @@ -1,14 +0,0 @@ -log4j.rootLogger=INFO, CA - -# ConsoleAppender -log4j.appender.CA=org.apache.log4j.ConsoleAppender -log4j.appender.CA.layout=org.apache.log4j.PatternLayout -log4j.appender.CA.layout.ConversionPattern= %d{hh:mm:ss,SSS} [%t] %-5p %c %x - %m%n - -#log4j.logger.org.camunda=DEBUG -#log4j.logger.org.springframework=DEBUG -log4j.logger.org.apache.camel=DEBUG -log4j.logger.org.camunda.bpm.camel=DEBUG -log4j.logger.org.camunda.bpm.camel.cdi=DEBUG -log4j.logger.org.jboss.shrinkwrap=DEBUG -log4j.logger.org.jboss.arquillian=DEBUG \ No newline at end of file diff --git a/camunda-bpm-camel-cdi/src/test/resources/logging.properties b/camunda-bpm-camel-cdi/src/test/resources/logging.properties deleted file mode 100644 index 5da3f3e..0000000 --- a/camunda-bpm-camel-cdi/src/test/resources/logging.properties +++ /dev/null @@ -1,22 +0,0 @@ -# See http://www.java-tips.org/java-se-tips/java.util.logging/how-to-configure-a-logger-default-values-with-a-properties.html -# Specify the handlers to create in the root logger -# (all loggers are children of the root logger) -# The following creates two handlers -handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler - -# Set the default logging level for the root logger -.level = ALL - -# Set the default logging level for new ConsoleHandler instances -java.util.logging.ConsoleHandler.level = INFO - -# Set the default logging level for new FileHandler instances -java.util.logging.FileHandler.level = ALL - -# Set the default formatter for new ConsoleHandler instances -java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter - -# Hide the message "WARNING: Invalid metadata org.camunda.bpm.incubation:camunda-bpm-camel-common:0.1-SNAPSHOT/maven-metadata.xml" -# See https://community.jboss.org/thread/198980 -org.jboss.shrinkwrap.resolver.impl.maven.level=SEVERE -org.jboss.shrinkwrap.resolver.impl.maven.LogRepositoryListener=SEVERE \ No newline at end of file diff --git a/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogService.java b/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogService.java index 1dbdd75..8bb8049 100644 --- a/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogService.java +++ b/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogService.java @@ -13,6 +13,6 @@ package org.camunda.bpm.camel.spring.util; public interface LogService { - public void debug(Object msg); - public void info(Object msg); + void debug(Object msg); + void info(Object msg); } diff --git a/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogServiceImpl.java b/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogServiceImpl.java index b189954..2a3724b 100644 --- a/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogServiceImpl.java +++ b/camunda-bpm-camel-common-tests/src/main/java/org/camunda/bpm/camel/spring/util/LogServiceImpl.java @@ -16,17 +16,16 @@ import org.slf4j.LoggerFactory; public class LogServiceImpl implements LogService { - final Logger log = LoggerFactory.getLogger(this.getClass()); @Override public void debug(Object msg) { - log.debug("LogService: {}", msg.toString()); + log.debug("LogService: {}", msg); } @Override public void info(Object msg) { - log.debug("LogService: {}", msg.toString()); + log.info("LogService: {}", msg); } } diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/ReceiveFromCamel.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/ReceiveFromCamel.bpmn20.xml index a8c557b..3af55b7 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/ReceiveFromCamel.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/ReceiveFromCamel.bpmn20.xml @@ -1,6 +1,6 @@ - - + + SequenceFlow_2 @@ -8,13 +8,13 @@ SequenceFlow_1 SequenceFlow_3 - + SequenceFlow_2 SequenceFlow_1 - - - + + + SequenceFlow_3 @@ -22,38 +22,38 @@ - + - + + + + - + - + - - - - - + + - + - - + + - - + + - + - \ No newline at end of file + diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/SendToCamel.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/SendToCamel.bpmn20.xml index 3580caf..48d1b35 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/SendToCamel.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/SendToCamel.bpmn20.xml @@ -1,20 +1,20 @@ - - + + flow1 - - + + flow1 flow2 - - + + flow2 SequenceFlow_2 - + SequenceFlow_2 @@ -22,39 +22,39 @@ - + - + + + + - + - + + + + + - - - + + + - + - - - - - - - - - + + - + - \ No newline at end of file + diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/SmokeTest.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/SmokeTest.bpmn20.xml index 25bb2ab..350f6fd 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/SmokeTest.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/SmokeTest.bpmn20.xml @@ -1,31 +1,31 @@ - - - - - - - + + + + + + + - - - + + + - - + + - - + + - - - + + + - - - + + + - \ No newline at end of file + diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask.bpmn20.xml index e3c0d67..2746e04 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask.bpmn20.xml @@ -1,6 +1,6 @@ - - + + SequenceFlow_0l4pbmo @@ -37,13 +37,6 @@ - - - - - - - @@ -53,53 +46,60 @@ - - - - - - - - - - - - - - - - - + + - + - + - - + + - + + + + + + + + + + + + + + + + + + + + + + + - - - + + + - + \ No newline at end of file diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask2.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask2.bpmn20.xml index 3e76acb..7f5b7f8 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask2.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask2.bpmn20.xml @@ -1,6 +1,6 @@ - - + + SequenceFlow_0l4pbmo @@ -33,17 +33,10 @@ - + - - - - - - - @@ -53,49 +46,56 @@ - - - - - - - - - - - - - - - - - + + - + - + - - + + - + + + + + + + + + + + + + + + + + + + + + + + - - - + + + diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask3.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask3.bpmn20.xml index 5372dfa..299c9a7 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask3.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask3.bpmn20.xml @@ -1,6 +1,6 @@ - - + + SequenceFlow_0l4pbmo @@ -33,17 +33,10 @@ - + - - - - - - - @@ -53,49 +46,56 @@ - - - - - - - - - - - - - - - - - + + - + - + - - + + - + + + + + + + + + + + + + + + + + + + + + + + - - - + + + diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask4.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask4.bpmn20.xml index f564c74..690ae48 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask4.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/StartExternalTask4.bpmn20.xml @@ -1,6 +1,6 @@ - - + + SequenceFlow_0l4pbmo @@ -33,17 +33,10 @@ - + - - - - - - - @@ -53,49 +46,56 @@ - - - - - - - - - - - - - - - - - + + - + - + - - + + - + + + + + + + + + + + + + + + + + + + + + + + - - - + + + diff --git a/camunda-bpm-camel-common-tests/src/main/resources/process/StartProcessFromRoute.bpmn20.xml b/camunda-bpm-camel-common-tests/src/main/resources/process/StartProcessFromRoute.bpmn20.xml index 33def1d..6ec6b56 100644 --- a/camunda-bpm-camel-common-tests/src/main/resources/process/StartProcessFromRoute.bpmn20.xml +++ b/camunda-bpm-camel-common-tests/src/main/resources/process/StartProcessFromRoute.bpmn20.xml @@ -1,63 +1,63 @@ - - + + SequenceFlow_2 - - + + SequenceFlow_2 SequenceFlow_4 SequenceFlow_3 - + SequenceFlow_4 SequenceFlow_3 - - + + - + - + + + + - + - + - - + + - - + + - + - - - - - - - + + + + - - - - + + + + - \ No newline at end of file + diff --git a/camunda-bpm-camel-common/pom.xml b/camunda-bpm-camel-common/pom.xml index cc55c8f..da74e51 100644 --- a/camunda-bpm-camel-common/pom.xml +++ b/camunda-bpm-camel-common/pom.xml @@ -37,9 +37,8 @@ test - junit - junit - ${junit.version} + org.junit.jupiter + junit-jupiter test @@ -48,18 +47,6 @@ ${mockito.version} test - - org.powermock - powermock-module-junit4 - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} - test - org.assertj assertj-core @@ -71,14 +58,12 @@ - maven-jar-plugin + maven-surefire-plugin + 2.22.2 - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - + - org.apache.felix maven-bundle-plugin diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelService.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelService.java index 09aad58..53f57b2 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelService.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelService.java @@ -31,14 +31,14 @@ public interface CamelService { * an Camel {@link org.apache.camel.Endpoint} URI * * @exception Exception BpmnError: Raises business error in workflow allowing boundary error handling - * Any other cheched or unchecked exception raises technical error stopping workflow at service task + * Any other checked or unchecked exception raises technical error stopping workflow at service task * * @return the result of the execution of the Camel route */ - public Object sendTo(String endpointUri) throws Exception; + Object sendTo(String endpointUri) throws Exception; /** - * Sends the specified process instance variables as a map to an Camel + * Sends the specified process instance variables as a map to a Camel * {@link org.apache.camel.Endpoint} * * Example usage in a ServiceTask expression: @@ -52,14 +52,14 @@ public interface CamelService { * null value sends all * * @exception Exception BpmnError: Raises business error in workflow allowing boundary error handling - * Any other cheched or unchecked exception raises technical error stopping workflow at service task + * Any other checked or unchecked exception raises technical error stopping workflow at service task * * @return the result of the execution of the Camel route */ - public Object sendTo(String endpointUri, String processVariables) throws Exception; + Object sendTo(String endpointUri, String processVariables) throws Exception; /** - * Sends the specified process instance variables as a map to an Camel + * Sends the specified process instance variables as a map to a Camel * {@link org.apache.camel.Endpoint} and provide correlationId for callback * * Example usage in a ServiceTask expression: @@ -77,10 +77,10 @@ public interface CamelService { * variable which is used for correlation * * @exception Exception BpmnError: Raises business error in workflow allowing boundary error handling - * Any other cheched or unchecked exception raises technical error stopping workflow at service task + * Any other checked or unchecked exception raises technical error stopping workflow at service task * * @return the result of the execution of the Camel route */ - public Object sendTo(String endpointUri, String processVariables, - String correlationKey) throws Exception; + Object sendTo(String endpointUri, String processVariables, String correlationKey) + throws Exception; } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelServiceCommonImpl.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelServiceCommonImpl.java index c8918da..541cf53 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelServiceCommonImpl.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamelServiceCommonImpl.java @@ -24,8 +24,6 @@ import java.util.Map; import java.util.Set; -import javax.management.RuntimeErrorException; - import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; @@ -60,7 +58,7 @@ public Object sendTo(String endpointUri, String processVariables, String correlationId) throws Exception { Collection vars; if (processVariables == null) { - vars = new LinkedList(); + vars = new LinkedList<>(); ActivityExecution execution = Context.getBpmnExecutionContext() .getExecution(); final Set variableNames = execution.getVariableNames(); @@ -69,7 +67,7 @@ public Object sendTo(String endpointUri, String processVariables, vars.add(variableName + "?"); } } - } else if ("".equals(processVariables)) { + } else if (processVariables.isEmpty()) { vars = Collections.emptyList(); } else { vars = Arrays.asList(processVariables.split("\\s*,\\s*")); @@ -77,58 +75,61 @@ public Object sendTo(String endpointUri, String processVariables, return sendToInternal(endpointUri, vars, correlationId); } - private Object sendToInternal(String endpointUri, + private Object sendToInternal( + String endpointUri, Collection variables, String correlationKey) throws Exception { - ActivityExecution execution = (ActivityExecution) Context - .getBpmnExecutionContext().getExecution(); - Map variablesToSend = new HashMap(); - for (String var : variables) { + ActivityExecution execution = Context.getBpmnExecutionContext().getExecution(); + Map variablesToSend = new HashMap<>(); + for (String variable : variables) { Object value; - if (var.endsWith("?")) { - value = execution.getVariable(var.substring(0, var.length() - 1)); + if (variable.endsWith("?")) { + value = execution.getVariable(variable.substring(0, variable.length() - 1)); } else { - value = execution.getVariable(var); + value = execution.getVariable(variable); if (value == null) { - throw new IllegalArgumentException("Process variable '" + var - + "' no found!"); + throw new IllegalArgumentException("Process variable '" + variable + "' no found!"); } } - variablesToSend.put(var, value); + variablesToSend.put(variable, value); } - log.debug("Sending process variables '{}' as a map to Camel endpoint '{}'", - variablesToSend, endpointUri); - ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); - String businessKey = execution.getBusinessKey(); + log.debug( + "Sending process variables '{}' as a map to Camel endpoint '{}'", + variablesToSend, + endpointUri); + try (ProducerTemplate producerTemplate = camelContext.createProducerTemplate()) { + String businessKey = execution.getBusinessKey(); + + Exchange exchange = new DefaultExchange(camelContext); + exchange.setProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID, execution.getProcessInstanceId()); + if (businessKey != null) { + exchange.setProperty(EXCHANGE_HEADER_BUSINESS_KEY, businessKey); + } + if (correlationKey != null) { + exchange.setProperty(EXCHANGE_HEADER_CORRELATION_KEY, correlationKey); + } + exchange.getIn().setBody(variablesToSend); + exchange.setPattern(ExchangePattern.InOut); + Exchange send = producerTemplate.send(endpointUri, exchange); + + // Exception handling + // Propagate BpmnError back from camel route, + // all other exceptions will cause workflow to stop as a technical error + // https://docs.camunda.org/get-started/rpa/error-handling/ + // https://docs.camunda.org/manual/7.15/reference/bpmn20/events/error-events/ + if (null != send.getException()) { + // Explicit BPMN business error, workflow has a chance to handle on boundary event, throw as is + // Note that this can terminate a process instance if no handling is defined in the model (https://docs.camunda.org/manual/latest/user-guide/process-engine/delegation-code/#throw-bpmn-errors-from-listeners) + if (send.getException() instanceof BpmnError) { + throw send.getException(); + } - Exchange exchange = new DefaultExchange(camelContext); - exchange.setProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID, - execution.getProcessInstanceId()); - if (businessKey != null) { - exchange.setProperty(EXCHANGE_HEADER_BUSINESS_KEY, businessKey); - } - if (correlationKey != null) { - exchange.setProperty(EXCHANGE_HEADER_CORRELATION_KEY, correlationKey); - } - exchange.getIn().setBody(variablesToSend); - exchange.setPattern(ExchangePattern.InOut); - Exchange send = producerTemplate.send(endpointUri, exchange); - - // Exception handling - // Propogate BpmnError back from camel route, - // all other exceptions will cause workflow to stop as a technical error - // https://docs.camunda.org/get-started/rpa/error-handling/ - // https://docs.camunda.org/manual/7.15/reference/bpmn20/events/error-events/ - if (null != send.getException()){ - // Explicit BPMN business error, workflow has a chance to handle on boundry event, throw as is - // Note that this can terminate a process instance if no handling is defined in the model (https://docs.camunda.org/manual/latest/user-guide/process-engine/delegation-code/#throw-bpmn-errors-from-listeners) - if (send.getException() instanceof BpmnError) throw ((BpmnError)send.getException()); - - // otherwise simply throw the exception, leads to incident in process instance - throw send.getException(); - } + // otherwise simply throw the exception, leads to incident in process instance + throw send.getException(); + } - return send.getIn().getBody(); + return send.getIn().getBody(); + } } public abstract void setProcessEngine(ProcessEngine processEngine); diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamundaUtils.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamundaUtils.java index b585ae9..df538ff 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamundaUtils.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/CamundaUtils.java @@ -17,17 +17,19 @@ import org.camunda.bpm.engine.OptimisticLockingException; public class CamundaUtils { + private static final long SLEEP_IN_MS = 250; + private static final int DEFAULT_TIMES = 1000; - private static long sleepInMs = 250; - private static int defaultTimes = 1000; + private CamundaUtils() { + throw new UnsupportedOperationException("This class cannot be instantiated"); + } public static V retryIfOptimisticLockingException(final Callable action) { - return retryIfOptimisticLockingException(defaultTimes, action); + return retryIfOptimisticLockingException(DEFAULT_TIMES, action); } public static V retryIfOptimisticLockingException(int times, final Callable action) { - - OptimisticLockingException lastException = null; + OptimisticLockingException lastException; do { try { return action.call(); @@ -41,25 +43,15 @@ public static V retryIfOptimisticLockingException(int times, final Callable< } try { - Thread.sleep(sleepInMs); + Thread.sleep(SLEEP_IN_MS); } catch (InterruptedException e) { - // never minde + // never mind } } while (times > 0); - - final StringBuilder message = new StringBuilder(); - message.append("Event after "); - message.append(times); - message.append(" attempts (every delayed for "); - message.append(sleepInMs); - message.append("ms) an OptimisticLockingException is thrown!"); - if (lastException != null) { - message.append(" message='"); - message.append(lastException.getMessage()); - message.append('\''); - } - throw new OptimisticLockingException(message.toString()); - + throw new OptimisticLockingException( + "Event after " + times + " attempts (every delayed for " + SLEEP_IN_MS + "ms)" + + " an OptimisticLockingException is thrown!" + + " message='" + lastException.getMessage() + '\''); } } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/ExchangeUtils.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/ExchangeUtils.java index d256d93..5e47aae 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/ExchangeUtils.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/ExchangeUtils.java @@ -28,9 +28,12 @@ * @author Bernd Ruecker */ public class ExchangeUtils { - private static final Logger LOG = LoggerFactory.getLogger(ExchangeUtils.class); + private ExchangeUtils() { + throw new UnsupportedOperationException("This class cannot be instantiated"); + } + /** * Copies variables from Camel into the process engine. * @@ -44,16 +47,13 @@ public class ExchangeUtils { * The Camel Exchange object * @param parameters * Parameters as defined in the docs - * @return A Map containing all of the variables to be used + * @return A Map containing all the variables to be used * in the process engine */ - @SuppressWarnings("rawtypes") public static Map prepareVariables(Exchange exchange, Map parameters) { - Map processVariables = new HashMap(); - + Map processVariables = new HashMap<>(); Object camelBody = exchange.getIn().getBody(); if (camelBody instanceof String) { - // If the COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER was passed // the value of it // is taken as variable to store the (string) body in @@ -62,22 +62,18 @@ public static Map prepareVariables(Exchange exchange, Map) { - - Map camelBodyMap = (Map) camelBody; - for (Map.Entry e : camelBodyMap.entrySet()) { + } else if (camelBody instanceof Map camelBodyMap) { + for (Map.Entry e : camelBodyMap.entrySet()) { if (e.getKey() instanceof String) { processVariables.put((String) e.getKey(), e.getValue()); } } - - } else if (camelBody != null) { - LOG.warn("unkown type of camel body - not handed over to process engine: " + camelBody.getClass()); + } else if (camelBody != null && LOG.isWarnEnabled()) { + LOG.warn( + "unknown type of camel body - not handed over to process engine: {}", + camelBody.getClass()); } - return processVariables; } } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/UriUtils.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/UriUtils.java index f1f35d0..4e0c10d 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/UriUtils.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/common/UriUtils.java @@ -28,17 +28,13 @@ public static class ParsedUri { * or component prefix */ public ParsedUri(final String remainingUri) { - this.remainingUri = remainingUri; - components = parseUri(remainingUri); - if ((components == null) || (components.length == 0)) { + if (components.length == 0) { throw new RuntimeException("Cannot create a producer for URI '" + remainingUri + "'"); } - final String identifier = components[0]; type = UriType.typeByIdentifier(identifier); - } public String[] getComponents() { @@ -48,7 +44,6 @@ public String[] getComponents() { public UriType getType() { return type; } - /** * @return the remaining part of the URI without the query parameters or * component prefix @@ -56,38 +51,33 @@ public UriType getType() { public String getRemainingUri() { return remainingUri; } - } public enum UriType { + START_PR("start"), + SEND_SIGNAL("signal"), + SEND_MESSAGE("message"), + POLL_EXTERNAL_TASKS("poll-externalTasks"), + PROCESS_EXTERNAL_TASK("async-externalTask"); - StartProcess("start"), SendSignal("signal"), SendMessage("message"), - PollExternalTasks("poll-externalTasks"), ProcessExternalTask("async-externalTask"); - - private String identifier; + private final String identifier; UriType(final String identifier) { this.identifier = identifier; } public static UriType typeByIdentifier(final String identifier) { - for (final UriType type : values()) { if (type.identifier.equals(identifier)) { return type; } } - throw new RuntimeException("Cannot create a producer for identifier '" + identifier + "'"); - } - }; + } public static String[] parseUri(String remainingUri) { - return remainingUri.split("/"); - } - } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmComponent.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmComponent.java index 2af5bb0..8808799 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmComponent.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmComponent.java @@ -29,7 +29,6 @@ * @author Rafael Cordones (@rafacm) */ public class CamundaBpmComponent extends DefaultComponent { - final Logger log = LoggerFactory.getLogger(CamundaBpmComponent.class); protected ProcessEngine processEngine; @@ -49,18 +48,15 @@ public void close() { } @Override - protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { - + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) { final ParsedUri parsedUri = new ParsedUri(remaining); - switch (parsedUri.getType()) { - case PollExternalTasks: - return new CamundaBpmPollExternalTasksEndpointImpl(uri, this, parameters); - case ProcessExternalTask: - return new CamundaBpmProcessExternalTaskEndpointImpl(uri, this, parameters); - default: - return new CamundaBpmEndpointDefaultImpl(uri, parsedUri, this, parameters); - } - + return switch (parsedUri.getType()) { + case POLL_EXTERNAL_TASKS -> + new CamundaBpmPollExternalTasksEndpointImpl(uri, this, parameters); + case PROCESS_EXTERNAL_TASK -> + new CamundaBpmProcessExternalTaskEndpointImpl(uri, this, parameters); + default -> new CamundaBpmEndpointDefaultImpl(uri, parsedUri, this, parameters); + }; } public ProcessEngine getProcessEngine() { diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmConstants.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmConstants.java index 2aa1385..e1a5d53 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmConstants.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmConstants.java @@ -33,34 +33,35 @@ public final class CamundaBpmConstants { public static final String EXCHANGE_RESPONSE_IGNORE = "CamundaBpmExternalTaskIgnore"; /* Apache Camel URI parameters */ - public final static String PROCESS_DEFINITION_KEY_PARAMETER = "processDefinitionKey"; - public final static String TOPIC_PARAMETER = "topic"; - public final static String WORKERID_PARAMETER = "workerId"; - public final static String VARIABLESTOFETCH_PARAMETER = "variablesToFetch"; - public final static String DESERIALIZEVARIABLES_PARAMETER = "deserializeVariables"; - public final static boolean DESERIALIZEVARIABLES_DEFAULT = true; - public final static String MAXTASKSPERPOLL_PARAMETER = "maxTasksPerPoll"; - public final static int MAXTASKSPERPOLL_DEFAULT = 5; - public final static String ASYNC_PARAMETER = "async"; - public final static boolean ASYNC_DEFAULT = false; - public final static String ONCOMPLETION_PARAMETER = "onCompletion"; - public final static boolean ONCOMPLETION_DEFAULT = false; - public final static String LOCKDURATION_PARAMETER = "lockDuration"; - public final static long LOCKDURATION_DEFAULT = 60000; - public final static String RETRIES_PARAMETER = "retries"; - public final static String RETRYTIMEOUT_PARAMETER = "retryTimeout"; - public final static long RETRYTIMEOUT_DEFAULT = 500; - public final static String RETRYTIMEOUTS_PARAMETER = "retryTimeouts"; - public final static String MESSAGE_NAME_PARAMETER = "messageName"; - public final static String CORRELATION_KEY_NAME_PARAMETER = "correlationKeyName"; - public final static String ACTIVITY_ID_PARAMETER = "activityId"; - public final static String COPY_MESSAGE_PROPERTIES_PARAMETER = "copyProperties"; - public final static String COPY_MESSAGE_HEADERS_PARAMETER = "copyHeaders"; - public final static String COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER = "copyBodyAsVariable"; - public final static String COPY_PROCESS_VARIABLES_TO_OUT_BODY_PARAMETER = "copyVariablesToOutBody"; + public static final String PROCESS_DEFINITION_KEY_PARAMETER = "processDefinitionKey"; + public static final String TOPIC_PARAMETER = "topic"; + public static final String WORKERID_PARAMETER = "workerId"; + public static final String VARIABLESTOFETCH_PARAMETER = "variablesToFetch"; + public static final String DESERIALIZEVARIABLES_PARAMETER = "deserializeVariables"; + public static final boolean DESERIALIZEVARIABLES_DEFAULT = true; + public static final String MAXTASKSPERPOLL_PARAMETER = "maxTasksPerPoll"; + public static final int MAXTASKSPERPOLL_DEFAULT = 5; + public static final String ASYNC_PARAMETER = "async"; + public static final boolean ASYNC_DEFAULT = false; + public static final String ONCOMPLETION_PARAMETER = "onCompletion"; + public static final boolean ONCOMPLETION_DEFAULT = false; + public static final String LOCKDURATION_PARAMETER = "lockDuration"; + public static final long LOCKDURATION_DEFAULT = 60000; + public static final String RETRIES_PARAMETER = "retries"; + public static final String RETRYTIMEOUT_PARAMETER = "retryTimeout"; + public static final long RETRYTIMEOUT_DEFAULT = 500; + public static final String RETRYTIMEOUTS_PARAMETER = "retryTimeouts"; + public static final String MESSAGE_NAME_PARAMETER = "messageName"; + public static final String CORRELATION_KEY_NAME_PARAMETER = "correlationKeyName"; + public static final String ACTIVITY_ID_PARAMETER = "activityId"; + public static final String COPY_MESSAGE_PROPERTIES_PARAMETER = "copyProperties"; + public static final String COPY_MESSAGE_HEADERS_PARAMETER = "copyHeaders"; + public static final String COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER = "copyBodyAsVariable"; + public static final String COPY_PROCESS_VARIABLES_TO_OUT_BODY_PARAMETER = "copyVariablesToOutBody"; private CamundaBpmConstants() { - } // prevent instantiation of helper class + throw new UnsupportedOperationException("This class cannot be instantiated"); + } public static String camundaBpmUri(String path) { return CAMUNDA_BPM_CAMEL_URI_SCHEME + ":" + path; diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpoint.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpoint.java index b24bad6..a6d97ef 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpoint.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpoint.java @@ -16,7 +16,5 @@ import org.camunda.bpm.engine.ProcessEngine; public interface CamundaBpmEndpoint extends Endpoint { - ProcessEngine getProcessEngine(); - } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpointDefaultImpl.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpointDefaultImpl.java index 57fcad1..7adb9c6 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpointDefaultImpl.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmEndpointDefaultImpl.java @@ -35,11 +35,10 @@ * @author Ryan Johnston (@rjfsu), Tijs Rademakers */ public class CamundaBpmEndpointDefaultImpl extends DefaultEndpoint implements CamundaBpmEndpoint { - private static final Logger LOG = LoggerFactory.getLogger(CamundaBpmEndpointDefaultImpl.class); - private CamundaBpmComponent component; - private Map parameters; + private final CamundaBpmComponent component; + private final Map parameters; private final ParsedUri uri; public CamundaBpmEndpointDefaultImpl(String uri, ParsedUri parsedUri, CamundaBpmComponent component, @@ -54,14 +53,15 @@ public ProcessEngine getProcessEngine() { return this.component.getProcessEngine(); } - public Producer createProducer() throws Exception { + public Producer createProducer() { return CamundaBpmProducerFactory.createProducer(this, this.uri, this.parameters); } - public Consumer createConsumer(Processor processor) throws Exception { + public Consumer createConsumer(Processor processor) { return null; } + @Override public boolean isSingleton() { return true; } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmPollExternalTasksEndpointImpl.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmPollExternalTasksEndpointImpl.java index a2b7f46..3771915 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmPollExternalTasksEndpointImpl.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmPollExternalTasksEndpointImpl.java @@ -45,11 +45,10 @@ import org.slf4j.LoggerFactory; public class CamundaBpmPollExternalTasksEndpointImpl extends DefaultPollingEndpoint implements CamundaBpmEndpoint { - private static final Logger LOG = LoggerFactory.getLogger( CamundaBpmPollExternalTasksEndpointImpl.class.getCanonicalName()); - private CamundaBpmComponent component; + private final CamundaBpmComponent component; // parameters private final String topic; @@ -65,11 +64,8 @@ public class CamundaBpmPollExternalTasksEndpointImpl extends DefaultPollingEndpo public CamundaBpmPollExternalTasksEndpointImpl(final String endpointUri, final CamundaBpmComponent component, final Map parameters) { - super(endpointUri, component); - this.component = component; - if (parameters.containsKey(TOPIC_PARAMETER)) { this.topic = (String) parameters.remove(TOPIC_PARAMETER); } else { @@ -127,7 +123,7 @@ public CamundaBpmPollExternalTasksEndpointImpl(final String endpointUri, final C if (parameters.containsKey(VARIABLESTOFETCH_PARAMETER)) { final String variables = (String) parameters.remove(VARIABLESTOFETCH_PARAMETER); if (variables.trim().isEmpty()) { - variablesToFetch = new LinkedList(); + variablesToFetch = new LinkedList<>(); } else { variablesToFetch = StringUtil.splitListBySeparator(variables, ","); } @@ -146,7 +142,6 @@ public CamundaBpmPollExternalTasksEndpointImpl(final String endpointUri, final C } else { this.deserializeVariables = DESERIALIZEVARIABLES_DEFAULT; } - } @Override @@ -157,7 +152,6 @@ public void close() { @Override public Consumer createConsumer(Processor processor) throws Exception { - final BatchConsumer consumer; if (getScheduledExecutorService() != null) { consumer = new BatchConsumer(this, @@ -189,38 +183,25 @@ public Consumer createConsumer(Processor processor) throws Exception { consumer.setMaxMessagesPerPoll(maxTasksPerPoll); return consumer; - } @Override - public PollingConsumer createPollingConsumer() throws Exception { - + public PollingConsumer createPollingConsumer() { return null; - // return new - // org.camunda.bpm.camel.component.externaltasks.PollingConsumer(this, - // topic); - } @Override - public Producer createProducer() throws Exception { - + public Producer createProducer() { return null; - } @Override public boolean isSingleton() { - return true; - } @Override public ProcessEngine getProcessEngine() { - return component.getProcessEngine(); - } - } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmProcessExternalTaskEndpointImpl.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmProcessExternalTaskEndpointImpl.java index 09949fd..6e9f0e7 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmProcessExternalTaskEndpointImpl.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/CamundaBpmProcessExternalTaskEndpointImpl.java @@ -30,13 +30,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class CamundaBpmProcessExternalTaskEndpointImpl extends ProcessorEndpoint implements - CamundaBpmEndpoint { - +public class CamundaBpmProcessExternalTaskEndpointImpl extends ProcessorEndpoint + implements CamundaBpmEndpoint { private static final Logger LOG = LoggerFactory.getLogger( CamundaBpmProcessExternalTaskEndpointImpl.class); - private CamundaBpmComponent component; + private final CamundaBpmComponent component; // parameters private final String topic; @@ -49,9 +48,7 @@ public class CamundaBpmProcessExternalTaskEndpointImpl extends ProcessorEndpoint public CamundaBpmProcessExternalTaskEndpointImpl(final String endpointUri, final CamundaBpmComponent component, final Map parameters) { - super(endpointUri, component); - this.component = component; if (parameters.containsKey(TOPIC_PARAMETER)) { @@ -95,14 +92,11 @@ public CamundaBpmProcessExternalTaskEndpointImpl(final String endpointUri, } else { this.workerId = null; } - } @Override public boolean isSingleton() { - return true; - } @Override @@ -113,17 +107,20 @@ public void close() { @Override public ProcessEngine getProcessEngine() { - return component.getProcessEngine(); - } @Override - protected Processor createProcessor() throws Exception { - - return new TaskProcessor(this, topic, retries, retryTimeout, retryTimeouts, true, onCompletion, + protected Processor createProcessor() { + return new TaskProcessor( + this, + topic, + retries, + retryTimeout, + retryTimeouts, + true, + onCompletion, workerId); - } } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/BatchConsumer.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/BatchConsumer.java index 0c2d3c7..f2ae896 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/BatchConsumer.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/BatchConsumer.java @@ -19,11 +19,9 @@ import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_TASK; import java.lang.reflect.Method; -import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; -import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import org.apache.camel.*; @@ -55,14 +53,12 @@ public class BatchConsumer extends ScheduledBatchPollingConsumer { private final TaskProcessor taskProcessor; static { - try { deserializeVariablesMethod = ExternalTaskQueryTopicBuilder.class.getMethod( "enableCustomObjectDeserialization"); } catch (Exception e) { // ignore because the Camunda version below 7.6.0 is used } - } public static boolean systemKnowsDeserializationOfVariables() { @@ -73,9 +69,7 @@ public BatchConsumer(final CamundaBpmEndpoint endpoint, final Processor processo final long retryTimeout, final long[] retryTimeouts, final long lockDuration, final String topic, final boolean completeTask, final List variablesToFetch, final boolean deserializeVariables, final String workerId) { - super(endpoint, processor); - this.camundaEndpoint = endpoint; this.lockDuration = lockDuration; this.topic = topic; @@ -83,7 +77,6 @@ public BatchConsumer(final CamundaBpmEndpoint endpoint, final Processor processo this.variablesToFetch = variablesToFetch; this.deserializeVariables = deserializeVariables; this.workerId = workerId; - this.taskProcessor = new TaskProcessor(endpoint, topic, retries, @@ -92,16 +85,13 @@ public BatchConsumer(final CamundaBpmEndpoint endpoint, final Processor processo completeTask, true, workerId); - } public BatchConsumer(final CamundaBpmEndpoint endpoint, final Processor processor, final ScheduledExecutorService executor, final int retries, final long retryTimeout, final long[] retryTimeouts, final long lockDuration, final String topic, final boolean completeTask, final List variablesToFetch, final boolean deserializeVariables, final String workerId) { - super(endpoint, processor, executor); - this.camundaEndpoint = endpoint; this.lockDuration = lockDuration; this.topic = topic; @@ -109,7 +99,6 @@ public BatchConsumer(final CamundaBpmEndpoint endpoint, final Processor processo this.variablesToFetch = variablesToFetch; this.deserializeVariables = deserializeVariables; this.workerId = workerId; - this.taskProcessor = new TaskProcessor(endpoint, topic, retries, @@ -118,7 +107,6 @@ public BatchConsumer(final CamundaBpmEndpoint endpoint, final Processor processo completeTask, true, workerId); - } @Override @@ -129,13 +117,12 @@ public void close() { @Override public int processBatch(Queue exchanges) throws Exception { - int total = exchanges.size(); int answer = total; for (int index = 0; index < total && isBatchAllowed(); index++) { // only loop if we are started (allowed to run) - // use poll to remove the head so it does not consume memory even + // use poll to remove the head, so it does not consume memory even // after we have processed it Exchange exchange = (Exchange) exchanges.poll(); // add current index and total as properties @@ -155,29 +142,22 @@ public int processBatch(Queue exchanges) throws Exception { } // drain any in progress files as we are done with this batch - removeExcessiveInProgressTasks(CastUtils.cast((Queue) exchanges, Exchange.class), 0); + removeExcessiveInProgressTasks(CastUtils.cast(exchanges, Exchange.class), 0); return answer; - } private boolean processExchange(final Exchange exchange) throws Exception { - taskProcessor.process(exchange); final Processor currentProcessor = getProcessor(); - if (currentProcessor instanceof AsyncProcessor) { - ((AsyncProcessor) currentProcessor).process(exchange, new AsyncCallback() { - @Override - public void done(boolean doneSync) { - // we are not interested in this event - } + if (currentProcessor instanceof AsyncProcessor asyncProcessor) { + asyncProcessor.process(exchange, doneSync -> { + // we are not interested in this event }); } else { currentProcessor.process(exchange); } - return true; - } /** @@ -189,77 +169,62 @@ public void done(boolean doneSync) { * the limit */ protected void removeExcessiveInProgressTasks(Queue exchanges, int limit) { - while (exchanges.size() > limit) { // must remove last Exchange exchange = exchanges.poll(); releaseTask(exchange); } - } private void releaseTask(final Exchange exchange) { - - exchange.setProperty(Exchange.ROLLBACK_ONLY, Boolean.TRUE); + exchange.setRollbackOnly(true); taskProcessor.internalProcessing(exchange); - } private ExternalTaskService getExternalTaskService() { - return camundaEndpoint.getProcessEngine().getExternalTaskService(); - } protected int poll() throws Exception { - int messagesPolled = 0; - - PriorityQueue exchanges = new PriorityQueue( + PriorityQueue exchanges = new PriorityQueue<>( /* * default-value, unfortunately * PriorityQueue.DEFAULT_INITIAL_CAPACITY is private and the * constructor with one parameter of type Comparator is not * available in JSE 7 */ - 11, new Comparator() { - @Override - public int compare(Exchange o1, Exchange o2) { - Long prio1 = (Long) o1.getProperty(EXCHANGE_HEADER_PROCESS_PRIO, 0); - Long prio2 = (Long) o2.getProperty(EXCHANGE_HEADER_PROCESS_PRIO, 0); - return prio1.compareTo(prio2); - } + 11, (o1, o2) -> { + Long priority1 = + o1.getProperty(EXCHANGE_HEADER_PROCESS_PRIO, 0, Long.class); + Long priority2 = + o2.getProperty(EXCHANGE_HEADER_PROCESS_PRIO, 0, Long.class); + return priority1.compareTo(priority2); }); if (isPollAllowed()) { - final List tasks = CamundaUtils.retryIfOptimisticLockingException( - new Callable>() { - @Override - public List call() { - ExternalTaskQueryTopicBuilder query = getExternalTaskService() // - .fetchAndLock(maxMessagesPerPoll, workerId, true) // - .topic(topic, lockDuration) // - .variables(variablesToFetch); - if (deserializeVariables && (deserializeVariablesMethod != null)) { - try { - query = (ExternalTaskQueryTopicBuilder) deserializeVariablesMethod.invoke(query); - } catch (Exception e) { - throw new RuntimeCamelException(e); - } - } - return query.execute(); + () -> { + ExternalTaskQueryTopicBuilder query = getExternalTaskService() // + .fetchAndLock(maxMessagesPerPoll, workerId, true) // + .topic(topic, lockDuration) // + .variables(variablesToFetch); + if (deserializeVariables && (deserializeVariablesMethod != null)) { + try { + query = (ExternalTaskQueryTopicBuilder) deserializeVariablesMethod.invoke(query); + } catch (Exception e) { + throw new RuntimeCamelException(e); } - }); + } + return query.execute(); + }); messagesPolled = tasks.size(); for (final LockedExternalTask task : tasks) { - final ExchangePattern pattern = completeTask ? ExchangePattern.InOut : ExchangePattern.InOnly; - ExtendedExchange exchange = getEndpoint().createExchange(pattern).adapt(ExtendedExchange.class); - - exchange.setFromEndpoint(getEndpoint()); + Exchange exchange = getEndpoint().createExchange(pattern); + exchange.getExchangeExtension().setFromEndpoint(getEndpoint()); exchange.setExchangeId(task.getWorkerId() + "/" + task.getId()); exchange.setProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID, task.getProcessInstanceId()); exchange.setProperty(EXCHANGE_HEADER_PROCESS_DEFINITION_KEY, task.getProcessDefinitionKey()); @@ -269,23 +234,15 @@ public List call() { final Message in = exchange.getIn(); in.setHeader(EXCHANGE_HEADER_TASK, task); in.setBody(task.getVariables()); - exchanges.add(exchange); - } - } - processBatch(CastUtils.cast(exchanges)); - return messagesPolled; - } public int getTimeout() { - return timeout; - } /** @@ -302,9 +259,6 @@ public int getTimeout() { * the timeout value */ public void setTimeout(int timeout) { - this.timeout = timeout; - } - } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/NoSuchExternalTaskException.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/NoSuchExternalTaskException.java index 803a896..6261cdd 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/NoSuchExternalTaskException.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/NoSuchExternalTaskException.java @@ -15,13 +15,8 @@ import org.apache.camel.RuntimeCamelException; public class NoSuchExternalTaskException extends RuntimeCamelException { - private static final long serialVersionUID = 1L; - public NoSuchExternalTaskException() { - // nothing to do - } - public NoSuchExternalTaskException(String message) { super(message); } @@ -33,5 +28,4 @@ public NoSuchExternalTaskException(Throwable cause) { public NoSuchExternalTaskException(String message, Throwable cause) { super(message, cause); } - } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/SetExternalTaskRetries.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/SetExternalTaskRetries.java index 12a7b99..25fb7f6 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/SetExternalTaskRetries.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/SetExternalTaskRetries.java @@ -34,9 +34,6 @@ @Target(value = { ElementType.TYPE }) @Retention(value = RetentionPolicy.RUNTIME) public @interface SetExternalTaskRetries { - - public int retries(); - - public boolean relative() default false; - + int retries(); + boolean relative() default false; } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/TaskProcessor.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/TaskProcessor.java index 249e725..d18ef85 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/TaskProcessor.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/externaltasks/TaskProcessor.java @@ -19,6 +19,7 @@ import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_RESPONSE_IGNORE; import java.util.Map; +import java.util.Optional; import java.util.concurrent.Callable; import org.apache.camel.*; @@ -32,7 +33,6 @@ import org.slf4j.LoggerFactory; public class TaskProcessor implements Processor { - private static final Logger LOG = LoggerFactory.getLogger(TaskProcessor.class.getCanonicalName()); private final CamundaBpmEndpoint camundaEndpoint; @@ -49,7 +49,6 @@ public class TaskProcessor implements Processor { public TaskProcessor(final CamundaBpmEndpoint endpoint, final String topic, final int retries, final long retryTimeout, final long[] retryTimeouts, final boolean completeTask, final boolean onCompletion, final String workerId) { - this.camundaEndpoint = endpoint; this.retries = retries; this.retryTimeout = retryTimeout; @@ -58,32 +57,23 @@ public TaskProcessor(final CamundaBpmEndpoint endpoint, final String topic, fina this.onCompletion = onCompletion; this.workerId = workerId; this.topic = topic; - } private ExternalTaskService getExternalTaskService() { - return camundaEndpoint.getProcessEngine().getExternalTaskService(); - } @Override public void process(final Exchange exchange) { - if (!onCompletion) { - internalProcessing(exchange); - } else { - // set headers only for "on-completion" processing because // otherwise the service doing something is already done - // and therefore cannot use this in-headers any more. + // and therefore cannot use this in-headers anymore. setInHeaders(exchange); - final TaskProcessor taskProcessor = this; - exchange.adapt(ExtendedExchange.class).addOnCompletion(new Synchronization() { - + exchange.getExchangeExtension().addOnCompletion(new Synchronization() { @Override public void onFailure(final Exchange exchange) { taskProcessor.internalProcessing(exchange); @@ -93,33 +83,26 @@ public void onFailure(final Exchange exchange) { public void onComplete(final Exchange exchange) { taskProcessor.internalProcessing(exchange); } - }); - } - } private void setInHeaders(final Exchange exchange) { - final Message in = getInMessage(exchange); final String taskId = getExternalTaskId(in); final ExternalTask task = getExternalTask(taskId); final SetExternalTaskRetries annotation = findAnnotationByException(exchange.getException()); - final int retries = retriesLeft(task.getRetries(), annotation); + final int retriesLeft = retriesLeft(task.getRetries(), annotation); final int attemptsStarted = attemptsStarted(task.getRetries(), annotation); - in.setHeader(EXCHANGE_HEADER_RETRIESLEFT, retries); + in.setHeader(EXCHANGE_HEADER_RETRIESLEFT, retriesLeft); in.setHeader(EXCHANGE_HEADER_ATTEMPTSSTARTED, attemptsStarted); - } @SuppressWarnings("unchecked") void internalProcessing(final Exchange exchange) { - final Message in = getInMessage(exchange); - String currentTaskId; ExternalTask currentTask; try { @@ -134,103 +117,84 @@ void internalProcessing(final Exchange exchange) { final ExternalTaskService externalTaskService = getExternalTaskService(); - final Message out; + final Message message; if (onCompletion) { // 'process-externalTask' at the end of a route does not have any // output // - only input which was any proceeder's output. - out = exchange.getOut(); + message = exchange.getMessage(); } else { - out = in; + message = in; } // failure if (exchange.isFailed()) { - if (task == null) { LOG.warn( - "Processing failed but the task seems to be already processed - will do nothing! Camnda external task id: '" - + taskId + "'"); + "Processing failed but the task seems to be already processed - will do nothing!" + + " Camunda external task id: '{}", taskId); return; } - final Exception exception = exchange.getException(); final SetExternalTaskRetries annotation = findAnnotationByException(exchange.getException()); - final int retries = retriesLeft(task.getRetries(), annotation); + final int retriesLeft = retriesLeft(task.getRetries(), annotation); final long calculatedTimeout = calculateTimeout(task.getRetries(), annotation); - - CamundaUtils.retryIfOptimisticLockingException(new Callable() { - @Override - public Void call() { - externalTaskService.handleFailure(task.getId(), - task.getWorkerId(), - exception != null ? exception.getMessage() : "task failed", - retries, - calculatedTimeout); - return null; - } + CamundaUtils.retryIfOptimisticLockingException((Callable) () -> { + externalTaskService.handleFailure(task.getId(), + task.getWorkerId(), + exception != null ? exception.getMessage() : "task failed", + retriesLeft, + calculatedTimeout); + return null; }); - - } else - // do not complete task in any way? - if (!completeTask) { - return; - } else - // bpmn error - if ((out != null) && (out.getBody() != null) && (out.getBody() instanceof String)) { - - final String errorCode = out.getBody(String.class); - - if (task == null) { - LOG.warn("Should complete the external task with BPM error '" + errorCode - + "' but the task seems to be already processed - will do nothing! Camnda external task id: '" - + taskId + "'"); - return; - } - - // Ignore if service advises us to do so. - if (errorCode.equals(EXCHANGE_RESPONSE_IGNORE)) { - return; - } - - CamundaUtils.retryIfOptimisticLockingException(new Callable() { - @Override - public Void call() { - externalTaskService.handleBpmnError(task.getId(), task.getWorkerId(), errorCode); - return null; + } else if (completeTask) { + if ((message != null) && (message.getBody() != null) && (message.getBody() instanceof String)) { + // bpmn error + final String errorCode = message.getBody(String.class); + if (task == null) { + LOG.warn("Should complete the external task with BPM error '{}'" + + " but the task seems to be already processed - will do nothing!" + + " Camunda external task id: '{}'", errorCode, taskId); + return; } - }); - } else - // success - { - if (task == null) { - LOG.warn("Should complete the external task but the task seems to be " - + "already processed - will do nothing! Camnda external task id: '" + taskId + "'"); - return; - } + // Ignore if service advises us to do so. + if (errorCode.equals(EXCHANGE_RESPONSE_IGNORE)) { + return; + } - final Map variablesToBeSet; - if ((out != null) && (out.getBody() != null) && (out.getBody() instanceof Map)) { - variablesToBeSet = out.getBody(Map.class); + CamundaUtils.retryIfOptimisticLockingException((Callable) () -> { + externalTaskService.handleBpmnError(task.getId(), task.getWorkerId(), errorCode); + return null; + }); } else { - variablesToBeSet = null; - } + // success + if (task == null) { + LOG.warn( + "Should complete the external task but the task seems to be already processed - will do nothing!" + + " Camunda external task id: '{}'", + taskId); + return; + } - CamundaUtils.retryIfOptimisticLockingException(new Callable() { - @Override - public Void call() { - if (variablesToBeSet != null) { - externalTaskService.complete(task.getId(), task.getWorkerId(), variablesToBeSet); - } else { - externalTaskService.complete(task.getId(), task.getWorkerId()); - } - return null; + final Map variablesToBeSet; + if ((message != null) && (message.getBody() != null) && (message.getBody() instanceof Map)) { + variablesToBeSet = message.getBody(Map.class); + } else { + variablesToBeSet = null; } - }); - } + CamundaUtils.retryIfOptimisticLockingException((Callable) () -> { + if (variablesToBeSet != null) { + externalTaskService.complete(task.getId(), task.getWorkerId(), variablesToBeSet); + } else { + externalTaskService.complete(task.getId(), task.getWorkerId()); + } + return null; + }); + } + } } private Message getInMessage(final Exchange exchange) { @@ -242,7 +206,6 @@ private Message getInMessage(final Exchange exchange) { } private ExternalTask getExternalTask(final String taskId) { - if (taskId == null) { return null; } @@ -265,32 +228,19 @@ private ExternalTask getExternalTask(final String taskId) { + "' is not available any more. For details see '" + "https://github.com/camunda/camunda-bpm-camel#camunda-bpmasync-externaltask-processing-outstanding-external-tasks'."); } - return task; - } private String getExternalTaskId(final Message in) { - final LockedExternalTask lockedTask = in.getHeader(EXCHANGE_HEADER_TASK, LockedExternalTask.class); final String lockedTaskId = in.getHeader(EXCHANGE_HEADER_TASKID, String.class); - final String taskId; - - if (lockedTask != null) { - taskId = lockedTask.getId(); - } else if (lockedTaskId != null) { - taskId = lockedTaskId; - } else { - taskId = null; - } - - return taskId; - + return Optional.ofNullable(lockedTask) + .map(LockedExternalTask::getId) + .orElse(lockedTaskId); } public int retriesLeft(final Integer taskRetries, final SetExternalTaskRetries annotation) { - final int currentRetries; final boolean decreaseCurrentRetriesByOne; if (taskRetries == null) { @@ -300,29 +250,22 @@ public int retriesLeft(final Integer taskRetries, final SetExternalTaskRetries a currentRetries = taskRetries; decreaseCurrentRetriesByOne = true; } - return findRetriesByAnnotation(annotation, currentRetries, decreaseCurrentRetriesByOne); - } private SetExternalTaskRetries findAnnotationByException(final Throwable e) { - if (e == null) { return null; } - final SetExternalTaskRetries annotation = e.getClass().getAnnotation(SetExternalTaskRetries.class); if (annotation != null) { return annotation; } - return findAnnotationByException(e.getCause()); - } private int findRetriesByAnnotation(final SetExternalTaskRetries annotation, final int currentRetries, final boolean decreaseCurrentRetriesByOne) { - if (annotation == null) { if (decreaseCurrentRetriesByOne) { return currentRetries - 1; @@ -336,18 +279,14 @@ private int findRetriesByAnnotation(final SetExternalTaskRetries annotation, fin } else { return annotation.retries(); } - } public int attemptsStarted(final Integer taskRetries, final SetExternalTaskRetries annotation) { - final int retriesLeft = retriesLeft(taskRetries, annotation); return this.retries - retriesLeft; - } private long calculateTimeout(final Integer taskRetries, final SetExternalTaskRetries annotation) { - final int currentTry = attemptsStarted(taskRetries, annotation); if (retries < 1) { return 0; @@ -356,7 +295,5 @@ private long calculateTimeout(final Integer taskRetries, final SetExternalTaskRe } else { return retryTimeout; } - } - } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducer.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducer.java index 0ab3bff..3574d2a 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducer.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducer.java @@ -25,7 +25,7 @@ public abstract class CamundaBpmProducer extends DefaultProducer { protected RuntimeService runtimeService; protected Map parameters; - public CamundaBpmProducer(CamundaBpmEndpoint endpoint, Map parameters) { + protected CamundaBpmProducer(CamundaBpmEndpoint endpoint, Map parameters) { super(endpoint); this.processEngine = endpoint.getProcessEngine(); if (this.processEngine != null) { @@ -33,9 +33,7 @@ public CamundaBpmProducer(CamundaBpmEndpoint endpoint, Map param } this.parameters = parameters; } - - protected CamundaBpmEndpoint getCamundaBpmEndpoint() { return (CamundaBpmEndpoint) getEndpoint(); } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducerFactory.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducerFactory.java index 21849bd..2abaa01 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducerFactory.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/CamundaBpmProducerFactory.java @@ -22,25 +22,18 @@ */ public final class CamundaBpmProducerFactory { - // private static final Logger log = - // LoggerFactory.getLogger(CamundaBpmFactory.class); - private CamundaBpmProducerFactory() { - } // Prevent instantiation of helper class + throw new UnsupportedOperationException("This class cannot be instantiated"); + } public static CamundaBpmProducer createProducer(final CamundaBpmEndpoint endpoint, final ParsedUri uri, final Map parameters) throws IllegalArgumentException { - - switch (uri.getType()) { - case StartProcess: - return new StartProcessProducer(endpoint, parameters); - case SendSignal: - case SendMessage: - return new MessageProducer(endpoint, parameters); - default: - throw new IllegalArgumentException("Cannot create a producer for URI '" + uri + "' - new ProducerType '" - + uri.getType() + "' not yet supported?"); - } + return switch (uri.getType()) { + case START_PR -> new StartProcessProducer(endpoint, parameters); + case SEND_SIGNAL, SEND_MESSAGE -> new MessageProducer(endpoint, parameters); + default -> throw new IllegalArgumentException("Cannot create a producer for URI '" + uri + + "' - new ProducerType '" + uri.getType() + "' not yet supported?"); + }; } diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/MessageProducer.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/MessageProducer.java index 44e13b4..d9f79ba 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/MessageProducer.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/MessageProducer.java @@ -46,7 +46,6 @@ * @author Bernd Ruecker */ public class MessageProducer extends CamundaBpmProducer { - private static final Logger LOG = LoggerFactory.getLogger(MessageProducer.class); private final String messageName; @@ -88,7 +87,6 @@ public void close() { } @Override - @SuppressWarnings({ "rawtypes", "unchecked" }) public void process(Exchange exchange) throws Exception { String processInstanceId = exchange.getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID, String.class); String businessKey = exchange.getProperty(EXCHANGE_HEADER_BUSINESS_KEY, String.class); @@ -96,10 +94,10 @@ public void process(Exchange exchange) throws Exception { Map processVariables = ExchangeUtils.prepareVariables(exchange, parameters); if (messageName != null) { - HashMap correlationKeys = new HashMap(); + HashMap correlationKeys = new HashMap<>(); if (correlationKeyName != null) { - Class clazz = String.class; + Class clazz = String.class; String correlationKeyType = exchange.getProperty(EXCHANGE_HEADER_CORRELATION_KEY_TYPE, String.class); if (correlationKeyType != null) { clazz = Class.forName(correlationKeyType); diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/StartProcessProducer.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/StartProcessProducer.java index 9bc5ddc..41df6d9 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/StartProcessProducer.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/component/producer/StartProcessProducer.java @@ -48,7 +48,6 @@ public StartProcessProducer(CamundaBpmEndpoint endpoint, Map par this.processDefinitionKey = (String) parameters.get(PROCESS_DEFINITION_KEY_PARAMETER); } else { processDefinitionKey = null; - // throw new IllegalArgumentException("You need to pass the '" + PROCESS_DEFINITION_KEY_PARAMETER + "' parameter! Parameters received: " + parameters); } } @@ -60,7 +59,7 @@ public void close() { @Override public void process(Exchange exchange) throws Exception { - Map processVariables = new HashMap(); + Map processVariables = new HashMap<>(); if (parameters.containsKey(COPY_MESSAGE_PROPERTIES_PARAMETER)) { processVariables.putAll(exchange.getProperties()); } @@ -95,24 +94,23 @@ private void setOutBody(final Exchange exchange, final ProcessInstanceWithVariab final String variableName = parameters.get(COPY_PROCESS_VARIABLES_TO_OUT_BODY_PARAMETER).toString(); if (variableName.equals("*")) { - exchange.getOut().setBody(instance.getVariables()); + exchange.getMessage().setBody(instance.getVariables()); } else if (variableName.contains(",")) { - final HashMap variables = new HashMap(); + final HashMap variables = new HashMap<>(); for (final String variableNameItem : variableName.split(",")) { Object val = instance.getVariables().get(variableNameItem); if (val != null) { variables.put(variableNameItem, val); } } - exchange.getOut().setBody(variables); + exchange.getMessage().setBody(variables); } else if (!variableName.trim().isEmpty()) { - exchange.getOut().setBody(instance.getVariables().get(variableName)); + exchange.getMessage().setBody(instance.getVariables().get(variableName)); } else { - exchange.getOut().setBody(instance.getProcessInstanceId()); + exchange.getMessage().setBody(instance.getProcessInstanceId()); } } else { - exchange.getOut().setBody(instance.getProcessInstanceId()); + exchange.getMessage().setBody(instance.getProcessInstanceId()); } } - } \ No newline at end of file diff --git a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/converter/TimePatternConverter.java b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/converter/TimePatternConverter.java index 3340b8c..52e747a 100644 --- a/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/converter/TimePatternConverter.java +++ b/camunda-bpm-camel-common/src/main/java/org/camunda/bpm/camel/converter/TimePatternConverter.java @@ -8,6 +8,7 @@ public class TimePatternConverter { private TimePatternConverter() { + throw new UnsupportedOperationException("This class cannot be instantiated"); } public static long toMilliSeconds(String value) { diff --git a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/BaseCamelTest.java b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/BaseCamelTest.java index 7aed7e6..0181d87 100644 --- a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/BaseCamelTest.java +++ b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/BaseCamelTest.java @@ -5,20 +5,20 @@ import org.camunda.bpm.camel.component.CamundaBpmComponent; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.RuntimeService; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import static org.camunda.bpm.camel.component.CamundaBpmConstants.CAMUNDA_BPM_CAMEL_URI_SCHEME; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -public class BaseCamelTest { +public abstract class BaseCamelTest { protected CamelContext camelContext = new DefaultCamelContext(); protected ProcessEngine processEngine = mock(ProcessEngine.class); protected RuntimeService runtimeService = mock(RuntimeService.class); - @Before - public void setUpMocksAndCamundaBpmComponent() { + @BeforeEach + void setUpMocksAndCamundaBpmComponent() { when(processEngine.getRuntimeService()).thenReturn(runtimeService); CamundaBpmComponent component = new CamundaBpmComponent(processEngine); diff --git a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/CamelServiceTest.java b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/CamelServiceTest.java index 3dd84c6..698efe6 100644 --- a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/CamelServiceTest.java +++ b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/CamelServiceTest.java @@ -1,40 +1,37 @@ package org.camunda.bpm.camel.common; -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import org.apache.camel.*; +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; import org.assertj.core.api.Assertions; import org.camunda.bpm.camel.BaseCamelTest; +import org.camunda.bpm.camel.component.CamundaBpmConstants; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.impl.context.BpmnExecutionContext; import org.camunda.bpm.engine.impl.context.Context; import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.MockedStatic; +import org.mockito.Mockito; -@RunWith(PowerMockRunner.class) -@PrepareForTest(Context.class) -public class CamelServiceTest extends BaseCamelTest { + +class CamelServiceTest extends BaseCamelTest { protected CamelServiceCommonImpl service; protected ProducerTemplate producerTemplate; protected ExecutionEntity execution; - @Before + private MockedStatic contextMock; + + @BeforeEach public void setupService() { service = new CamelServiceCommonImpl() { @Override @@ -48,120 +45,127 @@ public void setCamelContext(CamelContext camelContext) { } }; service.setProcessEngine(processEngine); - CamelContext camelContext = mock(ExtendedCamelContext.class); + CamelContext camelContext = Mockito.mock(CamelContext.class); service.setCamelContext(camelContext); - producerTemplate = mock(ProducerTemplate.class); - when(camelContext.createProducerTemplate()).thenReturn(producerTemplate); + producerTemplate = Mockito.mock(ProducerTemplate.class); + Mockito.when(camelContext.createProducerTemplate()).thenReturn(producerTemplate); + + BpmnExecutionContext executionContext = Mockito.mock(BpmnExecutionContext.class); + execution = Mockito.mock(ExecutionEntity.class); - BpmnExecutionContext executionContext = mock(BpmnExecutionContext.class); - execution = mock(ExecutionEntity.class); + Mockito.when(executionContext.getExecution()).thenReturn(execution); + Mockito.when(execution.getProcessInstanceId()).thenReturn("theProcessInstanceId"); + Mockito.when(execution.getBusinessKey()).thenReturn("theBusinessKey"); + Mockito.when(execution.getVariable(anyString())).thenReturn("theVariable"); - when(executionContext.getExecution()).thenReturn(execution); - when(execution.getProcessInstanceId()).thenReturn("theProcessInstanceId"); - when(execution.getBusinessKey()).thenReturn("theBusinessKey"); - when(execution.getVariable(anyString())).thenReturn("theVariable"); + contextMock = Mockito.mockStatic(Context.class); + contextMock + .when(Context::getBpmnExecutionContext) + .thenReturn(executionContext); + } - PowerMockito.mockStatic(Context.class); - PowerMockito.when(Context.getBpmnExecutionContext()).thenReturn( - executionContext); + @AfterEach + void teardownService() { + contextMock.close(); } @Test - public void testSendToEndpoint() throws Exception { - Exchange send = mock(Exchange.class); - Message message = mock(Message.class); - when(send.getIn()).thenReturn(message); - when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn( - send); + void testSendToEndpoint() throws Exception { + Exchange send = Mockito.mock(Exchange.class); + Message message = Mockito.mock(Message.class); + Mockito.when(send.getIn()).thenReturn(message); + Mockito.when(producerTemplate.send(anyString(), any(Exchange.class))) + .thenReturn(send); ArgumentCaptor exchangeCaptor = ArgumentCaptor .forClass(Exchange.class); service.sendTo("what/ever"); - verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); - verify(execution).getVariableNames(); + Mockito.verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); + Mockito.verify(execution).getVariableNames(); - assertThat(exchangeCaptor.getValue().getProperty(EXCHANGE_HEADER_BUSINESS_KEY)) + Assertions + .assertThat(exchangeCaptor + .getValue() + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY)) .isEqualTo("theBusinessKey"); - assertThat( - exchangeCaptor.getValue().getProperty(EXCHANGE_HEADER_CORRELATION_KEY)) + Assertions + .assertThat(exchangeCaptor + .getValue() + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY)) .isNull(); - assertThat( - exchangeCaptor.getValue().getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + Assertions + .assertThat(exchangeCaptor + .getValue() + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) .isEqualTo("theProcessInstanceId"); } @Test - public void testSendToEndpointWithNoVariables() throws Exception { - Exchange send = mock(Exchange.class); - Message message = mock(Message.class); - when(send.getIn()).thenReturn(message); - when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn( - send); + void testSendToEndpointWithNoVariables() throws Exception { + Exchange send = Mockito.mock(Exchange.class); + Message message = Mockito.mock(Message.class); + Mockito.when(send.getIn()).thenReturn(message); + Mockito.when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn(send); - ArgumentCaptor exchangeCaptor = ArgumentCaptor - .forClass(Exchange.class); + ArgumentCaptor exchangeCaptor = ArgumentCaptor.forClass(Exchange.class); service.sendTo("what/ever", ""); - verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); - verify(execution, never()).getVariableNames(); + Mockito.verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); + Mockito.verify(execution, never()).getVariableNames(); } @Test - public void testSendToEndpointWithOneVariable() throws Exception { - Exchange send = mock(Exchange.class); - Message message = mock(Message.class); - when(send.getIn()).thenReturn(message); - when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn( - send); + void testSendToEndpointWithOneVariable() throws Exception { + Exchange send = Mockito.mock(Exchange.class); + Message message = Mockito.mock(Message.class); + Mockito.when(send.getIn()).thenReturn(message); + Mockito.when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn(send); - ArgumentCaptor exchangeCaptor = ArgumentCaptor - .forClass(Exchange.class); + ArgumentCaptor exchangeCaptor = ArgumentCaptor.forClass(Exchange.class); service.sendTo("what/ever", "varName"); - verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); - verify(execution, never()).getVariableNames(); - verify(execution).getVariable("varName"); + Mockito.verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); + Mockito.verify(execution, never()).getVariableNames(); + Mockito.verify(execution).getVariable("varName"); } @Test - public void testSendToEndpointWithAlleVariables() throws Exception { - Exchange send = mock(Exchange.class); - Message message = mock(Message.class); - when(send.getIn()).thenReturn(message); - when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn( - send); + void testSendToEndpointWithAlleVariables() throws Exception { + Exchange send = Mockito.mock(Exchange.class); + Message message = Mockito.mock(Message.class); + Mockito.when(send.getIn()).thenReturn(message); + Mockito.when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn(send); - ArgumentCaptor exchangeCaptor = ArgumentCaptor - .forClass(Exchange.class); + ArgumentCaptor exchangeCaptor = ArgumentCaptor.forClass(Exchange.class); service.sendTo("what/ever", null); - verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); - verify(execution).getVariableNames(); + Mockito.verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); + Mockito.verify(execution).getVariableNames(); } @Test - public void testSendToEndpointWithCorrelation() throws Exception { - Exchange send = mock(Exchange.class); - Message message = mock(Message.class); - when(send.getIn()).thenReturn(message); - when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn( - send); + void testSendToEndpointWithCorrelation() throws Exception { + Exchange send = Mockito.mock(Exchange.class); + Message message = Mockito.mock(Message.class); + Mockito.when(send.getIn()).thenReturn(message); + Mockito.when(producerTemplate.send(anyString(), any(Exchange.class))).thenReturn(send); - ArgumentCaptor exchangeCaptor = ArgumentCaptor - .forClass(Exchange.class); + ArgumentCaptor exchangeCaptor = ArgumentCaptor.forClass(Exchange.class); service.sendTo("what/ever", null, "theCorrelationKey"); - verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); + Mockito.verify(producerTemplate).send(anyString(), exchangeCaptor.capture()); - assertThat( - exchangeCaptor.getValue().getProperty(EXCHANGE_HEADER_CORRELATION_KEY)) + Assertions + .assertThat(exchangeCaptor + .getValue() + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY)) .isEqualTo("theCorrelationKey"); } } \ No newline at end of file diff --git a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/UriParsingTest.java b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/UriParsingTest.java index 4ec9f11..de1c5b6 100644 --- a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/UriParsingTest.java +++ b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/common/UriParsingTest.java @@ -1,26 +1,24 @@ package org.camunda.bpm.camel.common; -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.CAMUNDA_BPM_CAMEL_URI_SCHEME; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.camundaBpmUri; - -import org.apache.camel.Component; import org.apache.camel.ResolveEndpointFailedException; -import org.assertj.core.api.Assertions; import org.camunda.bpm.camel.BaseCamelTest; -import org.camunda.bpm.camel.component.CamundaBpmComponent; -import org.junit.Test; +import org.camunda.bpm.camel.component.CamundaBpmConstants; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class UriParsingTest extends BaseCamelTest { +import java.util.Objects; +class UriParsingTest extends BaseCamelTest { @Test - public void testThatCamelContextIsInitialized() throws Exception { - Component component = camelContext.getComponent(CAMUNDA_BPM_CAMEL_URI_SCHEME); - assertThat(component).isInstanceOf(CamundaBpmComponent.class); + void testThatCamelContextIsInitialized() { + camelContext.getComponent(CamundaBpmConstants.CAMUNDA_BPM_CAMEL_URI_SCHEME); } - @Test(expected = ResolveEndpointFailedException.class) - public void testGetCamundaEndpointWithUnknownUriExtension() throws Exception { - camelContext.getEndpoint(camundaBpmUri("what/ever")); + @Test + void testGetCamundaEndpointWithUnknownUriExtension() { + String uri = Objects.requireNonNull(CamundaBpmConstants.camundaBpmUri("what/ever")); + Assertions.assertThrows( + ResolveEndpointFailedException.class, + () -> camelContext.getEndpoint(uri)); } } \ No newline at end of file diff --git a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/MessageProducerTest.java b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/MessageProducerTest.java index aeb578d..18f5a73 100644 --- a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/MessageProducerTest.java +++ b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/MessageProducerTest.java @@ -1,325 +1,328 @@ package org.camunda.bpm.camel.component.producer; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.ACTIVITY_ID_PARAMETER; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.CORRELATION_KEY_NAME_PARAMETER; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY_TYPE; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.MESSAGE_NAME_PARAMETER; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.camundaBpmUri; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; import java.util.Map; import org.apache.camel.Exchange; -import org.apache.camel.ExtendedExchange; import org.apache.camel.Message; import org.apache.camel.Producer; +import org.assertj.core.api.Assertions; import org.camunda.bpm.camel.BaseCamelTest; +import org.camunda.bpm.camel.component.CamundaBpmConstants; import org.camunda.bpm.camel.component.CamundaBpmEndpoint; import org.camunda.bpm.engine.runtime.Execution; import org.camunda.bpm.engine.runtime.ExecutionQuery; import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.runtime.ProcessInstanceQuery; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; -public class MessageProducerTest extends BaseCamelTest { +class MessageProducerTest extends BaseCamelTest { @Test - public void getSignalProcessProducerFromUri() throws Exception { + void getSignalProcessProducerFromUri() throws Exception { CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); Producer producer = endpoint.createProducer(); - assertThat(producer).isInstanceOf(MessageProducer.class); + Assertions.assertThat(producer).isInstanceOf(MessageProducer.class); } - @SuppressWarnings("unchecked") @Test - public void messageIsDeliveredCalled() throws Exception { + void messageIsDeliveredCalled() throws Exception { ProcessInstance processInstance = mock(ProcessInstance.class); - when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); - when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); - when( - runtimeService.startProcessInstanceByKey(eq("aProcessDefinitionKey"), anyMap())).thenReturn( - processInstance); + Mockito.when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); + Mockito.when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); + Mockito + .when(runtimeService.startProcessInstanceByKey( + eq("aProcessDefinitionKey"), + anyMap())) + .thenReturn(processInstance); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); Producer producer = endpoint.createProducer(); - assertThat(producer).isInstanceOf(MessageProducer.class); + Assertions.assertThat(producer).isInstanceOf(MessageProducer.class); } - @SuppressWarnings("unchecked") @Test - public void signalCalled() throws Exception { + void signalCalled() throws Exception { Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); ExecutionQuery query = mock(ExecutionQuery.class); Execution execution = mock(Execution.class); - when(exchange.getIn()).thenReturn(message); - when( - exchange.getProperty(eq(EXCHANGE_HEADER_PROCESS_INSTANCE_ID), eq(String.class))).thenReturn( - "theProcessInstanceId"); - when(runtimeService.createExecutionQuery()).thenReturn(query); - when(query.processInstanceId(anyString())).thenReturn(query); - when(query.activityId(anyString())).thenReturn(query); - when(query.singleResult()).thenReturn(execution); - when(execution.getId()).thenReturn("1234"); + Mockito.when(exchange.getIn()).thenReturn(message); + Mockito.when( + exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID, String.class)) + .thenReturn("theProcessInstanceId"); + Mockito.when(runtimeService.createExecutionQuery()).thenReturn(query); + Mockito.when(query.processInstanceId(anyString())).thenReturn(query); + Mockito.when(query.activityId(anyString())).thenReturn(query); + Mockito.when(query.singleResult()).thenReturn(execution); + Mockito.when(execution.getId()).thenReturn("1234"); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); Producer producer = endpoint.createProducer(); producer.process(exchange); - verify(runtimeService).signal(anyString(), anyMap()); + Mockito.verify(runtimeService).signal(anyString(), anyMap()); } @Test - public void signalTransformBusinesskey() throws Exception { - Exchange exchange = mock(ExtendedExchange.class); + void signalTransformBusinessKey() throws Exception { + Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); ExecutionQuery query = mock(ExecutionQuery.class); Execution execution = mock(Execution.class); ProcessInstanceQuery piQuery = mock(ProcessInstanceQuery.class); ProcessInstance processInstance = mock(ProcessInstance.class); - when(exchange.getIn()).thenReturn(message); - when(exchange.getProperty(eq(EXCHANGE_HEADER_BUSINESS_KEY), eq(String.class))).thenReturn( - "theBusinessKey"); + Mockito.when(exchange.getIn()).thenReturn(message); + Mockito + .when(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY, String.class)) + .thenReturn("theBusinessKey"); - when(runtimeService.createProcessInstanceQuery()).thenReturn(piQuery); - when(runtimeService.createExecutionQuery()).thenReturn(query); - when(piQuery.processInstanceBusinessKey(anyString())).thenReturn(piQuery); - when(piQuery.singleResult()).thenReturn(processInstance); - when(processInstance.getId()).thenReturn("theProcessInstanceId"); + Mockito.when(runtimeService.createProcessInstanceQuery()).thenReturn(piQuery); + Mockito.when(runtimeService.createExecutionQuery()).thenReturn(query); + Mockito.when(piQuery.processInstanceBusinessKey(anyString())).thenReturn(piQuery); + Mockito.when(piQuery.singleResult()).thenReturn(processInstance); + Mockito.when(processInstance.getId()).thenReturn("theProcessInstanceId"); - when(query.processInstanceId(anyString())).thenReturn(query); - when(query.activityId(anyString())).thenReturn(query); - when(query.singleResult()).thenReturn(execution); + Mockito.when(query.processInstanceId(anyString())).thenReturn(query); + Mockito.when(query.activityId(anyString())).thenReturn(query); + Mockito.when(query.singleResult()).thenReturn(execution); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); Producer producer = endpoint.createProducer(); producer.process(exchange); - verify(piQuery).processInstanceBusinessKey("theBusinessKey"); - verify(query).processInstanceId("theProcessInstanceId"); + Mockito.verify(piQuery).processInstanceBusinessKey("theBusinessKey"); + Mockito.verify(query).processInstanceId("theProcessInstanceId"); } - @SuppressWarnings("unchecked") @Test - public void messageProcessInstanceId() throws Exception { + void messageProcessInstanceId() throws Exception { Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); ExecutionQuery query = mock(ExecutionQuery.class); Execution execution = mock(Execution.class); - when(exchange.getIn()).thenReturn(message); - when( - exchange.getProperty(eq(EXCHANGE_HEADER_PROCESS_INSTANCE_ID), eq(String.class))).thenReturn( - "theProcessInstanceId"); - when(runtimeService.createExecutionQuery()).thenReturn(query); - when(query.processInstanceId(anyString())).thenReturn(query); - when(query.messageEventSubscriptionName(anyString())).thenReturn(query); - when(query.singleResult()).thenReturn(execution); - when(execution.getId()).thenReturn("theExecutionId"); + Mockito.when(exchange.getIn()).thenReturn(message); + Mockito + .when(exchange.getProperty( + CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID, + String.class)) + .thenReturn("theProcessInstanceId"); + Mockito.when(runtimeService.createExecutionQuery()).thenReturn(query); + Mockito.when(query.processInstanceId(anyString())).thenReturn(query); + Mockito.when(query.messageEventSubscriptionName(anyString())).thenReturn(query); + Mockito.when(query.singleResult()).thenReturn(execution); + Mockito.when(execution.getId()).thenReturn("theExecutionId"); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + MESSAGE_NAME_PARAMETER + "=" + "aMessageName")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.MESSAGE_NAME_PARAMETER + "=" + "aMessageName")); Producer producer = endpoint.createProducer(); producer.process(exchange); - verify(query).processInstanceId("theProcessInstanceId"); - verify(query).messageEventSubscriptionName("aMessageName"); + Mockito.verify(query).processInstanceId("theProcessInstanceId"); + Mockito.verify(query).messageEventSubscriptionName("aMessageName"); - verify(runtimeService).messageEventReceived(eq("aMessageName"), eq("theExecutionId"), anyMap()); + Mockito.verify(runtimeService) + .messageEventReceived(eq("aMessageName"), eq("theExecutionId"), anyMap()); } - @SuppressWarnings("unchecked") @Test - public void messageBusinessKey() throws Exception { + void messageBusinessKey() throws Exception { Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); - when(exchange.getIn()).thenReturn(message); - when(exchange.getProperty(eq(EXCHANGE_HEADER_BUSINESS_KEY), eq(String.class))).thenReturn( - "theBusinessKey"); + Mockito.when(exchange.getIn()).thenReturn(message); + Mockito.when(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY, String.class)) + .thenReturn("theBusinessKey"); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + MESSAGE_NAME_PARAMETER + "=" + "aMessageName")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.MESSAGE_NAME_PARAMETER + "=" + "aMessageName")); Producer producer = endpoint.createProducer(); producer.process(exchange); - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes,unchecked") Class> mapClass = (Class>) (Class) Map.class; ArgumentCaptor> correlationCaptor = ArgumentCaptor.forClass(mapClass); - verify(runtimeService).correlateMessage(eq("aMessageName"), + Mockito.verify(runtimeService).correlateMessage(eq("aMessageName"), eq("theBusinessKey"), correlationCaptor.capture(), anyMap()); - assertThat(correlationCaptor.getValue()).isEmpty(); + Assertions.assertThat(correlationCaptor.getValue()).isEmpty(); } - @SuppressWarnings("unchecked") @Test - public void messageBusinessKeyCorrelationKey() throws Exception { + void messageBusinessKeyCorrelationKey() throws Exception { Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); final String BODY = "body"; - when(message.getBody()).thenReturn(BODY); - when(exchange.getIn()).thenReturn(message); - when(exchange.getProperty(eq(EXCHANGE_HEADER_BUSINESS_KEY), eq(String.class))).thenReturn( - "theBusinessKey"); - when(exchange.getProperty(eq(EXCHANGE_HEADER_CORRELATION_KEY), eq(String.class))).thenReturn( - "theCorrelationKey"); - - CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint(camundaBpmUri( - "message?" + MESSAGE_NAME_PARAMETER + "=" + "aMessageName" + "&" - + CORRELATION_KEY_NAME_PARAMETER + "=" - + "aCorrelationKeyName" + "&" + COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER - + "=test")); + Mockito.when(message.getBody()).thenReturn(BODY); + Mockito.when(exchange.getIn()).thenReturn(message); + Mockito.when(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY, String.class)) + .thenReturn("theBusinessKey"); + Mockito.when(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY, String.class)) + .thenReturn("theCorrelationKey"); + + CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.MESSAGE_NAME_PARAMETER + "=aMessageName" + + "&" + CamundaBpmConstants.CORRELATION_KEY_NAME_PARAMETER + "=aCorrelationKeyName" + + "&" + CamundaBpmConstants.COPY_MESSAGE_BODY_AS_PROCESS_VARIABLE_PARAMETER + "=test")); Producer producer = endpoint.createProducer(); producer.process(exchange); - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes", "unchecked"}) Class> mapClass = (Class>) (Class) Map.class; ArgumentCaptor> correlationCaptor = ArgumentCaptor.forClass(mapClass); ArgumentCaptor> variablesCaptor = ArgumentCaptor.forClass(mapClass); - verify(runtimeService).correlateMessage(eq("aMessageName"), + Mockito.verify(runtimeService).correlateMessage(eq("aMessageName"), eq("theBusinessKey"), correlationCaptor.capture(), variablesCaptor.capture()); - assertThat(correlationCaptor.getValue()).hasSize(1); - assertThat(correlationCaptor.getValue().keySet()).contains("aCorrelationKeyName"); - assertThat(correlationCaptor.getValue().values()).contains("theCorrelationKey"); - assertThat(variablesCaptor.getValue()).hasSize(1); - assertThat(variablesCaptor.getValue()).containsKey("test"); - assertThat(variablesCaptor.getValue()).containsValue(BODY); + Assertions.assertThat(correlationCaptor.getValue()).hasSize(1); + Assertions.assertThat(correlationCaptor.getValue()) + .containsEntry("aCorrelationKeyName", "theCorrelationKey"); + Assertions.assertThat(variablesCaptor.getValue()).hasSize(1); + Assertions.assertThat(variablesCaptor.getValue()).containsEntry("test", BODY); } - @SuppressWarnings("unchecked") + @SuppressWarnings({"rawtypes", "unchecked"}) @Test - public void messageBusinessKeyCorrelationKeyType() throws Exception { + void messageBusinessKeyCorrelationKeyType() throws Exception { Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); - when(exchange.getIn()).thenReturn(message); - when(exchange.getProperty(eq(EXCHANGE_HEADER_BUSINESS_KEY), eq(String.class))).thenReturn( - "theBusinessKey"); - - when(exchange.getProperty(eq(EXCHANGE_HEADER_CORRELATION_KEY), - eq(java.lang.Integer.class))).thenReturn(15); - - when(exchange.getProperty(eq(EXCHANGE_HEADER_CORRELATION_KEY_TYPE), - eq(String.class))).thenReturn( - "java.lang.Integer"); + Mockito.when(exchange.getIn()).thenReturn(message); + Mockito + .when(exchange.getProperty( + CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY, + String.class)) + .thenReturn("theBusinessKey"); + + Mockito + .when(exchange.getProperty( + CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY, + Integer.class)) + .thenReturn(15); + + Mockito + .when(exchange.getProperty( + CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY_TYPE, + String.class)) + .thenReturn("java.lang.Integer"); - CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint(camundaBpmUri( - "message?" + MESSAGE_NAME_PARAMETER + "=" + "aMessageName" + "&" - + CORRELATION_KEY_NAME_PARAMETER + "=" - + "aCorrelationKeyName" + "&" + EXCHANGE_HEADER_CORRELATION_KEY_TYPE - + "=java.lang.Integer")); + CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.MESSAGE_NAME_PARAMETER + "=aMessageName" + "&" + + CamundaBpmConstants.CORRELATION_KEY_NAME_PARAMETER + "=aCorrelationKeyName" + "&" + + CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY_TYPE + "=java.lang.Integer")); Producer producer = endpoint.createProducer(); producer.process(exchange); - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes", "unchecked"}) Class> mapClass = (Class>) (Class) Map.class; ArgumentCaptor> correlationCaptor = ArgumentCaptor.forClass(mapClass); - verify(runtimeService).correlateMessage(eq("aMessageName"), + Mockito.verify(runtimeService).correlateMessage(eq("aMessageName"), eq("theBusinessKey"), correlationCaptor.capture(), anyMap()); - assertThat(correlationCaptor.getValue()).hasSize(1); - assertThat(correlationCaptor.getValue().keySet()).contains("aCorrelationKeyName"); - assertThat(correlationCaptor.getValue().values()).contains(15); + Assertions.assertThat(correlationCaptor.getValue()).hasSize(1); + Assertions.assertThat(correlationCaptor.getValue()).containsEntry("aCorrelationKeyName", 15); } - @SuppressWarnings("unchecked") @Test - public void messageNoKey() throws Exception { + void messageNoKey() throws Exception { Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); - when(exchange.getIn()).thenReturn(message); + Mockito.when(exchange.getIn()).thenReturn(message); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + MESSAGE_NAME_PARAMETER + "=" + "aMessageName")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.MESSAGE_NAME_PARAMETER + "=" + "aMessageName")); Producer producer = endpoint.createProducer(); producer.process(exchange); - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes", "unchecked"}) Class> mapClass = (Class>) (Class) Map.class; ArgumentCaptor> correlationCaptor = ArgumentCaptor.forClass(mapClass); - verify(runtimeService).correlateMessage(eq("aMessageName"), - correlationCaptor.capture(), - anyMapOf(String.class, Object.class)); + Mockito.verify(runtimeService).correlateMessage(eq("aMessageName"), + correlationCaptor.capture(), anyMap()); - assertThat(correlationCaptor.getValue()).isEmpty(); + Assertions.assertThat(correlationCaptor.getValue()).isEmpty(); } - @SuppressWarnings("unchecked") @Test - public void messageCorrelationKey() throws Exception { + void messageCorrelationKey() throws Exception { Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); - when(exchange.getIn()).thenReturn(message); - when(exchange.getProperty(eq(EXCHANGE_HEADER_CORRELATION_KEY), eq(String.class))).thenReturn( - "theCorrelationKey"); + Mockito.when(exchange.getIn()).thenReturn(message); + Mockito + .when(exchange.getProperty( + CamundaBpmConstants.EXCHANGE_HEADER_CORRELATION_KEY, + String.class)) + .thenReturn("theCorrelationKey"); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message?" + MESSAGE_NAME_PARAMETER + "=" + "aMessageName" + "&" - + CORRELATION_KEY_NAME_PARAMETER + "=" + "aCorrelationKeyName")); + CamundaBpmConstants.camundaBpmUri( + "message?" + CamundaBpmConstants.MESSAGE_NAME_PARAMETER + "=aMessageName" + "&" + + CamundaBpmConstants.CORRELATION_KEY_NAME_PARAMETER + "=aCorrelationKeyName")); Producer producer = endpoint.createProducer(); producer.process(exchange); - @SuppressWarnings("rawtypes") + @SuppressWarnings("rawtypes,unchecked") Class> mapClass = (Class>) (Class) Map.class; ArgumentCaptor> correlationCaptor = ArgumentCaptor.forClass(mapClass); - verify(runtimeService).correlateMessage(eq("aMessageName"), - correlationCaptor.capture(), - anyMapOf(String.class, Object.class)); - - assertThat(correlationCaptor.getValue()).hasSize(1); - assertThat(correlationCaptor.getValue().keySet()).contains("aCorrelationKeyName"); - assertThat(correlationCaptor.getValue().values()).contains("theCorrelationKey"); + Mockito.verify(runtimeService) + .correlateMessage( + eq("aMessageName"), + correlationCaptor.capture(), + anyMap()); + + Assertions.assertThat(correlationCaptor.getValue()).hasSize(1); + Assertions.assertThat(correlationCaptor.getValue()) + .containsEntry("aCorrelationKeyName", "theCorrelationKey"); } @Test - public void shouldFailWithoutMessageActivityId() { + void shouldFailWithoutMessageActivityId() { CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("message")); - - assertThatThrownBy(endpoint::createProducer) - .isInstanceOf(IllegalArgumentException.class); + CamundaBpmConstants.camundaBpmUri("message")); + org.junit.jupiter.api.Assertions.assertThrows( + IllegalArgumentException.class, + endpoint::createProducer); } } diff --git a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/SignalProcessProducerTest.java b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/SignalProcessProducerTest.java index 01fb8ba..5534790 100644 --- a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/SignalProcessProducerTest.java +++ b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/SignalProcessProducerTest.java @@ -1,78 +1,76 @@ package org.camunda.bpm.camel.component.producer; -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.ACTIVITY_ID_PARAMETER; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.camundaBpmUri; -import static org.mockito.Matchers.anyMap; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - import org.apache.camel.Endpoint; import org.apache.camel.Producer; +import org.assertj.core.api.Assertions; import org.camunda.bpm.camel.BaseCamelTest; +import org.camunda.bpm.camel.component.CamundaBpmConstants; import org.camunda.bpm.camel.component.CamundaBpmEndpoint; import org.camunda.bpm.engine.runtime.ProcessInstance; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; -public class SignalProcessProducerTest extends BaseCamelTest { +class SignalProcessProducerTest extends BaseCamelTest { @Test - public void getSignalProcessProducerFromUri() throws Exception { + void getSignalProcessProducerFromUri() throws Exception { CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("signal?" + PROCESS_DEFINITION_KEY_PARAMETER + "=" + "aProcessDefinitionKey" + "&" - + ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); + CamundaBpmConstants.camundaBpmUri( + "signal?" + CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER + "=aProcessDefinitionKey" + + "&" + CamundaBpmConstants.ACTIVITY_ID_PARAMETER + "=anActivityId")); Producer producer = endpoint.createProducer(); - assertThat(producer).isInstanceOf(MessageProducer.class); + Assertions.assertThat(producer).isInstanceOf(MessageProducer.class); } - // No longer valid - The process definition key may be past at execution of - // the route - // @Test(expected = IllegalArgumentException.class) - // public void noProcessDefinitionKeyParameterShouldThrowException() throws - // Exception { - // Endpoint endpoint = camelContext.getEndpoint(camundaBpmUri("signal")); - // endpoint.createProducer(); - // } - - @Test(expected = IllegalArgumentException.class) - public void noActivityIdParameterShouldThrowException() throws Exception { + @Test + void noActivityIdParameterShouldThrowException() { Endpoint endpoint = camelContext.getEndpoint( - camundaBpmUri("signal?" + PROCESS_DEFINITION_KEY_PARAMETER + "=" + "aProcessDefinitionKey")); - endpoint.createProducer(); + CamundaBpmConstants.camundaBpmUri("signal?" + CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER + "=aProcessDefinitionKey")); + org.junit.jupiter.api.Assertions.assertThrows( + IllegalArgumentException.class, + endpoint::createProducer); } - @SuppressWarnings("unchecked") @Test - public void signalShouldBeCalled() throws Exception { - ProcessInstance processInstance = mock(ProcessInstance.class); - when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); - when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); - when(runtimeService.startProcessInstanceByKey(eq("aProcessDefinitionKey"), anyMap())).thenReturn( - processInstance); + void signalShouldBeCalled() throws Exception { + ProcessInstance processInstance = Mockito.mock(ProcessInstance.class); + Mockito.when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); + Mockito.when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); + Mockito + .when(runtimeService.startProcessInstanceByKey( + eq("aProcessDefinitionKey"), + anyMap())) + .thenReturn(processInstance); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("signal?" + PROCESS_DEFINITION_KEY_PARAMETER + "=" + "aProcessDefinitionKey" + "&" - + ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); + CamundaBpmConstants.camundaBpmUri( + "signal?" + CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER + "=aProcessDefinitionKey" + + "&" + CamundaBpmConstants.ACTIVITY_ID_PARAMETER + "=anActivityId")); Producer producer = endpoint.createProducer(); - assertThat(producer).isInstanceOf(MessageProducer.class); + Assertions.assertThat(producer).isInstanceOf(MessageProducer.class); } - @SuppressWarnings("unchecked") @Test - public void signalWithBusinessKeyShouldBeCalled() throws Exception { - ProcessInstance processInstance = mock(ProcessInstance.class); - when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); - when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); - when(runtimeService.startProcessInstanceByKey(eq("aProcessDefinitionKey"), anyMap())).thenReturn( - processInstance); + void signalWithBusinessKeyShouldBeCalled() throws Exception { + ProcessInstance processInstance = Mockito.mock(ProcessInstance.class); + Mockito.when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); + Mockito.when(processInstance.getProcessDefinitionId()) + .thenReturn("theProcessDefinitionId"); + Mockito + .when(runtimeService.startProcessInstanceByKey( + eq("aProcessDefinitionKey"), + anyMap())) + .thenReturn(processInstance); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("signal?" + PROCESS_DEFINITION_KEY_PARAMETER + "=" + "aProcessDefinitionKey" + "&" - + ACTIVITY_ID_PARAMETER + "=" + "anActivityId")); + CamundaBpmConstants.camundaBpmUri( + "signal?" + CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER + "=aProcessDefinitionKey" + + "&" + CamundaBpmConstants.ACTIVITY_ID_PARAMETER + "=anActivityId")); Producer producer = endpoint.createProducer(); - assertThat(producer).isInstanceOf(MessageProducer.class); + Assertions.assertThat(producer).isInstanceOf(MessageProducer.class); } } diff --git a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/StartProcessProducerTest.java b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/StartProcessProducerTest.java index 0a6313c..b87d211 100644 --- a/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/StartProcessProducerTest.java +++ b/camunda-bpm-camel-common/src/test/java/org/camunda/bpm/camel/component/producer/StartProcessProducerTest.java @@ -3,83 +3,100 @@ import org.apache.camel.Exchange; import org.apache.camel.Producer; import org.apache.camel.support.DefaultExchange; +import org.assertj.core.api.Assertions; import org.camunda.bpm.camel.BaseCamelTest; +import org.camunda.bpm.camel.component.CamundaBpmConstants; import org.camunda.bpm.camel.component.CamundaBpmEndpoint; import org.camunda.bpm.engine.runtime.ProcessInstanceWithVariables; import org.camunda.bpm.engine.runtime.ProcessInstantiationBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.times; -public class StartProcessProducerTest extends BaseCamelTest { +class StartProcessProducerTest extends BaseCamelTest { @Test - public void getStartProcessProducerFromUri() throws Exception { + void getStartProcessProducerFromUri() throws Exception { CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("start?" + PROCESS_DEFINITION_KEY_PARAMETER + "=" + "aProcessDefinitionKey")); + CamundaBpmConstants.camundaBpmUri( + "start?" + CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER + "=aProcessDefinitionKey")); Producer producer = endpoint.createProducer(); - assertThat(producer).isInstanceOf(StartProcessProducer.class); + Assertions.assertThat(producer).isInstanceOf(StartProcessProducer.class); } - // No longer valid - The process definition key may be past at execution of - // the route - // @Test(expected = IllegalArgumentException.class) - // public void noProcessDefinitionKeyParameterShouldThrowException() throws - // Exception { - // Endpoint endpoint = camelContext.getEndpoint(camundaBpmUri("start")); - // endpoint.createProducer(); // This triggers the exception - // } - - @SuppressWarnings("unchecked") @Test - public void createProcessInstanceByKeyShouldBeCalled() throws Exception { - ProcessInstanceWithVariables processInstance = mock(ProcessInstanceWithVariables.class); - ProcessInstantiationBuilder processInstantiationBuilder = mock(ProcessInstantiationBuilder.class); - when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); - when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); - when(runtimeService.createProcessInstanceByKey(eq("aProcessDefinitionKey"))).thenReturn( - processInstantiationBuilder); - when(processInstantiationBuilder.setVariables(anyMap())).thenReturn(processInstantiationBuilder); - when(processInstantiationBuilder.executeWithVariablesInReturn()).thenReturn(processInstance); + void createProcessInstanceByKeyShouldBeCalled() throws Exception { + ProcessInstanceWithVariables processInstance = + Mockito.mock(ProcessInstanceWithVariables.class); + ProcessInstantiationBuilder processInstantiationBuilder = + Mockito.mock(ProcessInstantiationBuilder.class); + Mockito.when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); + Mockito.when(processInstance.getProcessDefinitionId()) + .thenReturn("theProcessDefinitionId"); + Mockito.when(runtimeService.createProcessInstanceByKey("aProcessDefinitionKey")) + .thenReturn(processInstantiationBuilder); + Mockito.when(processInstantiationBuilder.setVariables(anyMap())) + .thenReturn(processInstantiationBuilder); + Mockito.when(processInstantiationBuilder.executeWithVariablesInReturn()) + .thenReturn(processInstance); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("start?" + PROCESS_DEFINITION_KEY_PARAMETER + "=" + "aProcessDefinitionKey")); + CamundaBpmConstants.camundaBpmUri( + "start?" + CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER + "=aProcessDefinitionKey")); StartProcessProducer producer = (StartProcessProducer) endpoint.createProducer(); Exchange exchange = new DefaultExchange(camelContext); producer.process(exchange); - verify(runtimeService, times(1)).createProcessInstanceByKey(eq("aProcessDefinitionKey")); - assertThat(exchange.getProperty(EXCHANGE_HEADER_PROCESS_DEFINITION_ID)).isEqualTo("theProcessDefinitionId"); - assertThat(exchange.getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo("theProcessInstanceId"); + Mockito.verify(runtimeService, times(1)) + .createProcessInstanceByKey("aProcessDefinitionKey"); + Assertions + .assertThat(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_DEFINITION_ID)) + .isEqualTo("theProcessDefinitionId"); + Assertions + .assertThat(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo("theProcessInstanceId"); } - @SuppressWarnings("unchecked") @Test - public void createProcessInstanceByKeyWithBusinessKeyShouldBeCalled() throws Exception { - ProcessInstanceWithVariables processInstance = mock(ProcessInstanceWithVariables.class); - ProcessInstantiationBuilder processInstantiationBuilder = mock(ProcessInstantiationBuilder.class); - when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); - when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); - when(processInstance.getBusinessKey()).thenReturn("aBusinessKey"); - when(runtimeService.createProcessInstanceByKey(eq("aProcessDefinitionKey"))) + void createProcessInstanceByKeyWithBusinessKeyShouldBeCalled() throws Exception { + ProcessInstanceWithVariables processInstance = + Mockito.mock(ProcessInstanceWithVariables.class); + ProcessInstantiationBuilder processInstantiationBuilder = + Mockito.mock(ProcessInstantiationBuilder.class); + Mockito.when(processInstance.getProcessInstanceId()).thenReturn("theProcessInstanceId"); + Mockito.when(processInstance.getProcessDefinitionId()).thenReturn("theProcessDefinitionId"); + Mockito.when(processInstance.getBusinessKey()).thenReturn("aBusinessKey"); + Mockito.when(runtimeService.createProcessInstanceByKey("aProcessDefinitionKey")) .thenReturn(processInstantiationBuilder); - when(processInstantiationBuilder.setVariables(anyMap())).thenReturn(processInstantiationBuilder); - when(processInstantiationBuilder.businessKey(anyString())).thenReturn(processInstantiationBuilder); - when(processInstantiationBuilder.executeWithVariablesInReturn()).thenReturn(processInstance); + Mockito.when(processInstantiationBuilder.setVariables(anyMap())) + .thenReturn(processInstantiationBuilder); + Mockito.when(processInstantiationBuilder.businessKey(anyString())) + .thenReturn(processInstantiationBuilder); + Mockito.when(processInstantiationBuilder.executeWithVariablesInReturn()) + .thenReturn(processInstance); CamundaBpmEndpoint endpoint = (CamundaBpmEndpoint) camelContext.getEndpoint( - camundaBpmUri("start?" + PROCESS_DEFINITION_KEY_PARAMETER + "=" + "aProcessDefinitionKey")); + CamundaBpmConstants.camundaBpmUri( + "start?" + CamundaBpmConstants.PROCESS_DEFINITION_KEY_PARAMETER + "=aProcessDefinitionKey")); StartProcessProducer producer = (StartProcessProducer) endpoint.createProducer(); Exchange exchange = new DefaultExchange(camelContext); - exchange.setProperty(EXCHANGE_HEADER_BUSINESS_KEY, "aBusinessKey"); + exchange.setProperty(CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY, "aBusinessKey"); producer.process(exchange); - verify(runtimeService, times(1)).createProcessInstanceByKey(eq("aProcessDefinitionKey")); - verify(processInstantiationBuilder, times(1)).businessKey(eq("aBusinessKey")); - assertThat(exchange.getProperty(EXCHANGE_HEADER_PROCESS_DEFINITION_ID)).isEqualTo("theProcessDefinitionId"); - assertThat(exchange.getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo("theProcessInstanceId"); - assertThat(exchange.getProperty(EXCHANGE_HEADER_BUSINESS_KEY)).isEqualTo("aBusinessKey"); + Mockito.verify(runtimeService, times(1)) + .createProcessInstanceByKey("aProcessDefinitionKey"); + Mockito.verify(processInstantiationBuilder, times(1)) + .businessKey("aBusinessKey"); + Assertions + .assertThat(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_DEFINITION_ID)) + .isEqualTo("theProcessDefinitionId"); + Assertions + .assertThat(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo("theProcessInstanceId"); + Assertions + .assertThat(exchange.getProperty(CamundaBpmConstants.EXCHANGE_HEADER_BUSINESS_KEY)) + .isEqualTo("aBusinessKey"); } } diff --git a/camunda-bpm-camel-quarkus-cdi/pom.xml b/camunda-bpm-camel-quarkus-cdi/pom.xml new file mode 100644 index 0000000..8313a93 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/pom.xml @@ -0,0 +1,162 @@ + + + + camunda BPM - Apache Camel Integration (CDI) + camunda-bpm-camel-quarkus-cdi + + + org.camunda.bpm.extension.camel + camunda-bpm-camel + 0.9.0-SNAPSHOT + + 4.0.0 + + + false + 3.8.2 + + + + + io.quarkus.platform + quarkus-bom + ${quarkus.version} + import + pom + + + io.quarkus.platform + quarkus-camel-bom + ${quarkus.version} + import + pom + + + + + + + org.camunda.bpm.extension.camel + camunda-bpm-camel-common + + + org.camunda.bpm + camunda-engine + ${camunda-bpm.version} + provided + + + org.slf4j + slf4j-api + ${sl4j.version} + + + + org.apache.camel.quarkus + camel-quarkus-core + + + + org.camunda.bpm.quarkus + camunda-bpm-quarkus-engine + ${camunda-bpm.version} + test + + + io.quarkus + quarkus-test-h2 + ${quarkus.version} + test + + + io.quarkus + quarkus-jdbc-h2 + test + + + io.quarkus + quarkus-junit5 + ${quarkus.version} + test + + + io.quarkus + quarkus-arc + ${quarkus.version} + test + + + org.apache.camel.quarkus + camel-quarkus-mock + 3.8.0 + test + + + org.camunda.bpm.extension.camel + camunda-bpm-camel-common-tests + + + org.codehaus.groovy + groovy-jsr223 + 3.0.21 + test + + + org.awaitility + awaitility + test + + + jakarta.inject + jakarta.inject-api + compile + + + + + + + + + + + org.apache.maven.plugins + maven-failsafe-plugin + 3.2.5 + + + failsafe-integration-tests + integration-test + + integration-test + + + + failsafe-verify + verify + + verify + + + + + + io.smallrye + jandex-maven-plugin + 3.1.6 + + + make-index + + jandex + + + + + + + diff --git a/camunda-bpm-camel-cdi/src/main/java/org/camunda/bpm/camel/cdi/CamelServiceImpl.java b/camunda-bpm-camel-quarkus-cdi/src/main/java/org/camunda/bpm/camel/cdi/CamelServiceImpl.java similarity index 83% rename from camunda-bpm-camel-cdi/src/main/java/org/camunda/bpm/camel/cdi/CamelServiceImpl.java rename to camunda-bpm-camel-quarkus-cdi/src/main/java/org/camunda/bpm/camel/cdi/CamelServiceImpl.java index 835acf9..a2d628a 100644 --- a/camunda-bpm-camel-cdi/src/main/java/org/camunda/bpm/camel/cdi/CamelServiceImpl.java +++ b/camunda-bpm-camel-quarkus-cdi/src/main/java/org/camunda/bpm/camel/cdi/CamelServiceImpl.java @@ -4,12 +4,10 @@ import org.camunda.bpm.camel.common.CamelServiceCommonImpl; import org.camunda.bpm.engine.ProcessEngine; -import javax.ejb.Stateless; -import javax.inject.Inject; -import javax.inject.Named; +import jakarta.inject.Inject; +import jakarta.inject.Named; @Named("camel") -//@Stateless public class CamelServiceImpl extends CamelServiceCommonImpl { @Inject diff --git a/camunda-bpm-camel-cdi/src/main/resources/META-INF/beans.xml b/camunda-bpm-camel-quarkus-cdi/src/main/resources/META-INF/beans.xml similarity index 100% rename from camunda-bpm-camel-cdi/src/main/resources/META-INF/beans.xml rename to camunda-bpm-camel-quarkus-cdi/src/main/resources/META-INF/beans.xml diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/BaseQuarkusIntegrationTest.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/BaseQuarkusIntegrationTest.java new file mode 100644 index 0000000..aea4527 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/BaseQuarkusIntegrationTest.java @@ -0,0 +1,44 @@ +package org.camunda.bpm.camel.cdi; + +import org.camunda.bpm.camel.cdi.quarkus.LogServiceCdiImpl; +import org.camunda.bpm.camel.common.CamelService; +import org.camunda.bpm.engine.HistoryService; +import org.camunda.bpm.engine.RepositoryService; +import org.camunda.bpm.engine.RuntimeService; +import org.camunda.bpm.engine.TaskService; +import io.smallrye.common.annotation.Identifier; +import jakarta.inject.Inject; + +public class BaseQuarkusIntegrationTest { + + @Inject + RepositoryService repositoryService; + + @Inject + RuntimeService runtimeService; + + @Inject + TaskService taskService; + + @Inject + HistoryService historyService; + + @Inject + CamelContextBootstrap camelContextBootstrap; + + @Inject + @Identifier("cdiLog") + LogServiceCdiImpl log; + + @Inject + CamelService camelService; + + protected void deployProcess(String processFilePath) { + // Create a new deployment + repositoryService.createDeployment() + .addClasspathResource(processFilePath)// Filename of the process model + .enableDuplicateFiltering(true)// No redeployment when process model remains unchanged + .deploy(); + } + +} diff --git a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/CamelContextBootstrap.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/CamelContextBootstrap.java similarity index 87% rename from camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/CamelContextBootstrap.java rename to camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/CamelContextBootstrap.java index 6a6acdc..ca6b77f 100644 --- a/camunda-bpm-camel-cdi/src/test/java/org/camunda/bpm/camel/cdi/CamelContextBootstrap.java +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/CamelContextBootstrap.java @@ -1,17 +1,14 @@ package org.camunda.bpm.camel.cdi; +import io.quarkus.runtime.Startup; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import jakarta.inject.Inject; +import jakarta.inject.Singleton; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; -import org.apache.camel.cdi.CdiCamelContext; import org.camunda.bpm.camel.component.CamundaBpmComponent; -import org.camunda.bpm.camel.component.CamundaBpmEndpointDefaultImpl; import org.camunda.bpm.engine.ProcessEngine; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.ejb.Singleton; -import javax.ejb.Startup; -import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,7 +32,7 @@ public class CamelContextBootstrap { private static final Logger LOG = LoggerFactory.getLogger(CamelContextBootstrap.class); @Inject - CdiCamelContext camelCtx; + CamelContext camelCtx; @Inject ProcessEngine processEngine; diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ConsumeExternalTasksTest.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ConsumeExternalTasksTest.java new file mode 100644 index 0000000..9fb8c4f --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ConsumeExternalTasksTest.java @@ -0,0 +1,986 @@ +package org.camunda.bpm.camel.cdi; + +/* Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.Serial; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Expression; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.camunda.bpm.camel.component.CamundaBpmConstants; +import org.camunda.bpm.camel.component.externaltasks.SetExternalTaskRetries; +import org.camunda.bpm.engine.ExternalTaskService; +import org.camunda.bpm.engine.externaltask.ExternalTask; +import org.camunda.bpm.engine.externaltask.LockedExternalTask; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.history.HistoricVariableInstance; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@QuarkusTest +@QuarkusTestResource(H2DatabaseTestResource.class) +public class ConsumeExternalTasksTest extends BaseQuarkusIntegrationTest { + @Inject + CamelContext camelContext; + @Inject + ExternalTaskService externalTaskService; + @Inject + @EndpointInject("mock:resultEndpointET") + MockEndpoint mockEndpoint; + + @Produces + @ApplicationScoped + public RouteBuilder createRoute() { + return new RouteBuilder() { + public void configure() { + from("camunda-bpm:poll-externalTasks?topic=topic1&maxTasksPerPoll=5&delay=250&retries=2&retryTimeouts=1s&retryTimeout=2s") + .routeId("firstRoute") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .threads(2) + .to(mockEndpoint) + ; + + from("camunda-bpm:poll-externalTasks?topic=topic2&async=true&delay=250&variablesToFetch=var2,var3&lockDuration=2s&maxTasksPerPoll=2&workerId=0815") + .routeId("secondRoute") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to(mockEndpoint) + ; + + from("camunda-bpm:poll-externalTasks?topic=topic3&async=false&delay=250&variablesToFetch=") + .routeId("thirdRoute") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to(mockEndpoint) + ; + + from("direct:firstTestRoute") + .routeId("firstProcessRoute") + .to("camunda-bpm:async-externalTask?onCompletion=true&retries=2&retryTimeouts=1s") + .to(mockEndpoint) + ; + + from("direct:secondTestRoute") + .routeId("secondProcessRoute") + .to(mockEndpoint) + .to("camunda-bpm:async-externalTask") + ; + } + }; + } + + @Test + @SuppressWarnings("unchecked") + public void testSetProcessVariables() throws Exception { + deployProcess("process/StartExternalTask.bpmn20.xml"); + // variables to be set by the Camel-endpoint processing the external + // task + mockEndpoint.returnReplyBody(new Expression() { + @Override + public T evaluate(Exchange exchange, Class type) { + Map variables = exchange.getIn().getBody(Map.class); + final String var2 = (String) variables.get("var2"); + + final HashMap result = new HashMap<>(); + result.put("var2", var2 + "bar"); + result.put("var3", "bar3"); + + return (T) result; + } + }); + + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess", + processVariables); + assertNotNull(processInstance); + await().atMost(1, TimeUnit.SECONDS).until( + () -> externalTaskService.createExternalTaskQuery().processInstanceId(processInstance.getId()).active().count() == 0); + + // assert that the camunda BPM process instance ID has been added as a + // property to the message + assertEquals(processInstance.getId(), mockEndpoint.assertExchangeReceived(0).getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)); + + // all process instance variables are loaded since no "variablesToFetch" + // parameter was given + var exchangeIn = mockEndpoint.assertExchangeReceived(0).getIn(); + assertNotNull(exchangeIn.getBody()); + assertInstanceOf(Map.class, exchangeIn.getBody()); + assertEquals(2, exchangeIn.getBody(Map.class).size()); + assertEquals("foo", exchangeIn.getBody(Map.class).get("var1")); + assertEquals("bar", exchangeIn.getBody(Map.class).get("var2")); + + // assert that the variables sent in the response-message has been set + // into the process + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap.get("var1")), + () -> assertEquals("barbar", variablesAsMap.get("var2")), + () -> assertEquals("bar3", variablesAsMap.get("var3")) + ); + + assertHappyEnd(processInstance); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + } + + @Test + @SuppressWarnings("unchecked") + public void testLoadNoProcessVariablesAndAsyncIsFalse() throws Exception { + deployProcess("process/StartExternalTask3.bpmn20.xml"); + // variables to be set by the Camel-endpoint processing the external + // task + mockEndpoint.returnReplyBody(new Expression() { + @Override + @SuppressWarnings("unchecked") + public T evaluate(Exchange exchange, Class type) { + final HashMap result = new HashMap<>(); + result.put("var1", "foo1"); + result.put("var2", "bar2"); + return (T) result; + } + }); + + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess3", + processVariables); + assertNotNull(processInstance); + await().atMost(1, TimeUnit.SECONDS).until( + () -> externalTaskService.createExternalTaskQuery().processInstanceId(processInstance.getId()).active().count() == 0); + + + // assert that the camunda BPM process instance ID has been added as a + // property to the message + assertEquals(processInstance.getId(), mockEndpoint.assertExchangeReceived(0).getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)); + + // no process instance variables are loaded since an empty + // "variablesToFetch" parameter was given + assertNotNull(mockEndpoint.assertExchangeReceived(0).getIn().getBody()); + assertInstanceOf(Map.class, mockEndpoint.assertExchangeReceived(0).getIn().getBody()); + assertTrue(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class).isEmpty()); + + // assert that the variables sent in the response-message has been set + // into the process + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(2, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo1", variablesAsMap.get("var1")), + () -> assertEquals("bar2", variablesAsMap.get("var2")) + ); + + // assert that process in end event "HappyEnd" + assertHappyEnd(processInstance); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + } + + @Test + public void testCompleteTaskOnCompletionSuccessfully() { + deployProcess("process/StartExternalTask4.bpmn20.xml"); + // variables to be set by the Camel-endpoint processing the external + // task + mockEndpoint.returnReplyBody(new Expression() { + @Override + @SuppressWarnings("unchecked") + public T evaluate(Exchange exchange, Class type) { + final HashMap result = new HashMap<>(); + result.put("var2", "bar2"); + result.put("var3", "bar3"); + return (T) result; + } + }); + + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + processVariables.put("var3", "foobar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", + processVariables); + assertNotNull(processInstance); + + // external task is still not resolved and not locked + final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks1); + assertEquals(1, externalTasks1.size()); + assertNull(externalTasks1.get(0).getWorkerId()); + + // find external task and lock + final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); + assertNotNull(locked); + assertEquals(1, locked.size()); + final LockedExternalTask lockedExternalTask = locked.get(0); + + // call route "direct:testRoute" + final ProducerTemplate template = camelContext.createProducerTemplate(); + template.requestBodyAndHeader("direct:firstTestRoute", + null, + "CamundaBpmExternalTaskId", + lockedExternalTask.getId()); + + // ensure endpoint has been called + assertNotNull(mockEndpoint.assertExchangeReceived(0)); + assertEquals(0, mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_ATTEMPTSSTARTED)); + assertEquals(2, mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_RETRIESLEFT)); + + // assert that process in end event "HappyEnd" + assertHappyEnd(processInstance); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + + // assert that the variables sent in the response-message has been set + // into the process + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap.get("var1")), + () -> assertEquals("bar2", variablesAsMap.get("var2")), + () -> assertEquals("bar3", variablesAsMap.get("var3")) + ); + } + + @Test + public void testCompleteTaskOnCompletionFailure() { + deployProcess("process/StartExternalTask4.bpmn20.xml"); + final String FAILURE = "Failure"; + + // variables returned but must not be set since task will not be + // completed + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new Exception(FAILURE); + }); + + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + processVariables.put("var3", "foobar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", + processVariables); + assertNotNull(processInstance); + + // external task is still not resolved and not locked + final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks1); + assertEquals(1, externalTasks1.size()); + assertNull(externalTasks1.get(0).getWorkerId()); + assertNull(externalTasks1.get(0).getRetries()); + + // find external task and lock + final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); + assertNotNull(locked); + assertEquals(1, locked.size()); + final LockedExternalTask lockedExternalTask = locked.get(0); + + // call route "direct:testRoute" + final ProducerTemplate template = camelContext.createProducerTemplate(); + try { + template.requestBodyAndHeader("direct:firstTestRoute", + null, + "CamundaBpmExternalTaskId", + lockedExternalTask.getId()); + fail("Expected an exception, but Camel route succeeded!"); + } catch (Exception e) { + // expected + } + + // ensure endpoint has been called + assertNotNull(mockEndpoint.assertExchangeReceived(0)); + + // external task is still not resolved + final List externalTasks2 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks2); + assertEquals(1, externalTasks2.size()); + assertEquals(2, externalTasks2.get(0).getRetries()); + + // assert that process not in the end event "HappyEnd" + assertProcessDidNotEnd(processInstance, "HappyEnd"); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + + // assert that the variables sent in the response-message has been set + // into the process + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap.get("var1")), + () -> assertEquals("bar", variablesAsMap.get("var2")), + () -> assertEquals("foobar", variablesAsMap.get("var3")) + ); + + // complete task to make test order not relevant + externalTaskService.complete(externalTasks2.get(0).getId(), "0815"); + } + + @SuppressWarnings("unchecked") + @Test + public void testCompleteTaskSuccessfully() { + deployProcess("process/StartExternalTask4.bpmn20.xml"); + // variables to be set by the Camel-endpoint processing the external + // task + mockEndpoint.returnReplyBody(new Expression() { + @Override + public T evaluate(Exchange exchange, Class type) { + final HashMap result = new HashMap<>(); + result.put("var2", "bar2"); + result.put("var3", "bar3"); + return (T) result; + } + }); + + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + processVariables.put("var3", "foobar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", + processVariables); + assertNotNull(processInstance); + + // external task is still not resolved and not locked + final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks1); + assertEquals(1, externalTasks1.size()); + assertNull(externalTasks1.get(0).getWorkerId()); + assertNull(externalTasks1.get(0).getRetries()); + + // find external task and lock + final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); + assertNotNull(locked); + assertEquals(1, locked.size()); + final LockedExternalTask lockedExternalTask = locked.get(0); + + // call route "direct:testRoute" + final ProducerTemplate template = camelContext.createProducerTemplate(); + template.requestBodyAndHeader("direct:secondTestRoute", + null, + "CamundaBpmExternalTaskId", + lockedExternalTask.getId()); + + // ensure endpoint has been called + assertNotNull(mockEndpoint.assertExchangeReceived(0)); + + // assert that process in end event "HappyEnd" + assertHappyEnd(processInstance); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + + // assert that the variables sent in the response-message has been set + // into the process + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap.get("var1")), + () -> assertEquals("bar2", variablesAsMap.get("var2")), + () -> assertEquals("bar3", variablesAsMap.get("var3")) + ); + } + + @Test + public void testCompleteTaskFailure() { + deployProcess("process/StartExternalTask4.bpmn20.xml"); + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + processVariables.put("var3", "foobar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", + processVariables); + assertNotNull(processInstance); + + // external task is still not resolved and not locked + final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks1); + assertEquals(1, externalTasks1.size()); + assertNull(externalTasks1.get(0).getWorkerId()); + assertNull(externalTasks1.get(0).getRetries()); + + // find external task and lock + final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); + assertNotNull(locked); + assertEquals(1, locked.size()); + final LockedExternalTask lockedExternalTask = locked.get(0); + + + /* + * test CamundaBpmConstants.EXCHANGE_RESPONSE_IGNORE + */ + + // variables returned but must not be set since task will not be + // completed + mockEndpoint.returnReplyBody(new Expression() { + @SuppressWarnings("unchecked") + @Override + public T evaluate(Exchange exchange, Class type) { + return (T) CamundaBpmConstants.EXCHANGE_RESPONSE_IGNORE; + } + }); + + // second route does not recognize exceptions + + // call route "direct:secondTestRoute" + final ProducerTemplate template = camelContext.createProducerTemplate(); + template.requestBodyAndHeader("direct:secondTestRoute", + null, + "CamundaBpmExternalTaskId", + lockedExternalTask.getId()); + + // ensure endpoint has been called + assertNotNull(mockEndpoint.assertExchangeReceived(0)); + + // external task is still not resolved + final List externalTasks2 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks2); + assertEquals(1, externalTasks2.size()); + // Exception aborted processing so retries could not be set! + assertNull(externalTasks2.get(0).getRetries()); + assertNull(externalTasks2.get(0).getErrorMessage()); + + // assert that process not in the end event "HappyEnd" + assertProcessDidNotEnd(processInstance, "HappyEnd"); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + + // assert that the variables unchanged + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap.get("var1")), + () -> assertEquals("bar", variablesAsMap.get("var2")), + () -> assertEquals("foobar", variablesAsMap.get("var3")) + ); + + /* + * test common exception + */ + + mockEndpoint.reset(); + + final String FAILURE = "FAILURE"; + + // variables returned but must not be set since task will not be + // completed + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new Exception(FAILURE); + }); + + // call route "direct:testRoute" + final ProducerTemplate template2 = camelContext.createProducerTemplate(); + try { + template2.requestBodyAndHeader("direct:firstTestRoute", + null, + "CamundaBpmExternalTaskId", + lockedExternalTask.getId()); + fail("Expected an exception, but Camel route succeeded!"); + } catch (Exception e) { + // expected + } + + // ensure endpoint has been called + assertNotNull(mockEndpoint.assertExchangeReceived(0)); + + // external task is still not resolved + final List externalTasks4 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks4); + assertEquals(1, externalTasks4.size()); + // Exception aborted processing so retries could not be set! Really? + assertEquals(2, externalTasks4.get(0).getRetries()); + assertEquals(FAILURE, externalTasks4.get(0).getErrorMessage()); + + // assert that process not in the end event "HappyEnd" + assertProcessDidNotEnd(processInstance, "HappyEnd"); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + + // assert that the variables unchanged + final List variables2 = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables2.size()); + final HashMap variablesAsMap2 = new HashMap<>(); + for (final HistoricVariableInstance variable : variables2) { + variablesAsMap2.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap2.get("var1")), + () -> assertEquals("bar", variablesAsMap2.get("var2")), + () -> assertEquals("foobar", variablesAsMap2.get("var3")) + ); + + // complete task to make test order not relevant + externalTaskService.complete(externalTasks2.get(0).getId(), "0815"); + } + + @Test + public void testSetExternalTaskRetriesAnnotation() { + deployProcess("process/StartExternalTask4.bpmn20.xml"); + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + processVariables.put("var3", "foobar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", + processVariables); + assertNotNull(processInstance); + + // external task is still not resolved and not locked + final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks1); + assertEquals(1, externalTasks1.size()); + assertNull(externalTasks1.get(0).getWorkerId()); + assertNull(externalTasks1.get(0).getRetries()); + + // find external task and lock + final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); + assertNotNull(locked); + assertEquals(1, locked.size()); + final LockedExternalTask lockedExternalTask = locked.get(0); + + // set retries artificially + externalTaskService.handleFailure(lockedExternalTask.getId(), "0815", "Blabal", 2, 0); + + /* + * DoNotChangeRetriesException + */ + + mockEndpoint.reset(); + + final String DONTCHANGEMSG = "DoNotChange"; + + // variables returned but must not be set since task will not be + // completed + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new DontChangeRetriesException(DONTCHANGEMSG); + }); + + // call route "direct:testRoute" + final ProducerTemplate template2 = camelContext.createProducerTemplate(); + try { + template2.requestBodyAndHeader("direct:firstTestRoute", + null, + "CamundaBpmExternalTaskId", + lockedExternalTask.getId()); + fail("Expected an exception, but Camel route succeeded!"); + } catch (Exception e) { + // expected + } + + // ensure endpoint has been called + assertNotNull(mockEndpoint.assertExchangeReceived(0)); + + // external task is still not resolved + final List externalTasks4 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks4); + assertEquals(1, externalTasks4.size()); + // Exception aborted processing so retries could not be set! + assertEquals(2, externalTasks4.get(0).getRetries()); + assertEquals(DONTCHANGEMSG, externalTasks4.get(0).getErrorMessage()); + // assert that process not in the end event "HappyEnd" + assertProcessDidNotEnd(processInstance, "HappyEnd"); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + + // assert that the variables unchanged + final List variables2 = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables2.size()); + final HashMap variablesAsMap2 = new HashMap<>(); + for (final HistoricVariableInstance variable : variables2) { + variablesAsMap2.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap2.get("var1")), + () -> assertEquals("bar", variablesAsMap2.get("var2")), + () -> assertEquals("foobar", variablesAsMap2.get("var3")) + ); + + /* + * DoNotChangeRetriesException + */ + mockEndpoint.reset(); + final String CREATEINCIDENT = "Incident"; + + // variables returned but must not be set since task will not be + // completed + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new CreateIncidentException(CREATEINCIDENT); + }); + + // call route "direct:testRoute" + final ProducerTemplate template3 = camelContext.createProducerTemplate(); + try { + template3.requestBodyAndHeader("direct:firstTestRoute", + null, + "CamundaBpmExternalTaskId", + lockedExternalTask.getId()); + fail("Expected an exception, but Camel route succeeded!"); + } catch (Exception e) { + // expected + } + + // ensure endpoint has been called + assertNotNull(mockEndpoint.assertExchangeReceived(0)); + + // external task is still not resolved + final List externalTasks3 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks3); + assertEquals(1, externalTasks3.size()); + // Exception aborted processing so retries could not be set! + assertEquals(0, externalTasks3.get(0).getRetries()); + assertEquals(CREATEINCIDENT, externalTasks3.get(0).getErrorMessage()); + + + // assert that process not in the end event "HappyEnd" + assertProcessDidNotEnd(processInstance, "HappyEnd"); + + // assert that process ended not due to error boundary event 4711 + assertProcessDidNotEnd(processInstance, "End4711"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + + // assert that the variables unchanged + final List variables3 = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(3, variables3.size()); + final HashMap variablesAsMap3 = new HashMap<>(); + for (final HistoricVariableInstance variable : variables3) { + variablesAsMap3.put(variable.getName(), variable.getValue()); + } + assertAll( + () -> assertEquals("foo", variablesAsMap3.get("var1")), + () -> assertEquals("bar", variablesAsMap3.get("var2")), + () -> assertEquals("foobar", variablesAsMap3.get("var3")) + ); + + // complete task to make test order not relevant + externalTaskService.complete(externalTasks1.get(0).getId(), "0815"); + } + + @SuppressWarnings("unchecked") + @Test + public void testBpmnError() throws Exception { + deployProcess("process/StartExternalTask.bpmn20.xml"); + // variables to be set by the Camel-endpoint processing the external + // task + mockEndpoint.returnReplyBody(new Expression() { + @Override + public T evaluate(Exchange exchange, Class type) { + return (T) "4711"; + } + }); + + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess", + processVariables); + assertNotNull(processInstance); + + // wait for the external task to be completed + // external task is resolved + await().atMost(1, TimeUnit.SECONDS).until(() -> externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).active().count() == 0); +// + // assert that the camunda BPM process instance ID has been added as a + // property to the message + assertEquals(processInstance.getId(), mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)); +// + // assert that the variables sent in the response-message has been set + // into the process + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(2, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertEquals("foo", variablesAsMap.get("var1")); + assertEquals("bar", variablesAsMap.get("var2")); + + // assert that process ended + final HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId( + processInstance.getId()).singleResult(); + assertNotNull(historicProcessInstance.getEndTime()); + + // assert that process ended due to error boundary event 4711 + assertNotNull(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()); + // assert that process not in end event "HappyEnd" + assertProcessDidNotEnd(processInstance, "HappyEnd"); + + // assert that process ended not due to error boundary event 0815 + assertProcessDidNotEnd(processInstance, "End0815"); + } + + @Test + public void testIncidentAndRetryTimeouts() throws Exception { + deployProcess("process/StartExternalTask.bpmn20.xml"); + + // variables to be set by the Camel-endpoint processing the external + // task + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new RuntimeException("fail!"); + }); + + // count incidents for later comparison + final long incidentCount = runtimeService.createIncidentQuery().count(); + + // start process + final Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess", + processVariables); + assertNotNull(processInstance); + + // wait for the external task to be completed + await().atMost(2, TimeUnit.SECONDS).until(() -> !externalTaskService.createExternalTaskQuery() + .processInstanceId(processInstance.getId()).list().isEmpty() + && externalTaskService.createExternalTaskQuery() + .processInstanceId(processInstance.getId()).list().get(0).getRetries() != null + && externalTaskService.createExternalTaskQuery() + .processInstanceId(processInstance.getId()).list().get(0).getRetries() == 2); + + // external task is still not resolved + final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks1); + assertEquals(1, externalTasks1.size()); + assertEquals(2, externalTasks1.get(0).getRetries()); + + // wait for the next try + await().atMost(2, TimeUnit.SECONDS).until(() -> externalTaskService.createExternalTaskQuery() + .processInstanceId(processInstance.getId()).list().get(0).getRetries() == 1); + + // external task is still not resolved + final List externalTasks2 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks2); + assertEquals(1, externalTasks2.size()); + assertEquals(1, externalTasks2.get(0).getRetries()); + + // next try is 2 seconds so after 1 second nothing changes + Thread.sleep(1000); + + // external task is still not resolved + final List externalTasks3 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks3); + assertEquals(1, externalTasks3.size()); + assertEquals(1, externalTasks3.get(0).getRetries()); + + // wait for the next try + await().atMost(5, TimeUnit.SECONDS).until(() -> externalTaskService.createExternalTaskQuery() + .processInstanceId(processInstance.getId()).list().get(0).getRetries() == 0); + + // external task is still not resolved + final List externalTasks4 = externalTaskService.createExternalTaskQuery().processInstanceId( + processInstance.getId()).list(); + assertNotNull(externalTasks4); + assertEquals(1, externalTasks4.size()); + assertEquals(0, externalTasks4.get(0).getRetries()); + + // assert that the camunda BPM process instance ID has been added as a + // property to the message + assertEquals(processInstance.getId(), mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)); + assertEquals(0, mockEndpoint + .assertExchangeReceived(0) + .getIn().getHeader(CamundaBpmConstants.EXCHANGE_HEADER_ATTEMPTSSTARTED)); + assertEquals(2, mockEndpoint + .assertExchangeReceived(0) + .getIn().getHeader(CamundaBpmConstants.EXCHANGE_HEADER_RETRIESLEFT)); + assertEquals(1, mockEndpoint + .assertExchangeReceived(1) + .getIn().getHeader(CamundaBpmConstants.EXCHANGE_HEADER_ATTEMPTSSTARTED)); + assertEquals(1, mockEndpoint + .assertExchangeReceived(1) + .getIn().getHeader(CamundaBpmConstants.EXCHANGE_HEADER_RETRIESLEFT)); + + // assert that the variables sent in the response-message has been set + // into the process + final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( + processInstance.getId()).list(); + assertEquals(2, variables.size()); + final HashMap variablesAsMap = new HashMap<>(); + for (final HistoricVariableInstance variable : variables) { + variablesAsMap.put(variable.getName(), variable.getValue()); + } + assertEquals("foo", variablesAsMap.get("var1")); + assertEquals("bar", variablesAsMap.get("var2")); + + // assert that process not ended + final HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId( + processInstance.getId()).singleResult(); + assertNull(historicProcessInstance.getEndTime()); + + // assert that incident raised + assertEquals(incidentCount + 1, runtimeService.createIncidentQuery().count()); + } + + @SetExternalTaskRetries(retries = 0) + public static class CreateIncidentException extends Exception { + @Serial + private static final long serialVersionUID = 1L; + + public CreateIncidentException(final String message) { + super(message); + } + } + + @SetExternalTaskRetries(retries = 0, relative = true) + public static class DontChangeRetriesException extends Exception { + @Serial + private static final long serialVersionUID = 1L; + + public DontChangeRetriesException(final String message) { + super(message); + } + } + + private void assertProcessDidNotEnd(ProcessInstance processInstance, String endActivityId) { + assertNull(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId(endActivityId) + .singleResult() + ); + } + + private void assertHappyEnd(ProcessInstance processInstance) { + // assert that process in end event "HappyEnd" + assertNotNull(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult() + ); + } + + @AfterEach + void resetMock() { + mockEndpoint.reset(); + } +} \ No newline at end of file diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ReceiveFromCamelIT.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ReceiveFromCamelIT.java new file mode 100644 index 0000000..c36c28d --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ReceiveFromCamelIT.java @@ -0,0 +1,89 @@ +package org.camunda.bpm.camel.cdi; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.camunda.bpm.camel.cdi.quarkus.LogServiceCdiImpl; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.quarkus.engine.extension.event.CamundaEngineStartupEvent; +import org.junit.jupiter.api.Test; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.QuarkusTest; +import io.smallrye.common.annotation.Identifier; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; +import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; + + +@QuarkusTest +@QuarkusTestResource(H2DatabaseTestResource.class) +public class ReceiveFromCamelIT extends BaseQuarkusIntegrationTest { + + private final static String PROCESS_DEFINITION_KEY = "receiveFromCamelProcess"; + + @Inject + @EndpointInject("mock:resultEndpoint") + MockEndpoint resultEndpoint; + @Inject + @Identifier("cdiLog") + LogServiceCdiImpl log; + + // Method is called as soon as the Process Engine is running + public void deployProcess(@Observes CamundaEngineStartupEvent startupEvent) { + deployProcess("process/ReceiveFromCamelQuarkus.bpmn20.xml"); + } + + @Produces + @ApplicationScoped + public RouteBuilder createRoute() { + return new RouteBuilder() { + public void configure() { + from("direct:sendToCamundaBpm") + .routeId("receive-from-camel-route") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to("camunda-bpm://signal?processDefinitionKey=receiveFromCamelProcess&activityId=waitForCamel") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to(resultEndpoint) + ; + } + }; + } + + @Test + public void doTest() throws IOException { + Map processVariables = new HashMap<>(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + processVariables.put("log", log); +// processVariables.put("log", Variables.objectValue(log, true).serializationDataFormat(Variables.SerializationDataFormats.JAVA).create()); + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY, processVariables); + + // Verify that a process instance has executed and there is one instance executing now + assertEquals(1, historyService.createHistoricProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()); + assertEquals(1, runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()); + + /* + * We need the process instance ID to be able to send the message to it + * + * FIXME: we need to fix this with the process execution id or even better with the Activity Instance Model + * http://camundabpm.blogspot.de/2013/06/introducing-activity-instance-model-to.html + */ + try (ProducerTemplate tpl = camelContextBootstrap.getCamelContext().createProducerTemplate()) { + tpl.sendBodyAndProperty("direct:sendToCamundaBpm", null, EXCHANGE_HEADER_PROCESS_INSTANCE_ID, processInstance.getId()); + } + + // Assert that the camunda BPM process instance ID has been added as a property to the message + assertEquals(processInstance.getId(), resultEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)); + + // Assert that the process instance is finished + assertEquals(0, runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()); + } +} \ No newline at end of file diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/SendToCamelIT.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/SendToCamelIT.java new file mode 100644 index 0000000..32a6561 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/SendToCamelIT.java @@ -0,0 +1,70 @@ +package org.camunda.bpm.camel.cdi; + +import java.util.HashMap; +import java.util.Map; +import org.apache.camel.EndpointInject; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.camunda.bpm.quarkus.engine.extension.event.CamundaEngineStartupEvent; +import org.junit.jupiter.api.Test; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; +import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; + + +@QuarkusTest +@QuarkusTestResource(H2DatabaseTestResource.class) +public class SendToCamelIT extends BaseQuarkusIntegrationTest { + + private static final String PROCESS_DEFINITION_KEY = "sendToCamelProcess"; + @Inject + @EndpointInject("mock:resultEndpoint2") + MockEndpoint resultEndpoint; + + // Method is called as soon as the Process Engine is running + public void deployProcess(@Observes CamundaEngineStartupEvent startupEvent) { + deployProcess("process/SendToCamelQuarkusDelegate.bpmn20.bpmn"); + } + + @Produces + @ApplicationScoped + public RouteBuilder createRoute() { + return new RouteBuilder() { + public void configure() { + from("direct:sendToCamelServiceTask") + .routeId("send-to-camel-route") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to(resultEndpoint) + ; + } + }; + } + + @Test + public void doTest() { + Map processVariables = new HashMap(); + processVariables.put("var1", "foo"); + processVariables.put("var2", "bar"); + processVariables.put("log", log); + ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("sendToCamelProcess", processVariables); + + // Verify that a process instance was executed and there are no instances executing now + assertEquals(1, historyService.createHistoricProcessInstanceQuery().processDefinitionKey("sendToCamelProcess").count()); + assertEquals(0, runtimeService.createProcessInstanceQuery().processDefinitionKey("sendToCamelProcess").count()); + + // Assert that the camunda BPM process instance ID has been added as a property to the message + assertEquals(processInstance.getId(), resultEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)); + + // Assert that the body of the message received by the endpoint contains a hash map with the value of the process variable 'var1' sent from camunda BPM + assertEquals("{var1=foo}", resultEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)); + + // FIXME: check that var2 is also present as a property! + } +} \ No newline at end of file diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ServiceDelegateBean.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ServiceDelegateBean.java new file mode 100644 index 0000000..4ee58a4 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/ServiceDelegateBean.java @@ -0,0 +1,39 @@ +package org.camunda.bpm.camel.cdi; + +import java.io.IOException; +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +import org.camunda.bpm.camel.component.CamundaBpmConstants; +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; +import jakarta.enterprise.context.Dependent; +import jakarta.inject.Inject; +import jakarta.inject.Named; + +@Named +@Dependent +public class ServiceDelegateBean implements JavaDelegate { + + + @Inject + CamelContext camelCtx; + + @Override + public void execute(DelegateExecution execution) { +// String expression = (String) execution.getVariable("expression"); +// vars = new Map(); +// vars.put(camel); +// vars.put(execution); +// ONGL.execute(expression, vars); +// execution.get + + try (ProducerTemplate tpl = camelCtx.createProducerTemplate()) { + tpl.sendBodyAndProperty((String) execution.getVariable("endpoint"), + execution.getVariable("content"), + CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID, execution.getProcessInstanceId()); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/SmokeIT.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/SmokeIT.java new file mode 100644 index 0000000..8847b72 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/SmokeIT.java @@ -0,0 +1,76 @@ +package org.camunda.bpm.camel.cdi; + +import org.apache.camel.EndpointInject; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.camunda.bpm.engine.task.Task; +import org.camunda.bpm.quarkus.engine.extension.event.CamundaEngineStartupEvent; +import org.junit.jupiter.api.Test; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/* + * This test is basically a ... smoke test. It's a baseline to check that all the moving pieces + * (Maven deps, Arquillian config, ...) are working OK: + * - process definition deployment + * - Camel context instantiation and route startup + * - ... + * + * See other tests in this package for actual exercising of the camunda BPM <-> Camel integration + */ +@QuarkusTest +@QuarkusTestResource(H2DatabaseTestResource.class) +public class SmokeIT extends BaseQuarkusIntegrationTest { + + private static final String PROCESS_DEFINITION_KEY = "smokeTestProcess"; + + @Inject + @EndpointInject("mock:resultEndpoint3") + MockEndpoint resultEndpoint; + + // Method is called as soon as the Process Engine is running + public void deployProcess(@Observes CamundaEngineStartupEvent startupEvent) { + deployProcess( "process/SmokeTest.bpmn20.xml"); + } + + @Produces + @ApplicationScoped + public RouteBuilder createRoute() { + return new RouteBuilder() { + public void configure() { + from("timer://smoke-message?repeatCount=1") + .routeId("smoke-test-route") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to(resultEndpoint) + ; + } + }; + } + + @Test + public void doTest() throws InterruptedException { + + assertNotNull(camelContextBootstrap); + assertNotNull(camelContextBootstrap.getCamelContext()); + assertNotNull(camelService); + + runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY); + Task task = taskService.createTaskQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).singleResult(); + + assertNotNull(task); + assertEquals("My Task", task.getName()); + assertEquals(1, runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()); + + taskService.complete(task.getId()); + assertEquals(0, runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()); + resultEndpoint.expectedMessageCount(1); + resultEndpoint.assertIsSatisfied(); + } +} diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/StartProcessFromRouteIT.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/StartProcessFromRouteIT.java new file mode 100644 index 0000000..b41b0d6 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/StartProcessFromRouteIT.java @@ -0,0 +1,84 @@ +package org.camunda.bpm.camel.cdi; + +import java.io.IOException; +import java.util.Map; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.camunda.bpm.quarkus.engine.extension.event.CamundaEngineStartupEvent; +import org.junit.jupiter.api.Test; +import io.quarkus.test.common.QuarkusTestResource; +import io.quarkus.test.h2.H2DatabaseTestResource; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; +import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@QuarkusTest +@QuarkusTestResource(H2DatabaseTestResource.class) +public class StartProcessFromRouteIT extends BaseQuarkusIntegrationTest { + + private static final String PROCESS_DEFINITION_KEY = "startProcessFromRoute"; + + @Inject + @EndpointInject("mock:mockEndpoint") + MockEndpoint mockEndpoint; + @Inject + @EndpointInject("mock:processVariableEndpoint") + MockEndpoint processVariableEndpoint; + + // Method is called as soon as the Process Engine is running + public void deployProcess(@Observes CamundaEngineStartupEvent startupEvent) { + deployProcess("process/StartProcessFromRouteQuarkus.bpmn20.xml"); + } + + @Produces + @ApplicationScoped + public RouteBuilder createRoute() { + return new RouteBuilder() { + public void configure() { + from("direct:start") + .routeId("start-process-from-route") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to("camunda-bpm://start?processDefinitionKey=startProcessFromRoute©BodyAsVariable=var1") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to(mockEndpoint) + ; + + from("direct:processVariable") + .routeId("processVariableRoute") + .to("log:org.camunda.bpm.camel.cdi?level=INFO&showAll=true&multiline=true") + .to(processVariableEndpoint) + ; + } + }; + } + + @Test + public void doTest() throws IOException { + String processInstanceId; + try (ProducerTemplate tpl = camelContextBootstrap.getCamelContext().createProducerTemplate()) { + processInstanceId = (String) tpl.requestBody("direct:start", Map.of("var1", "valueOfVar1", "log", log)); + } + assertNotNull(processInstanceId); + System.out.println("Process instance ID: " + processInstanceId); + + // Verify that a process instance was executed and there are no instances executing now + assertEquals(1, historyService.createHistoricProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()); + assertEquals(0, runtimeService.createProcessInstanceQuery().processDefinitionKey(PROCESS_DEFINITION_KEY).count()); + + // Assert that the camunda BPM process instance ID has been added as a property to the message + assertEquals(processInstanceId, mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)); + + // The body of the message coming out from the camunda-bpm: endpoint is the process instance + assertEquals(processInstanceId, mockEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)); + + // We should receive a hash map with the value of 'var1' as the body of the message + assertEquals("{var1=valueOfVar1}", processVariableEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)); + } +} \ No newline at end of file diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/quarkus/CamelServiceQuarkusImpl.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/quarkus/CamelServiceQuarkusImpl.java new file mode 100644 index 0000000..ddfe493 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/quarkus/CamelServiceQuarkusImpl.java @@ -0,0 +1,12 @@ +package org.camunda.bpm.camel.cdi.quarkus; + +import org.camunda.bpm.camel.cdi.CamelServiceImpl; +import jakarta.enterprise.context.Dependent; + +/** + * Quarkus needs a @Dependent or @ApplicationScoped annotation to instantiate a class. + * The annotation @Named from CamelServiceImpl is not sufficient. + */ +@Dependent +public class CamelServiceQuarkusImpl extends CamelServiceImpl { +} diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/quarkus/LogServiceCdiImpl.java b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/quarkus/LogServiceCdiImpl.java new file mode 100644 index 0000000..2582099 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/java/org/camunda/bpm/camel/cdi/quarkus/LogServiceCdiImpl.java @@ -0,0 +1,12 @@ +package org.camunda.bpm.camel.cdi.quarkus; + +import java.io.Serializable; +import org.camunda.bpm.camel.spring.util.LogServiceImpl; +import io.smallrye.common.annotation.Identifier; +import jakarta.inject.Singleton; + +@Singleton +@Identifier("cdiLog") +public class LogServiceCdiImpl extends LogServiceImpl implements Serializable { + +} diff --git a/camunda-bpm-camel-cdi/src/test/resources/META-INF/processes.xml b/camunda-bpm-camel-quarkus-cdi/src/test/resources/META-INF/processes.xml similarity index 100% rename from camunda-bpm-camel-cdi/src/test/resources/META-INF/processes.xml rename to camunda-bpm-camel-quarkus-cdi/src/test/resources/META-INF/processes.xml diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/resources/application.properties b/camunda-bpm-camel-quarkus-cdi/src/test/resources/application.properties new file mode 100644 index 0000000..fdc916e --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/resources/application.properties @@ -0,0 +1,11 @@ +quarkus.log.min-level=TRACE + +#camunda +quarkus.camunda.jobExecutorActivate=false +quarkus.camunda.databaseSchemaUpdate=true + +quarkus.datasource.db-kind=h2 +quarkus.datasource.jdbc.url=jdbc:h2:mem:CAMUNDADB;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE +quarkus.datasource.password=sa +quarkus.datasource.username=sa + diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/ReceiveFromCamelQuarkus.bpmn20.xml b/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/ReceiveFromCamelQuarkus.bpmn20.xml new file mode 100644 index 0000000..532fe0d --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/ReceiveFromCamelQuarkus.bpmn20.xml @@ -0,0 +1,60 @@ + + + + + SequenceFlow_2 + + + SequenceFlow_1 + SequenceFlow_3 + + + + + + SequenceFlow_3 + + + SequenceFlow_2 + SequenceFlow_1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/SendToCamelQuarkusDelegate.bpmn20.bpmn b/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/SendToCamelQuarkusDelegate.bpmn20.bpmn new file mode 100644 index 0000000..6b160b6 --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/SendToCamelQuarkusDelegate.bpmn20.bpmn @@ -0,0 +1,64 @@ + + + + + flow1 + + + + + + direct:sendToCamelServiceTask + + + ${var1} + + + + + flow1 + flow2 + + + + flow2 + Flow_0lmdzfn + + + + Flow_0lmdzfn + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/StartProcessFromRouteQuarkus.bpmn20.xml b/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/StartProcessFromRouteQuarkus.bpmn20.xml new file mode 100644 index 0000000..dc81cef --- /dev/null +++ b/camunda-bpm-camel-quarkus-cdi/src/test/resources/process/StartProcessFromRouteQuarkus.bpmn20.xml @@ -0,0 +1,75 @@ + + + + + SequenceFlow_2 + + + + SequenceFlow_3 + + + + SequenceFlow_2 + Flow_111obad + + + + + + direct:processVariable + + + ${var1} + + + + + Flow_111obad + SequenceFlow_3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/camunda-bpm-camel-spring/pom.xml b/camunda-bpm-camel-spring/pom.xml index f1724b5..7d3abd5 100644 --- a/camunda-bpm-camel-spring/pom.xml +++ b/camunda-bpm-camel-spring/pom.xml @@ -121,9 +121,15 @@ camunda-bpm-camel-common-tests - junit - junit - ${junit.version} + org.junit.jupiter + junit-jupiter + test + + + + + org.junit.vintage + junit-vintage-engine test @@ -167,12 +173,12 @@ jakarta.xml.bind jakarta.xml.bind-api - 2.3.2 + 4.0.1 org.glassfish.jaxb jaxb-runtime - 2.3.2 + 4.0.5 diff --git a/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/CamelServiceImpl.java b/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/CamelServiceImpl.java index 7be992d..d31f3ea 100644 --- a/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/CamelServiceImpl.java +++ b/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/CamelServiceImpl.java @@ -15,16 +15,24 @@ import org.apache.camel.CamelContext; import org.camunda.bpm.camel.common.CamelServiceCommonImpl; import org.camunda.bpm.engine.ProcessEngine; -import org.springframework.beans.factory.annotation.Required; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +@Service public class CamelServiceImpl extends CamelServiceCommonImpl { - @Required + @Autowired + public CamelServiceImpl(ProcessEngine processEngine, CamelContext camelContext) { + setProcessEngine(processEngine); + setCamelContext(camelContext); + } + + @Override public void setProcessEngine(ProcessEngine processEngine) { this.processEngine = processEngine; } - @Required + @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } diff --git a/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/SpringCamundaBpmComponent.java b/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/SpringCamundaBpmComponent.java index ed5da6e..3585cab 100644 --- a/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/SpringCamundaBpmComponent.java +++ b/camunda-bpm-camel-spring/src/main/java/org/camunda/bpm/camel/spring/SpringCamundaBpmComponent.java @@ -15,11 +15,13 @@ import org.camunda.bpm.camel.component.CamundaBpmComponent; import org.camunda.bpm.engine.ProcessEngine; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +@Service public class SpringCamundaBpmComponent extends CamundaBpmComponent { @Autowired - public void setProcessEngine(ProcessEngine processEngine) { - super.setProcessEngine(processEngine); + public SpringCamundaBpmComponent(ProcessEngine processEngine) { + super(processEngine); } } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ConsumeExternalTasksTest.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ConsumeExternalTasksTest.java index 917c3e0..437f6c0 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ConsumeExternalTasksTest.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ConsumeExternalTasksTest.java @@ -13,11 +13,6 @@ * limitations under the License. */ -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_ATTEMPTSSTARTED; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.EXCHANGE_HEADER_RETRIESLEFT; - import java.util.Date; import java.util.HashMap; import java.util.List; @@ -26,7 +21,6 @@ import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Expression; -import org.apache.camel.Processor; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.assertj.core.api.Assertions; @@ -42,7 +36,6 @@ import org.camunda.bpm.engine.runtime.ProcessInstance; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -55,7 +48,6 @@ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:consume-external-tasks-config.xml") public class ConsumeExternalTasksTest { - @SetExternalTaskRetries(retries = 0) public static class CreateIncidentException extends Exception { private static final long serialVersionUID = 1L; @@ -63,7 +55,7 @@ public static class CreateIncidentException extends Exception { public CreateIncidentException(final String message) { super(message); } - }; + } @SetExternalTaskRetries(retries = 0, relative = true) public static class DontChangeRetriesException extends Exception { @@ -72,52 +64,36 @@ public static class DontChangeRetriesException extends Exception { public DontChangeRetriesException(final String message) { super(message); } - }; + } private MockEndpoint mockEndpoint; - @Autowired(required = true) + @Autowired private CamelContext camelContext; - @Autowired(required = true) + @Autowired private RuntimeService runtimeService; - @Autowired(required = true) + @Autowired private HistoryService historyService; - @Autowired(required = true) + @Autowired private ExternalTaskService externalTaskService; - @Autowired(required = true) + @Autowired @Rule public ProcessEngineRule processEngineRule; @Before - public void setUp() throws Exception { - + public void setUp() { mockEndpoint = (MockEndpoint) camelContext.getEndpoint("mock:endpoint"); mockEndpoint.reset(); - - // start consumer if stopped by previous test (see "tearDown()") - // ((BatchConsumer) - // camelContext.getRoute("firstRoute").getConsumer()).start(); - } - @After - public void tearDown() throws Exception { - - // avoid accessing during shutdown of Camunda engine - // ((BatchConsumer) - // camelContext.getRoute("firstRoute").getConsumer()).stop(); - - } - - @SuppressWarnings("unchecked") @Test @Deployment(resources = { "process/StartExternalTask.bpmn20.xml" }) + @SuppressWarnings("unchecked") public void testSetProcessVariables() throws Exception { - // variables to be set by the Camel-endpoint processing the external // task mockEndpoint.returnReplyBody(new Expression() { @@ -126,20 +102,21 @@ public T evaluate(Exchange exchange, Class type) { Map variables = exchange.getIn().getBody(Map.class); final String var2 = (String) variables.get("var2"); - final HashMap result = new HashMap(); + final HashMap result = new HashMap<>(); result.put("var2", var2 + "bar"); result.put("var3", "bar3"); + return (T) result; } }); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // wait for the external task to be completed Thread.sleep(1000); @@ -147,65 +124,78 @@ public T evaluate(Exchange exchange, Class type) { // external task is not open any more final long externalTasksCount = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).active().count(); - assertThat(externalTasksCount).isEqualTo(0); + Assertions.assertThat(externalTasksCount).isZero(); // assert that the camunda BPM process instance ID has been added as a // property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo( - processInstance.getId()); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); // all process instance variables are loaded since no "variablesToFetch" // parameter was given var exchangeIn = mockEndpoint.assertExchangeReceived(0).getIn(); - assertThat(exchangeIn.getBody()).isNotNull(); - assertThat(exchangeIn.getBody()).isInstanceOf(Map.class); - assertThat(exchangeIn.getBody(Map.class)).hasSize(2); - assertThat(exchangeIn.getBody(Map.class)).containsKey("var1"); - assertThat(exchangeIn.getBody(Map.class)).containsKey("var2"); - assertThat(exchangeIn.getBody(Map.class)).containsValue("foo"); - assertThat(exchangeIn.getBody(Map.class)).containsValue("bar"); + Assertions.assertThat(exchangeIn.getBody()).isNotNull(); + Assertions.assertThat(exchangeIn.getBody()).isInstanceOf(Map.class); + Assertions.assertThat(exchangeIn.getBody(Map.class)).hasSize(2); + Assertions.assertThat(exchangeIn.getBody(Map.class)).containsEntry("var1", "foo"); + Assertions.assertThat(exchangeIn.getBody(Map.class)).containsEntry("var2", "bar"); // assert that the variables sent in the response-message has been set // into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(3); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(3); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("barbar"); - assertThat(variablesAsMap.containsKey("var3")).isTrue(); - assertThat(variablesAsMap.get("var3")).isEqualTo("bar3"); + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "barbar") + .containsEntry("var3", "bar3"); // assert that process in end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNotNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNotNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); - + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); } - @SuppressWarnings("unchecked") @Test @Deployment(resources = { "process/StartExternalTask3.bpmn20.xml" }) + @SuppressWarnings("unchecked") public void testLoadNoProcessVariablesAndAsyncIsFalse() throws Exception { - // variables to be set by the Camel-endpoint processing the external // task mockEndpoint.returnReplyBody(new Expression() { @Override + @SuppressWarnings("unchecked") public T evaluate(Exchange exchange, Class type) { - final HashMap result = new HashMap(); + final HashMap result = new HashMap<>(); result.put("var1", "foo1"); result.put("var2", "bar2"); return (T) result; @@ -213,12 +203,12 @@ public T evaluate(Exchange exchange, Class type) { }); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess3", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // wait for the external task to be completed Thread.sleep(1000); @@ -226,58 +216,79 @@ public T evaluate(Exchange exchange, Class type) { // external task is not open any more final long externalTasksCount = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).active().count(); - assertThat(externalTasksCount).isEqualTo(0); + Assertions.assertThat(externalTasksCount).isZero(); // assert that the camunda BPM process instance ID has been added as a // property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo( - processInstance.getId()); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); // no process instance variables are loaded since an empty // "variablesToFetch" parameter was given - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody()).isNotNull(); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody()).isInstanceOf(Map.class); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class).size()).isEqualTo(0); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody()) + .isNotNull() + .isInstanceOf(Map.class); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(Map.class)) + .isEmpty(); // assert that the variables sent in the response-message has been set // into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(2); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(2); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo1"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar2"); + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo1") + .containsEntry("var2", "bar2"); // assert that process in end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNotNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNotNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); - + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); } - @SuppressWarnings("unchecked") @Test @Deployment(resources = { "process/StartExternalTask4.bpmn20.xml" }) - public void testCompleteTaskOnCompletionSucessfully() throws Exception { - + public void testCompleteTaskOnCompletionSuccessfully() { // variables returned but must not be set since task will not be // completed mockEndpoint.returnReplyBody(new Expression() { @Override + @SuppressWarnings("unchecked") public T evaluate(Exchange exchange, Class type) { - final HashMap result = new HashMap(); + final HashMap result = new HashMap<>(); result.put("var2", "bar2"); result.put("var3", "bar3"); return (T) result; @@ -285,26 +296,28 @@ public T evaluate(Exchange exchange, Class type) { }); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); processVariables.put("var3", "foobar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // external task is still not resolved and not locked final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks1).isNotNull(); - assertThat(externalTasks1.size()).isEqualTo(1); - assertThat(externalTasks1.get(0).getWorkerId()).isNull(); + Assertions.assertThat(externalTasks1) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks1.get(0).getWorkerId()).isNull(); // find external task and lock final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); - assertThat(locked).isNotNull(); - assertThat(locked.size()).isEqualTo(1); + Assertions.assertThat(locked) + .isNotNull() + .hasSize(1); final LockedExternalTask lockedExternalTask = locked.get(0); // call route "direct:testRoute" @@ -315,78 +328,97 @@ public T evaluate(Exchange exchange, Class type) { lockedExternalTask.getId()); // ensure endpoint has been called - assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getHeader(EXCHANGE_HEADER_ATTEMPTSSTARTED)).isEqualTo( - 0); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getHeader(EXCHANGE_HEADER_RETRIESLEFT)).isEqualTo(2); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_ATTEMPTSSTARTED)) + .isEqualTo(0); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_RETRIESLEFT)) + .isEqualTo(2); // assert that process in end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNotNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNotNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); // assert that the variables sent in the response-message has been set // into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(3); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(3); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar2"); - assertThat(variablesAsMap.containsKey("var3")).isTrue(); - assertThat(variablesAsMap.get("var3")).isEqualTo("bar3"); - + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar2") + .containsEntry("var3", "bar3"); } @Test @Deployment(resources = { "process/StartExternalTask4.bpmn20.xml" }) - public void testCompleteTaskOnCompletionFailure() throws Exception { - + public void testCompleteTaskOnCompletionFailure() { final String FAILURE = "Failure"; // variables returned but must not be set since task will not be // completed - mockEndpoint.whenAnyExchangeReceived(new Processor() { - @Override - public void process(Exchange exchange) throws Exception { - throw new Exception(FAILURE); - } + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new Exception(FAILURE); }); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); processVariables.put("var3", "foobar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // external task is still not resolved and not locked final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks1).isNotNull(); - assertThat(externalTasks1.size()).isEqualTo(1); - assertThat(externalTasks1.get(0).getWorkerId()).isNull(); - assertThat(externalTasks1.get(0).getRetries()).isNull(); + Assertions.assertThat(externalTasks1) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks1.get(0).getWorkerId()).isNull(); + Assertions.assertThat(externalTasks1.get(0).getRetries()).isNull(); // find external task and lock final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); - assertThat(locked).isNotNull(); - assertThat(locked.size()).isEqualTo(1); + Assertions.assertThat(locked) + .isNotNull() + .hasSize(1); final LockedExternalTask lockedExternalTask = locked.get(0); // call route "direct:testRoute" @@ -402,59 +434,71 @@ public void process(Exchange exchange) throws Exception { } // ensure endpoint has been called - assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); // external task is still not resolved final List externalTasks2 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks2).isNotNull(); - assertThat(externalTasks2.size()).isEqualTo(1); - assertThat(externalTasks2.get(0).getRetries()).isEqualTo(2); + Assertions.assertThat(externalTasks2) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks2.get(0).getRetries()).isEqualTo(2); // assert that process not in the end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); // assert that the variables sent in the response-message has been set // into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(3); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(3); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar"); - assertThat(variablesAsMap.containsKey("var3")).isTrue(); - assertThat(variablesAsMap.get("var3")).isEqualTo("foobar"); + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar") + .containsEntry("var3", "foobar"); // complete task to make test order not relevant externalTaskService.complete(externalTasks2.get(0).getId(), "0815"); - } @SuppressWarnings("unchecked") @Test @Deployment(resources = { "process/StartExternalTask4.bpmn20.xml" }) - public void testCompleteTaskSucessfully() throws Exception { - + public void testCompleteTaskSuccessfully() { // variables returned but must not be set since task will not be // completed mockEndpoint.returnReplyBody(new Expression() { @Override public T evaluate(Exchange exchange, Class type) { - final HashMap result = new HashMap(); + final HashMap result = new HashMap<>(); result.put("var2", "bar2"); result.put("var3", "bar3"); return (T) result; @@ -462,26 +506,30 @@ public T evaluate(Exchange exchange, Class type) { }); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); processVariables.put("var3", "foobar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // external task is still not resolved and not locked - final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( - processInstance.getId()).list(); - assertThat(externalTasks1).isNotNull(); - assertThat(externalTasks1.size()).isEqualTo(1); - assertThat(externalTasks1.get(0).getWorkerId()).isNull(); + final List externalTasks1 = externalTaskService + .createExternalTaskQuery() + .processInstanceId(processInstance.getId()) + .list(); + Assertions.assertThat(externalTasks1) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks1.get(0).getWorkerId()).isNull(); // find external task and lock final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); - assertThat(locked).isNotNull(); - assertThat(locked.size()).isEqualTo(1); + Assertions.assertThat(locked) + .isNotNull() + .hasSize(1); final LockedExternalTask lockedExternalTask = locked.get(0); // call route "direct:testRoute" @@ -492,64 +540,77 @@ public T evaluate(Exchange exchange, Class type) { lockedExternalTask.getId()); // ensure endpoint has been called - assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); // assert that process in end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNotNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNotNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); // assert that the variables sent in the response-message has been set // into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(3); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(3); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar2"); - assertThat(variablesAsMap.containsKey("var3")).isTrue(); - assertThat(variablesAsMap.get("var3")).isEqualTo("bar3"); - + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar2") + .containsEntry("var3", "bar3"); } @Test @Deployment(resources = { "process/StartExternalTask4.bpmn20.xml" }) - public void testCompleteTaskFailure() throws Exception { - + public void testCompleteTaskFailure() { // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); processVariables.put("var3", "foobar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // external task is still not resolved and not locked final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks1).isNotNull(); - assertThat(externalTasks1.size()).isEqualTo(1); - assertThat(externalTasks1.get(0).getWorkerId()).isNull(); - assertThat(externalTasks1.get(0).getRetries()).isNull(); + Assertions.assertThat(externalTasks1) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks1.get(0).getWorkerId()).isNull(); + Assertions.assertThat(externalTasks1.get(0).getRetries()).isNull(); // find external task and lock final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); - assertThat(locked).isNotNull(); - assertThat(locked.size()).isEqualTo(1); + Assertions.assertThat(locked) + .isNotNull() + .hasSize(1); final LockedExternalTask lockedExternalTask = locked.get(0); /* @@ -576,43 +637,57 @@ public T evaluate(Exchange exchange, Class type) { lockedExternalTask.getId()); // ensure endpoint has been called - assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); // external task is still not resolved final List externalTasks2 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks2).isNotNull(); - assertThat(externalTasks2.size()).isEqualTo(1); + Assertions.assertThat(externalTasks2) + .isNotNull() + .hasSize(1); // Exception aborted processing so retries could not be set! - assertThat(externalTasks2.get(0).getRetries()).isNull(); - assertThat(externalTasks2.get(0).getErrorMessage()).isNull(); + Assertions.assertThat(externalTasks2.get(0).getRetries()).isNull(); + Assertions.assertThat(externalTasks2.get(0).getErrorMessage()).isNull(); // assert that process not in the end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); // assert that the variables unchanged final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(3); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(3); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar"); - assertThat(variablesAsMap.containsKey("var3")).isTrue(); - assertThat(variablesAsMap.get("var3")).isEqualTo("foobar"); + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar") + .containsEntry("var3", "foobar"); /* * test common exception @@ -624,11 +699,8 @@ public T evaluate(Exchange exchange, Class type) { // variables returned but must not be set since task will not be // completed - mockEndpoint.whenAnyExchangeReceived(new Processor() { - @Override - public void process(Exchange exchange) throws Exception { - throw new Exception(FAILURE); - } + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new Exception(FAILURE); }); // call route "direct:testRoute" @@ -644,43 +716,57 @@ public void process(Exchange exchange) throws Exception { } // ensure endpoint has been called - assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); // external task is still not resolved final List externalTasks4 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks4).isNotNull(); - assertThat(externalTasks4.size()).isEqualTo(1); + Assertions.assertThat(externalTasks4) + .isNotNull() + .hasSize(1); // Exception aborted processing so retries could not be set! - assertThat(externalTasks4.get(0).getRetries()).isEqualTo(2); - assertThat(externalTasks4.get(0).getErrorMessage()).isEqualTo(FAILURE); + Assertions.assertThat(externalTasks4.get(0).getRetries()).isEqualTo(2); + Assertions.assertThat(externalTasks4.get(0).getErrorMessage()).isEqualTo(FAILURE); // assert that process not in the end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); // assert that the variables unchanged final List variables2 = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables2.size()).isEqualTo(3); - final HashMap variablesAsMap2 = new HashMap(); + Assertions.assertThat(variables2).hasSize(3); + final HashMap variablesAsMap2 = new HashMap<>(); for (final HistoricVariableInstance variable : variables2) { variablesAsMap2.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap2.containsKey("var1")).isTrue(); - assertThat(variablesAsMap2.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap2.containsKey("var2")).isTrue(); - assertThat(variablesAsMap2.get("var2")).isEqualTo("bar"); - assertThat(variablesAsMap2.containsKey("var3")).isTrue(); - assertThat(variablesAsMap2.get("var3")).isEqualTo("foobar"); + Assertions.assertThat(variablesAsMap2) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar") + .containsEntry("var3", "foobar"); // complete task to make test order not relevant externalTaskService.complete(externalTasks2.get(0).getId(), "0815"); @@ -689,37 +775,38 @@ public void process(Exchange exchange) throws Exception { @Test @Deployment(resources = { "process/StartExternalTask4.bpmn20.xml" }) - public void testSetExternalTaskRetriesAnnotation() throws Exception { - + public void testSetExternalTaskRetriesAnnotation() { // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); processVariables.put("var3", "foobar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // external task is still not resolved and not locked final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks1).isNotNull(); - assertThat(externalTasks1.size()).isEqualTo(1); - assertThat(externalTasks1.get(0).getWorkerId()).isNull(); - assertThat(externalTasks1.get(0).getRetries()).isNull(); + Assertions.assertThat(externalTasks1) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks1.get(0).getWorkerId()).isNull(); + Assertions.assertThat(externalTasks1.get(0).getRetries()).isNull(); // find external task and lock final List locked = externalTaskService.fetchAndLock(1, "0815", true).topic("topic4", 5000).execute(); - assertThat(locked).isNotNull(); - assertThat(locked.size()).isEqualTo(1); + Assertions.assertThat(locked) + .isNotNull() + .hasSize(1); final LockedExternalTask lockedExternalTask = locked.get(0); // set retries artificially externalTaskService.handleFailure(lockedExternalTask.getId(), "0815", "Blabal", 2, 0); /* - * DontChangeRetriesException + * DoNotChangeRetriesException */ mockEndpoint.reset(); @@ -728,11 +815,8 @@ public void testSetExternalTaskRetriesAnnotation() throws Exception { // variables returned but must not be set since task will not be // completed - mockEndpoint.whenAnyExchangeReceived(new Processor() { - @Override - public void process(Exchange exchange) throws Exception { - throw new DontChangeRetriesException(DONTCHANGEMSG); - } + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new DontChangeRetriesException(DONTCHANGEMSG); }); // call route "direct:testRoute" @@ -748,59 +832,67 @@ public void process(Exchange exchange) throws Exception { } // ensure endpoint has been called - assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); // external task is still not resolved final List externalTasks4 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks4).isNotNull(); - assertThat(externalTasks4.size()).isEqualTo(1); + Assertions.assertThat(externalTasks4) + .isNotNull() + .hasSize(1); // Exception aborted processing so retries could not be set! - assertThat(externalTasks4.get(0).getRetries()).isEqualTo(2); - assertThat(externalTasks4.get(0).getErrorMessage()).isEqualTo(DONTCHANGEMSG); + Assertions.assertThat(externalTasks4.get(0).getRetries()).isEqualTo(2); + Assertions.assertThat(externalTasks4.get(0).getErrorMessage()).isEqualTo(DONTCHANGEMSG); // assert that process not in the end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); // assert that the variables unchanged final List variables2 = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables2.size()).isEqualTo(3); - final HashMap variablesAsMap2 = new HashMap(); + Assertions.assertThat(variables2).hasSize(3); + final HashMap variablesAsMap2 = new HashMap<>(); for (final HistoricVariableInstance variable : variables2) { variablesAsMap2.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap2.containsKey("var1")).isTrue(); - assertThat(variablesAsMap2.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap2.containsKey("var2")).isTrue(); - assertThat(variablesAsMap2.get("var2")).isEqualTo("bar"); - assertThat(variablesAsMap2.containsKey("var3")).isTrue(); - assertThat(variablesAsMap2.get("var3")).isEqualTo("foobar"); - + Assertions.assertThat(variablesAsMap2) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar") + .containsEntry("var3", "foobar"); /* - * DontChangeRetriesException + * DoNotChangeRetriesException */ - mockEndpoint.reset(); - final String CREATEINCIDENT = "Incident"; // variables returned but must not be set since task will not be // completed - mockEndpoint.whenAnyExchangeReceived(new Processor() { - @Override - public void process(Exchange exchange) throws Exception { - throw new CreateIncidentException(CREATEINCIDENT); - } + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new CreateIncidentException(CREATEINCIDENT); }); // call route "direct:testRoute" @@ -816,60 +908,71 @@ public void process(Exchange exchange) throws Exception { } // ensure endpoint has been called - assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0)).isNotNull(); // external task is still not resolved final List externalTasks3 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks3).isNotNull(); - assertThat(externalTasks3.size()).isEqualTo(1); + Assertions.assertThat(externalTasks3) + .isNotNull() + .hasSize(1); // Exception aborted processing so retries could not be set! - assertThat(externalTasks3.get(0).getRetries()).isEqualTo(0); - assertThat(externalTasks3.get(0).getErrorMessage()).isEqualTo(CREATEINCIDENT); + Assertions.assertThat(externalTasks3.get(0).getRetries()).isZero(); + Assertions.assertThat(externalTasks3.get(0).getErrorMessage()).isEqualTo(CREATEINCIDENT); // assert that process not in the end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); // assert that the variables unchanged final List variables3 = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables3.size()).isEqualTo(3); - final HashMap variablesAsMap3 = new HashMap(); + Assertions.assertThat(variables3).hasSize(3); + final HashMap variablesAsMap3 = new HashMap<>(); for (final HistoricVariableInstance variable : variables3) { variablesAsMap3.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap3.containsKey("var1")).isTrue(); - assertThat(variablesAsMap3.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap3.containsKey("var2")).isTrue(); - assertThat(variablesAsMap3.get("var2")).isEqualTo("bar"); - assertThat(variablesAsMap3.containsKey("var3")).isTrue(); - assertThat(variablesAsMap3.get("var3")).isEqualTo("foobar"); - + Assertions.assertThat(variablesAsMap3) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar") + .containsEntry("var3", "foobar"); // complete task to make test order not relevant externalTaskService.complete(externalTasks1.get(0).getId(), "0815"); - } - @SuppressWarnings("unchecked") @Test @Deployment(resources = { "process/StartExternalTask2.bpmn20.xml" }) + @SuppressWarnings("unchecked") public void testAsyncIsTrueAndLockDuration() throws Exception { - // variables returned but must not be set since task will not be // completed mockEndpoint.returnReplyBody(new Expression() { @Override public T evaluate(Exchange exchange, Class type) { - final HashMap result = new HashMap(); + final HashMap result = new HashMap<>(); result.put("var2", "bar2"); result.put("var3", "bar3"); return (T) result; @@ -877,13 +980,13 @@ public T evaluate(Exchange exchange, Class type) { }); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); processVariables.put("var3", "foobar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess2", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // wait for the external task to be completed Thread.sleep(1000); @@ -891,58 +994,77 @@ public T evaluate(Exchange exchange, Class type) { // external task is still not resolved and locked final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks1).isNotNull(); - assertThat(externalTasks1.size()).isEqualTo(1); - assertThat(externalTasks1.get(0).getWorkerId()).isEqualTo("0815"); - assertThat(externalTasks1.get(0).getLockExpirationTime()).isAfter(new Date()); + Assertions.assertThat(externalTasks1) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks1.get(0).getWorkerId()).isEqualTo("0815"); + Assertions.assertThat(externalTasks1.get(0).getLockExpirationTime()).isAfter(new Date()); - // wait for the task to unlock and refetch by Camel + // wait for the task to unlock and re-fetch by Camel Thread.sleep(2000); // assert that the camunda BPM process instance ID has been added as a // property to the message for both exchanges received - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo( - processInstance.getId()); - assertThat(mockEndpoint.assertExchangeReceived(1).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo( - processInstance.getId()); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(1) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); // only two process instance variables are loaded according configured // value of "variablesToFetch" parameter - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody()).isNotNull(); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody()).isInstanceOf(Map.class); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class).size()).isEqualTo(2); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)).containsKey("var2"); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)).containsKey("var3"); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)).containsValue("bar"); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)).containsValue("foobar"); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody()).isNotNull(); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody()).isInstanceOf(Map.class); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)).hasSize(2); + Assertions.assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)) + .containsEntry("var2", "bar") + .containsEntry("var3", "foobar"); // assert that the variables sent in the response-message has NOT been // set into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(3); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(3); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar"); - assertThat(variablesAsMap.containsKey("var3")).isTrue(); - assertThat(variablesAsMap.get("var3")).isEqualTo("foobar"); + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar") + .containsEntry("var3", "foobar"); // assert that process NOT in end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); } @@ -950,7 +1072,6 @@ public T evaluate(Exchange exchange, Class type) { @Test @Deployment(resources = { "process/StartExternalTask.bpmn20.xml" }) public void testBpmnError() throws Exception { - // variables to be set by the Camel-endpoint processing the external // task mockEndpoint.returnReplyBody(new Expression() { @@ -961,12 +1082,12 @@ public T evaluate(Exchange exchange, Class type) { }); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // wait for the external task to be completed Thread.sleep(1000); @@ -974,69 +1095,81 @@ public T evaluate(Exchange exchange, Class type) { // external task is still not resolved final long externalTasksCount = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).active().count(); - assertThat(externalTasksCount).isEqualTo(0); + Assertions.assertThat(externalTasksCount).isZero(); // assert that the camunda BPM process instance ID has been added as a // property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo( - processInstance.getId()); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); // assert that the variables sent in the response-message has been set // into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(2); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(2); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar"); + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar"); // assert that process ended final HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId( processInstance.getId()).singleResult(); - assertThat(historicProcessInstance.getEndTime()).isNotNull(); + Assertions.assertThat(historicProcessInstance.getEndTime()).isNotNull(); // assert that process ended due to error boundary event 4711 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End4711").singleResult()).isNotNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End4711") + .singleResult()) + .isNotNull(); // assert that process not in end event "HappyEnd" - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("HappyEnd").singleResult()).isNull(); + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("HappyEnd") + .singleResult()) + .isNull(); // assert that process ended not due to error boundary event 0815 - assertThat(historyService.createHistoricActivityInstanceQuery().processInstanceId( - processInstance.getId()).activityId("End0815").singleResult()).isNull(); - + Assertions + .assertThat(historyService + .createHistoricActivityInstanceQuery() + .processInstanceId(processInstance.getId()) + .activityId("End0815") + .singleResult()) + .isNull(); } @Test @Deployment(resources = { "process/StartExternalTask.bpmn20.xml" }) public void testIncidentAndRetryTimeouts() throws Exception { - // variables to be set by the Camel-endpoint processing the external // task - mockEndpoint.whenAnyExchangeReceived(new Processor() { - @Override - public void process(final Exchange exchange) throws Exception { - throw new RuntimeException("fail!"); - } + mockEndpoint.whenAnyExchangeReceived(exchange -> { + throw new RuntimeException("fail!"); }); // count incidents for later comparison final long incidentCount = runtimeService.createIncidentQuery().count(); // start process - final Map processVariables = new HashMap(); + final Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); final ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("startExternalTaskProcess", processVariables); - assertThat(processInstance).isNotNull(); + Assertions.assertThat(processInstance).isNotNull(); // wait for the external task to be completed Thread.sleep(1000); @@ -1044,9 +1177,10 @@ public void process(final Exchange exchange) throws Exception { // external task is still not resolved final List externalTasks1 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks1).isNotNull(); - assertThat(externalTasks1.size()).isEqualTo(1); - assertThat(externalTasks1.get(0).getRetries()).isEqualTo(2); + Assertions.assertThat(externalTasks1) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks1.get(0).getRetries()).isEqualTo(2); // wait for the next try Thread.sleep(1000); @@ -1054,9 +1188,10 @@ public void process(final Exchange exchange) throws Exception { // external task is still not resolved final List externalTasks2 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks2).isNotNull(); - assertThat(externalTasks2.size()).isEqualTo(1); - assertThat(externalTasks2.get(0).getRetries()).isEqualTo(1); + Assertions.assertThat(externalTasks2) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks2.get(0).getRetries()).isEqualTo(1); // next try is 2 seconds so after 1 second nothing changes Thread.sleep(1000); @@ -1064,9 +1199,10 @@ public void process(final Exchange exchange) throws Exception { // external task is still not resolved final List externalTasks3 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks3).isNotNull(); - assertThat(externalTasks3.size()).isEqualTo(1); - assertThat(externalTasks3.get(0).getRetries()).isEqualTo(1); + Assertions.assertThat(externalTasks3) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks3.get(0).getRetries()).isEqualTo(1); // wait for the next try Thread.sleep(1000); @@ -1074,44 +1210,63 @@ public void process(final Exchange exchange) throws Exception { // external task is still not resolved final List externalTasks4 = externalTaskService.createExternalTaskQuery().processInstanceId( processInstance.getId()).list(); - assertThat(externalTasks4).isNotNull(); - assertThat(externalTasks4.size()).isEqualTo(1); - assertThat(externalTasks4.get(0).getRetries()).isEqualTo(0); + Assertions.assertThat(externalTasks4) + .isNotNull() + .hasSize(1); + Assertions.assertThat(externalTasks4.get(0).getRetries()).isZero(); // assert that the camunda BPM process instance ID has been added as a // property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo( - processInstance.getId()); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); // assert that in-headers are set properly - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getHeader(EXCHANGE_HEADER_ATTEMPTSSTARTED)).isEqualTo( - 0); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getHeader(EXCHANGE_HEADER_RETRIESLEFT)).isEqualTo(2); - assertThat(mockEndpoint.assertExchangeReceived(1).getIn().getHeader(EXCHANGE_HEADER_ATTEMPTSSTARTED)).isEqualTo( - 1); - assertThat(mockEndpoint.assertExchangeReceived(1).getIn().getHeader(EXCHANGE_HEADER_RETRIESLEFT)).isEqualTo(1); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_ATTEMPTSSTARTED)) + .isEqualTo(0); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_RETRIESLEFT)) + .isEqualTo(2); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(1) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_ATTEMPTSSTARTED)) + .isEqualTo(1); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(1) + .getIn() + .getHeader(CamundaBpmConstants.EXCHANGE_HEADER_RETRIESLEFT)) + .isEqualTo(1); // assert that the variables sent in the response-message has been set // into the process final List variables = historyService.createHistoricVariableInstanceQuery().processInstanceId( processInstance.getId()).list(); - assertThat(variables.size()).isEqualTo(2); - final HashMap variablesAsMap = new HashMap(); + Assertions.assertThat(variables).hasSize(2); + final HashMap variablesAsMap = new HashMap<>(); for (final HistoricVariableInstance variable : variables) { variablesAsMap.put(variable.getName(), variable.getValue()); } - assertThat(variablesAsMap.containsKey("var1")).isTrue(); - assertThat(variablesAsMap.get("var1")).isEqualTo("foo"); - assertThat(variablesAsMap.containsKey("var2")).isTrue(); - assertThat(variablesAsMap.get("var2")).isEqualTo("bar"); + Assertions.assertThat(variablesAsMap) + .containsEntry("var1", "foo") + .containsEntry("var2", "bar"); // assert that process not ended final HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId( processInstance.getId()).singleResult(); - assertThat(historicProcessInstance.getEndTime()).isNull(); + Assertions.assertThat(historicProcessInstance.getEndTime()).isNull(); // assert that incident raised - assertThat(runtimeService.createIncidentQuery().count()).isEqualTo(incidentCount + 1); - + Assertions.assertThat(runtimeService.createIncidentQuery().count()).isEqualTo(incidentCount + 1); } - } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ReceiveFromCamelTest.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ReceiveFromCamelTest.java index 40cd161..9e9bf6c 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ReceiveFromCamelTest.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/ReceiveFromCamelTest.java @@ -15,6 +15,7 @@ import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.assertj.core.api.Assertions; +import org.camunda.bpm.camel.component.CamundaBpmConstants; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.runtime.ProcessInstance; @@ -32,28 +33,24 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:receive-from-camel-config.xml") public class ReceiveFromCamelTest { - MockEndpoint mockEndpoint; - @Autowired(required = true) + @Autowired ApplicationContext applicationContext; - @Autowired(required = true) + @Autowired CamelContext camelContext; - @Autowired(required = true) + @Autowired RuntimeService runtimeService; - @Autowired(required = true) + @Autowired HistoryService historyService; - @Autowired(required = true) + @Autowired @Rule public ProcessEngineRule processEngineRule; @@ -65,15 +62,25 @@ public void setUp() { @Test @Deployment(resources = {"process/ReceiveFromCamel.bpmn20.xml"}) - public void doTest() throws Exception { - Map processVariables = new HashMap(); + public void doTest() { + Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("receiveFromCamelProcess", processVariables); // Verify that a process instance has executed and there is one instance executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("receiveFromCamelProcess").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("receiveFromCamelProcess").count()).isEqualTo(1); + Assertions + .assertThat(historyService + .createHistoricProcessInstanceQuery() + .processDefinitionKey("receiveFromCamelProcess") + .count()) + .isEqualTo(1); + Assertions + .assertThat(runtimeService + .createProcessInstanceQuery() + .processDefinitionKey("receiveFromCamelProcess") + .count()) + .isEqualTo(1); /* * We need the process instance ID to be able to send the message to it @@ -82,12 +89,25 @@ public void doTest() throws Exception { * http://camundabpm.blogspot.de/2013/06/introducing-activity-instance-model-to.html */ ProducerTemplate tpl = camelContext.createProducerTemplate(); - tpl.sendBodyAndProperty("direct:sendToCamundaBpm", null, EXCHANGE_HEADER_PROCESS_INSTANCE_ID, processInstance.getId()); + tpl.sendBodyAndProperty( + "direct:sendToCamundaBpm", + null, + CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID, + processInstance.getId()); // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo(processInstance.getId()); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); // Assert that the process instance is finished - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("receiveFromCamelProcess").count()).isEqualTo(0); + Assertions + .assertThat(runtimeService + .createProcessInstanceQuery() + .processDefinitionKey("receiveFromCamelProcess") + .count()) + .isZero(); } } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SendToCamelTest.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SendToCamelTest.java index bdd2899..24b8d68 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SendToCamelTest.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SendToCamelTest.java @@ -14,6 +14,7 @@ import org.apache.camel.CamelContext; import org.apache.camel.component.mock.MockEndpoint; import org.assertj.core.api.Assertions; +import org.camunda.bpm.camel.component.CamundaBpmConstants; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.runtime.ProcessInstance; @@ -31,28 +32,25 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:send-to-camel-config.xml") public class SendToCamelTest { MockEndpoint mockEndpoint; - @Autowired(required = true) + @Autowired ApplicationContext applicationContext; - @Autowired(required = true) + @Autowired CamelContext camelContext; - @Autowired(required = true) + @Autowired RuntimeService runtimeService; - @Autowired(required = true) + @Autowired HistoryService historyService; - @Autowired(required = true) + @Autowired @Rule public ProcessEngineRule processEngineRule; @@ -64,21 +62,39 @@ public void setUp() { @Test @Deployment(resources = {"process/SendToCamel.bpmn20.xml"}) - public void doTest() throws Exception { - Map processVariables = new HashMap(); + public void doTest() { + Map processVariables = new HashMap<>(); processVariables.put("var1", "foo"); processVariables.put("var2", "bar"); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("sendToCamelProcess", processVariables); // Verify that a process instance was executed and there are no instances executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("sendToCamelProcess").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("sendToCamelProcess").count()).isEqualTo(0); + Assertions + .assertThat(historyService + .createHistoricProcessInstanceQuery() + .processDefinitionKey("sendToCamelProcess") + .count()) + .isEqualTo(1); + Assertions + .assertThat(runtimeService + .createProcessInstanceQuery() + .processDefinitionKey("sendToCamelProcess") + .count()) + .isZero(); // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo(processInstance.getId()); + Assertions.assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstance.getId()); // Assert that the body of the message received by the endpoint contains a hash map with the value of the process variable 'var1' sent from camunda BPM - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo("{var1=foo}"); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(String.class)) + .isEqualTo("{var1=foo}"); // FIXME: check that var2 is also present as a property! } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SmokeTest.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SmokeTest.java index 3760551..10ffa03 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SmokeTest.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/SmokeTest.java @@ -2,7 +2,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.assertj.core.api.Assertions; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.task.Task; @@ -15,15 +14,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:smoke-test-config.xml") public class SmokeTest { - @Autowired(required = true) + @Autowired RuntimeService runtimeService; - @Autowired(required = true) + @Autowired TaskService taskService; @Autowired @@ -32,12 +30,12 @@ public class SmokeTest { @Test @Deployment(resources = {"process/SmokeTest.bpmn20.xml"} ) - public void smokeTest() throws Exception { + public void smokeTest() { runtimeService.startProcessInstanceByKey("smokeTestProcess"); Task task = taskService.createTaskQuery().singleResult(); - assertThat("My Task").isEqualTo(task.getName()); + assertThat(task.getName()).isEqualTo("My Task"); taskService.complete(task.getId()); - assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(0); + assertThat(runtimeService.createProcessInstanceQuery().count()).isZero(); } } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/StartProcessFromRouteTest.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/StartProcessFromRouteTest.java index 205079f..512d0c3 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/StartProcessFromRouteTest.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/StartProcessFromRouteTest.java @@ -17,6 +17,7 @@ import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.assertj.core.api.Assertions; +import org.camunda.bpm.camel.component.CamundaBpmConstants; import org.camunda.bpm.engine.HistoryService; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.test.Deployment; @@ -32,9 +33,6 @@ import java.util.Collections; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; - @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:start-process-from-route-config.xml") public class StartProcessFromRouteTest { @@ -42,16 +40,16 @@ public class StartProcessFromRouteTest { MockEndpoint mockEndpoint; MockEndpoint processVariableEndpoint; - @Autowired(required = true) + @Autowired CamelContext camelContext; - @Autowired(required = true) + @Autowired RuntimeService runtimeService; - @Autowired(required = true) + @Autowired HistoryService historyService; - @Autowired(required = true) + @Autowired @Rule public ProcessEngineRule processEngineRule; @@ -65,97 +63,197 @@ public void setUp() { @Test @Deployment(resources = {"process/StartProcessFromRoute.bpmn20.xml"}) - public void doTest() throws Exception { + public void doTest() { ProducerTemplate tpl = camelContext.createProducerTemplate(); String processInstanceId = (String) tpl.requestBody("direct:start", Collections.singletonMap("var1", "valueOfVar1")); - assertThat(processInstanceId).isNotNull(); + Assertions.assertThat(processInstanceId).isNotNull(); System.out.println("Process instance ID: " + processInstanceId); // Verify that a process instance was executed and there are no instances executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(0); + Assertions + .assertThat(historyService + .createHistoricProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute") + .count()) + .isEqualTo(1); + Assertions + .assertThat(runtimeService + .createProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute") + .count()) + .isZero(); // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isEqualTo(processInstanceId); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isEqualTo(processInstanceId); - // The body of the message comming out from the camunda-bpm: endpoint is the process instance - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo(processInstanceId); + // The body of the message coming out from the camunda-bpm: endpoint is the process instance + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(String.class)) + .isEqualTo(processInstanceId); // We should receive a hash map as the body of the message with a 'var1' key - assertThat(processVariableEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo("{var1=valueOfVar1}"); + Assertions + .assertThat(processVariableEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(String.class)) + .isEqualTo("{var1=valueOfVar1}"); } @Test @Deployment(resources = {"process/StartProcessFromRoute.bpmn20.xml"}) - public void doTestReturnVariable() throws Exception { + public void doTestReturnVariable() { ProducerTemplate tpl = camelContext.createProducerTemplate(); String var1 = (String) tpl.requestBody("direct:startReturnVariable", Collections.singletonMap("var1", "valueOfVar1")); - assertThat(var1).isNotNull(); + Assertions.assertThat(var1).isNotNull(); // Verify that a process instance was executed and there are no instances executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(0); + Assertions + .assertThat(historyService + .createHistoricProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute") + .count()) + .isEqualTo(1); + Assertions + .assertThat(runtimeService + .createProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute") + .count()) + .isZero(); // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isNotNull(); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isNotNull(); - // The body of the message comming out from the camunda-bpm: endpoint is the process instance - assertThat(var1).isEqualTo("valueOfVar1"); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo(var1); + // The body of the message coming out from the camunda-bpm: endpoint is the process instance + Assertions.assertThat(var1).isEqualTo("valueOfVar1"); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(String.class)) + .isEqualTo(var1); // We should receive a hash map as the body of the message with a 'var1' key - assertThat(processVariableEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo("{var1=valueOfVar1}"); + Assertions + .assertThat(processVariableEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(String.class)) + .isEqualTo("{var1=valueOfVar1}"); } @Test @Deployment(resources = {"process/StartProcessFromRoute.bpmn20.xml"}) - public void doTestReturnVariables() throws Exception { + @SuppressWarnings("unchecked") + public void doTestReturnVariables() { ProducerTemplate tpl = camelContext.createProducerTemplate(); Map vars = (Map) tpl.requestBody("direct:startReturnVariables", Collections.singletonMap("var1", "valueOfVar1")); - assertThat(vars).isNotNull(); + Assertions.assertThat(vars).isNotNull(); // Verify that a process instance was executed and there are no instances executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(0); + Assertions + .assertThat(historyService + .createHistoricProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute" + ).count()) + .isEqualTo(1); + Assertions + .assertThat(runtimeService + .createProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute") + .count()) + .isZero(); // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isNotNull(); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isNotNull(); - // The body of the message comming out from the camunda-bpm: endpoint is the process instance - assertThat(vars).isNotNull(); - assertThat(vars.size()).isEqualTo(1); - assertThat(vars.get("var1")).isEqualTo("valueOfVar1"); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)).isEqualTo(vars); + // The body of the message coming out from the camunda-bpm: endpoint is the process instance + Assertions.assertThat(vars) + .isNotNull() + .hasSize(1) + .containsEntry("var1", "valueOfVar1"); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(Map.class)) + .isEqualTo(vars); // We should receive a hash map as the body of the message with a 'var1' key - assertThat(processVariableEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo("{var1=valueOfVar1}"); + Assertions + .assertThat(processVariableEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(String.class)) + .isEqualTo("{var1=valueOfVar1}"); } @Test @Deployment(resources = {"process/StartProcessFromRoute.bpmn20.xml"}) - public void doTestReturnAllVariables() throws Exception { + @SuppressWarnings("unchecked") + public void doTestReturnAllVariables() { ProducerTemplate tpl = camelContext.createProducerTemplate(); Map vars = (Map) tpl.requestBody("direct:startReturnAllVariables", Collections.singletonMap("var1", "valueOfVar1")); - assertThat(vars).isNotNull(); + Assertions.assertThat(vars).isNotNull(); // Verify that a process instance was executed and there are no instances executing now - assertThat(historyService.createHistoricProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(1); - assertThat(runtimeService.createProcessInstanceQuery().processDefinitionKey("startProcessFromRoute").count()).isEqualTo(0); + Assertions + .assertThat(historyService + .createHistoricProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute") + .count()) + .isEqualTo(1); + Assertions + .assertThat(runtimeService + .createProcessInstanceQuery() + .processDefinitionKey("startProcessFromRoute") + .count()) + .isZero(); // Assert that the camunda BPM process instance ID has been added as a property to the message - assertThat(mockEndpoint.assertExchangeReceived(0).getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID)).isNotNull(); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getProperty(CamundaBpmConstants.EXCHANGE_HEADER_PROCESS_INSTANCE_ID)) + .isNotNull(); - // The body of the message comming out from the camunda-bpm: endpoint is the process instance - assertThat(vars).isNotNull(); - assertThat(vars.size()).isEqualTo(1); - assertThat(vars.get("var1")).isEqualTo("valueOfVar1"); - assertThat(mockEndpoint.assertExchangeReceived(0).getIn().getBody(Map.class)).isEqualTo(vars); + // The body of the message coming out from the camunda-bpm: endpoint is the process instance + Assertions.assertThat(vars) + .isNotNull() + .hasSize(1) + .containsEntry("var1", "valueOfVar1"); + Assertions + .assertThat(mockEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(Map.class)) + .isEqualTo(vars); // We should receive a hash map as the body of the message with a 'var1' key - assertThat(processVariableEndpoint.assertExchangeReceived(0).getIn().getBody(String.class)).isEqualTo("{var1=valueOfVar1}"); + Assertions + .assertThat(processVariableEndpoint + .assertExchangeReceived(0) + .getIn() + .getBody(String.class)) + .isEqualTo("{var1=valueOfVar1}"); } } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenService.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenService.java index dff79bb..6e42508 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenService.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenService.java @@ -22,7 +22,6 @@ * */ public class BrokenService { - private static final Logger LOG = LoggerFactory.getLogger(BrokenService.class); /** @@ -35,5 +34,4 @@ public void alwaysFails() throws BrokenServiceException { LOG.info("{} called", this.getClass().getSimpleName()); throw new BrokenServiceException("Provoked failure"); } - } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenServiceException.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenServiceException.java index 1969a58..c2fff46 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenServiceException.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/BrokenServiceException.java @@ -18,11 +18,9 @@ * */ public class BrokenServiceException extends Exception { - private static final long serialVersionUID = 1L; public BrokenServiceException(String message) { super(message); } - } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyExecutionListener.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyExecutionListener.java index c4ceb9a..b278186 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyExecutionListener.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyExecutionListener.java @@ -5,14 +5,12 @@ /** * Attach to the ReceiveTask (end event). - * - * @author stefan.schulze@accelsis.biz * + * @author stefan.schulze@accelsis.biz */ public class DummyExecutionListener implements ExecutionListener { - - @Override - public void notify(DelegateExecution execution) throws Exception { - // dummy - } + @Override + public void notify(DelegateExecution execution) { + // dummy + } } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyJavaDelegate.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyJavaDelegate.java index 8e380b1..b504b1f 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyJavaDelegate.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/DummyJavaDelegate.java @@ -10,10 +10,8 @@ * */ public class DummyJavaDelegate implements JavaDelegate { - @Override - public void execute(DelegateExecution execution) throws Exception { + public void execute(DelegateExecution execution) { // dummy } - } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/InitDelegate.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/InitDelegate.java index fbb09e0..1e6110c 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/InitDelegate.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/InitDelegate.java @@ -5,10 +5,8 @@ import static org.camunda.bpm.camel.component.CamundaBpmConstants.*; public class InitDelegate implements JavaDelegate { - @Override public void execute(DelegateExecution execution) throws Exception { execution.setVariable(EXCHANGE_HEADER_PROCESS_INSTANCE_ID, execution.getProcessInstanceId()); } - } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/Routing.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/Routing.java index b61d380..897481c 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/Routing.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/Routing.java @@ -7,12 +7,11 @@ * */ public enum Routing { - /** * Process should terminate normally. */ DEFAULT, - + /** * Camel route should throw an exception and propagate it back to the caller. */ @@ -22,5 +21,4 @@ public enum Routing { * Camel route should throw an exception and handle it. */ HANDLE_ERROR; - } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/SleepBean.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/SleepBean.java index a92d8b9..b4ce98e 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/SleepBean.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/SleepBean.java @@ -3,7 +3,6 @@ import org.apache.camel.Exchange; public class SleepBean { - public void sleep(String body, Exchange exchange) throws Exception { Thread.sleep(1500); } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TestJoinDelegate.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TestJoinDelegate.java index 9dc20e4..96f6474 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TestJoinDelegate.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TestJoinDelegate.java @@ -4,10 +4,8 @@ import org.camunda.bpm.engine.delegate.JavaDelegate; public class TestJoinDelegate implements JavaDelegate { - @Override public void execute(DelegateExecution execution) throws Exception { // dummy task } - } diff --git a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TimeConsumingService.java b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TimeConsumingService.java index 7e6be78..a08cfe8 100644 --- a/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TimeConsumingService.java +++ b/camunda-bpm-camel-spring/src/test/java/org/camunda/bpm/camel/spring/util/TimeConsumingService.java @@ -7,7 +7,6 @@ * */ public class TimeConsumingService { - /** * Spend some time. * @@ -16,5 +15,4 @@ public class TimeConsumingService { public void doWork() throws InterruptedException { Thread.sleep(100); } - } diff --git a/pom.xml b/pom.xml index d8ca3e7..e4091ad 100644 --- a/pom.xml +++ b/pom.xml @@ -16,29 +16,31 @@ pom - 11 + 17 ${java.version} ${java.version} - 7.16.0 - 3.16.0 - 5.3.19 - 1.7.36 + 7.21.0-alpha4 + 4.4.0 + 6.1.3 + 2.0.12 - 4.13.2 - 3.23.1 - 2.28.2 - 2.0.9 + 5.10.2 + 3.25.3 + 5.11.0 + + 1.4.197 - - 3.3.2 + + 3.6.3 camunda-bpm-camel-common camunda-bpm-camel-common-tests camunda-bpm-camel-spring + camunda-bpm-camel-quarkus-cdi @@ -75,6 +77,13 @@ camunda-bpm-camel-spring ${project.version} + + org.junit + junit-bom + ${junit.version} + pom + import + @@ -145,7 +154,7 @@ false - camunda-bpm-camel-cdi + camunda-bpm-camel-quarkus-cdi